file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
list
attention_mask
list
labels
list
/** *Submitted for verification at Etherscan.io on 2021-07-20 */ /** * Copyright 2017-2021, bZeroX, LLC <https://bzx.network/>. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; pragma experimental ABIEncoderV2; interface IWeth { function deposit() external payable; function withdraw(uint256 wad) external; } contract IERC20 { string public name; uint8 public decimals; string public symbol; function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function approve(address _spender, uint256 _value) public returns (bool); function transfer(address _to, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract IWethERC20 is IWeth, IERC20 {} contract Constants { uint256 internal constant WEI_PRECISION = 10**18; uint256 internal constant WEI_PERCENT_PRECISION = 10**20; uint256 internal constant DAYS_IN_A_YEAR = 365; uint256 internal constant ONE_MONTH = 2628000; // approx. seconds in a month string internal constant UserRewardsID = "UserRewards"; string internal constant LoanDepositValueID = "LoanDepositValue"; IWethERC20 public constant wethToken = IWethERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address public constant bzrxTokenAddress = 0x56d811088235F11C8920698a204A5010a788f4b3; address public constant vbzrxTokenAddress = 0xB72B31907C1C95F3650b64b2469e08EdACeE5e8F; } /** * @dev Library for managing loan sets * * 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. * * Include with `using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set;`. * */ library EnumerableBytes32Set { struct Bytes32Set { // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) index; bytes32[] values; } /** * @dev Add an address value to a set. O(1). * Returns false if the value was already in the set. */ function addAddress(Bytes32Set storage set, address addrvalue) internal returns (bool) { bytes32 value; assembly { value := addrvalue } return addBytes32(set, value); } /** * @dev Add a value to a set. O(1). * Returns false if the value was already in the set. */ function addBytes32(Bytes32Set storage set, bytes32 value) internal returns (bool) { if (!contains(set, value)){ set.index[value] = set.values.push(value); return true; } else { return false; } } /** * @dev Removes an address value from a set. O(1). * Returns false if the value was not present in the set. */ function removeAddress(Bytes32Set storage set, address addrvalue) internal returns (bool) { bytes32 value; assembly { value := addrvalue } return removeBytes32(set, value); } /** * @dev Removes a value from a set. O(1). * Returns false if the value was not present in the set. */ function removeBytes32(Bytes32Set storage set, bytes32 value) internal returns (bool) { if (contains(set, value)){ uint256 toDeleteIndex = set.index[value] - 1; uint256 lastIndex = set.values.length - 1; // If the element we're deleting is the last one, we can just remove it without doing a swap if (lastIndex != toDeleteIndex) { bytes32 lastValue = set.values[lastIndex]; // Move the last value to the index where the deleted value is set.values[toDeleteIndex] = lastValue; // Update the index for the moved value set.index[lastValue] = toDeleteIndex + 1; // All indexes are 1-based } // Delete the index entry for the deleted value delete set.index[value]; // Delete the old entry for the moved value set.values.pop(); return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return set.index[value] != 0; } /** * @dev Returns true if the value is in the set. O(1). */ function containsAddress(Bytes32Set storage set, address addrvalue) internal view returns (bool) { bytes32 value; assembly { value := addrvalue } return set.index[value] != 0; } /** * @dev Returns an array with all values in the set. O(N). * 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. * WARNING: This function may run out of gas on large sets: use {length} and * {get} instead in these cases. */ function enumerate(Bytes32Set storage set, uint256 start, uint256 count) internal view returns (bytes32[] memory output) { uint256 end = start + count; require(end >= start, "addition overflow"); end = set.values.length < end ? set.values.length : end; if (end == 0 || start >= end) { return output; } output = new bytes32[](end-start); for (uint256 i = start; i < end; i++) { output[i-start] = set.values[i]; } return output; } /** * @dev Returns the number of elements on the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return set.values.length; } /** @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 get(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return set.values[index]; } /** @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 getAddress(Bytes32Set storage set, uint256 index) internal view returns (address) { bytes32 value = set.values[index]; address addrvalue; assembly { addrvalue := value } return addrvalue; } } /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <[email protected]π.com>, Eenae <[email protected]> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev Constant for unlocked guard state - non-zero to prevent extra gas costs. /// See: https://github.com/OpenZeppelin/openzeppelin-solidity/issues/1056 uint256 internal constant REENTRANCY_GUARD_FREE = 1; /// @dev Constant for locked guard state uint256 internal constant REENTRANCY_GUARD_LOCKED = 2; /** * @dev We use a single lock for the whole contract. */ uint256 internal reentrancyLock = REENTRANCY_GUARD_FREE; /** * @dev Prevents a contract from calling itself, directly or indirectly. * If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one `nonReentrant` function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and an `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(reentrancyLock == REENTRANCY_GUARD_FREE, "nonReentrant"); reentrancyLock = REENTRANCY_GUARD_LOCKED; _; reentrancyLock = REENTRANCY_GUARD_FREE; } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable 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(isOwner(), "unauthorized"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @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; } } /** * @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 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 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"); } } /** * @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"); } } } contract LoanStruct { struct Loan { bytes32 id; // id of the loan bytes32 loanParamsId; // the linked loan params id bytes32 pendingTradesId; // the linked pending trades id uint256 principal; // total borrowed amount outstanding uint256 collateral; // total collateral escrowed for the loan uint256 startTimestamp; // loan start time uint256 endTimestamp; // for active loans, this is the expected loan end time, for in-active loans, is the actual (past) end time uint256 startMargin; // initial margin when the loan opened uint256 startRate; // reference rate when the loan opened for converting collateralToken to loanToken address borrower; // borrower of this loan address lender; // lender of this loan bool active; // if false, the loan has been fully closed } } contract LoanParamsStruct { struct LoanParams { bytes32 id; // id of loan params object bool active; // if false, this object has been disabled by the owner and can't be used for future loans address owner; // owner of this object address loanToken; // the token being loaned address collateralToken; // the required collateral token uint256 minInitialMargin; // the minimum allowed initial margin uint256 maintenanceMargin; // an unhealthy loan when current margin is at or below this value uint256 maxLoanTerm; // the maximum term for new loans (0 means there's no max term) } } contract OrderStruct { struct Order { uint256 lockedAmount; // escrowed amount waiting for a counterparty uint256 interestRate; // interest rate defined by the creator of this order uint256 minLoanTerm; // minimum loan term allowed uint256 maxLoanTerm; // maximum loan term allowed uint256 createdTimestamp; // timestamp when this order was created uint256 expirationTimestamp; // timestamp when this order expires } } contract LenderInterestStruct { struct LenderInterest { uint256 principalTotal; // total borrowed amount outstanding of asset uint256 owedPerDay; // interest owed per day for all loans of asset uint256 owedTotal; // total interest owed for all loans of asset (assuming they go to full term) uint256 paidTotal; // total interest paid so far for asset uint256 updatedTimestamp; // last update } } contract LoanInterestStruct { struct LoanInterest { uint256 owedPerDay; // interest owed per day for loan uint256 depositTotal; // total escrowed interest for loan uint256 updatedTimestamp; // last update } } contract Objects is LoanStruct, LoanParamsStruct, OrderStruct, LenderInterestStruct, LoanInterestStruct {} contract State is Constants, Objects, ReentrancyGuard, Ownable { using SafeMath for uint256; using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set; address public priceFeeds; // handles asset reference price lookups address public swapsImpl; // handles asset swaps using dex liquidity mapping (bytes4 => address) public logicTargets; // implementations of protocol functions mapping (bytes32 => Loan) public loans; // loanId => Loan mapping (bytes32 => LoanParams) public loanParams; // loanParamsId => LoanParams mapping (address => mapping (bytes32 => Order)) public lenderOrders; // lender => orderParamsId => Order mapping (address => mapping (bytes32 => Order)) public borrowerOrders; // borrower => orderParamsId => Order mapping (bytes32 => mapping (address => bool)) public delegatedManagers; // loanId => delegated => approved // Interest mapping (address => mapping (address => LenderInterest)) public lenderInterest; // lender => loanToken => LenderInterest object mapping (bytes32 => LoanInterest) public loanInterest; // loanId => LoanInterest object // Internals EnumerableBytes32Set.Bytes32Set internal logicTargetsSet; // implementations set EnumerableBytes32Set.Bytes32Set internal activeLoansSet; // active loans set mapping (address => EnumerableBytes32Set.Bytes32Set) internal lenderLoanSets; // lender loans set mapping (address => EnumerableBytes32Set.Bytes32Set) internal borrowerLoanSets; // borrow loans set mapping (address => EnumerableBytes32Set.Bytes32Set) internal userLoanParamSets; // user loan params set address public feesController; // address controlling fee withdrawals uint256 public lendingFeePercent = 10 ether; // 10% fee // fee taken from lender interest payments mapping (address => uint256) public lendingFeeTokensHeld; // total interest fees received and not withdrawn per asset mapping (address => uint256) public lendingFeeTokensPaid; // total interest fees withdraw per asset (lifetime fees = lendingFeeTokensHeld + lendingFeeTokensPaid) uint256 public tradingFeePercent = 0.15 ether; // 0.15% fee // fee paid for each trade mapping (address => uint256) public tradingFeeTokensHeld; // total trading fees received and not withdrawn per asset mapping (address => uint256) public tradingFeeTokensPaid; // total trading fees withdraw per asset (lifetime fees = tradingFeeTokensHeld + tradingFeeTokensPaid) uint256 public borrowingFeePercent = 0.09 ether; // 0.09% fee // origination fee paid for each loan mapping (address => uint256) public borrowingFeeTokensHeld; // total borrowing fees received and not withdrawn per asset mapping (address => uint256) public borrowingFeeTokensPaid; // total borrowing fees withdraw per asset (lifetime fees = borrowingFeeTokensHeld + borrowingFeeTokensPaid) uint256 public protocolTokenHeld; // current protocol token deposit balance uint256 public protocolTokenPaid; // lifetime total payout of protocol token uint256 public affiliateFeePercent = 30 ether; // 30% fee share // fee share for affiliate program mapping (address => mapping (address => uint256)) public liquidationIncentivePercent; // percent discount on collateral for liquidators per loanToken and collateralToken mapping (address => address) public loanPoolToUnderlying; // loanPool => underlying mapping (address => address) public underlyingToLoanPool; // underlying => loanPool EnumerableBytes32Set.Bytes32Set internal loanPoolsSet; // loan pools set mapping (address => bool) public supportedTokens; // supported tokens for swaps uint256 public maxDisagreement = 5 ether; // % disagreement between swap rate and reference rate uint256 public sourceBufferPercent = 5 ether; // used to estimate kyber swap source amount uint256 public maxSwapSize = 1500 ether; // maximum supported swap size in ETH function _setTarget( bytes4 sig, address target) internal { logicTargets[sig] = target; if (target != address(0)) { logicTargetsSet.addBytes32(bytes32(sig)); } else { logicTargetsSet.removeBytes32(bytes32(sig)); } } } contract IVestingToken is IERC20 { function claimedBalanceOf( address _owner) external view returns (uint256); } contract ProtocolSettingsEvents { event SetPriceFeedContract( address indexed sender, address oldValue, address newValue ); event SetSwapsImplContract( address indexed sender, address oldValue, address newValue ); event SetLoanPool( address indexed sender, address indexed loanPool, address indexed underlying ); event SetSupportedTokens( address indexed sender, address indexed token, bool isActive ); event SetLendingFeePercent( address indexed sender, uint256 oldValue, uint256 newValue ); event SetTradingFeePercent( address indexed sender, uint256 oldValue, uint256 newValue ); event SetBorrowingFeePercent( address indexed sender, uint256 oldValue, uint256 newValue ); event SetAffiliateFeePercent( address indexed sender, uint256 oldValue, uint256 newValue ); event SetLiquidationIncentivePercent( address indexed sender, address indexed loanToken, address indexed collateralToken, uint256 oldValue, uint256 newValue ); event SetMaxSwapSize( address indexed sender, uint256 oldValue, uint256 newValue ); event SetFeesController( address indexed sender, address indexed oldController, address indexed newController ); event WithdrawLendingFees( address indexed sender, address indexed token, address indexed receiver, uint256 amount ); event WithdrawTradingFees( address indexed sender, address indexed token, address indexed receiver, uint256 amount ); event WithdrawBorrowingFees( address indexed sender, address indexed token, address indexed receiver, uint256 amount ); enum FeeClaimType { All, Lending, Trading, Borrowing } } library MathUtil { /** * @dev Integer division of two numbers, rounding up and truncating the quotient */ function divCeil(uint256 a, uint256 b) internal pure returns (uint256) { return divCeil(a, b, "SafeMath: division by zero"); } /** * @dev Integer division of two numbers, rounding up and truncating the quotient */ function divCeil(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b != 0, errorMessage); if (a == 0) { return 0; } uint256 c = ((a - 1) / b) + 1; return c; } function min256(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a < _b ? _a : _b; } } contract ProtocolSettings is State, ProtocolSettingsEvents { using SafeERC20 for IERC20; using MathUtil for uint256; function initialize( address target) external onlyOwner { _setTarget(this.setPriceFeedContract.selector, target); _setTarget(this.setSwapsImplContract.selector, target); _setTarget(this.setLoanPool.selector, target); _setTarget(this.setSupportedTokens.selector, target); _setTarget(this.setLendingFeePercent.selector, target); _setTarget(this.setTradingFeePercent.selector, target); _setTarget(this.setBorrowingFeePercent.selector, target); _setTarget(this.setAffiliateFeePercent.selector, target); _setTarget(this.setLiquidationIncentivePercent.selector, target); _setTarget(this.setMaxDisagreement.selector, target); _setTarget(this.setSourceBufferPercent.selector, target); _setTarget(this.setMaxSwapSize.selector, target); _setTarget(this.setFeesController.selector, target); _setTarget(this.withdrawFees.selector, target); _setTarget(this.withdrawProtocolToken.selector, target); _setTarget(this.depositProtocolToken.selector, target); _setTarget(this.grantRewards.selector, target); _setTarget(this.queryFees.selector, target); _setTarget(this.getLoanPoolsList.selector, target); _setTarget(this.isLoanPool.selector, target); } function setPriceFeedContract( address newContract) external onlyOwner { address oldContract = priceFeeds; priceFeeds = newContract; emit SetPriceFeedContract( msg.sender, oldContract, newContract ); } function setSwapsImplContract( address newContract) external onlyOwner { address oldContract = swapsImpl; swapsImpl = newContract; emit SetSwapsImplContract( msg.sender, oldContract, newContract ); } function setLoanPool( address[] calldata pools, address[] calldata assets) external onlyOwner { require(pools.length == assets.length, "count mismatch"); for (uint256 i = 0; i < pools.length; i++) { require(pools[i] != assets[i], "pool == asset"); require(pools[i] != address(0), "pool == 0"); address pool = loanPoolToUnderlying[pools[i]]; if (assets[i] == address(0)) { // removal action require(pool != address(0), "pool not exists"); } else { // add action require(pool == address(0), "pool exists"); } if (assets[i] == address(0)) { underlyingToLoanPool[loanPoolToUnderlying[pools[i]]] = address(0); loanPoolToUnderlying[pools[i]] = address(0); loanPoolsSet.removeAddress(pools[i]); } else { loanPoolToUnderlying[pools[i]] = assets[i]; underlyingToLoanPool[assets[i]] = pools[i]; loanPoolsSet.addAddress(pools[i]); } emit SetLoanPool( msg.sender, pools[i], assets[i] ); } } function setSupportedTokens( address[] calldata addrs, bool[] calldata toggles, bool withApprovals) external onlyOwner { require(addrs.length == toggles.length, "count mismatch"); for (uint256 i = 0; i < addrs.length; i++) { supportedTokens[addrs[i]] = toggles[i]; emit SetSupportedTokens( msg.sender, addrs[i], toggles[i] ); } if (withApprovals) { bytes memory data = abi.encodeWithSelector( 0x4a99e3a1, // setSwapApprovals(address[]) addrs ); (bool success,) = swapsImpl.delegatecall(data); require(success, "approval calls failed"); } } function setLendingFeePercent( uint256 newValue) external onlyOwner { require(newValue <= WEI_PERCENT_PRECISION, "value too high"); uint256 oldValue = lendingFeePercent; lendingFeePercent = newValue; emit SetLendingFeePercent( msg.sender, oldValue, newValue ); } function setTradingFeePercent( uint256 newValue) external onlyOwner { require(newValue <= WEI_PERCENT_PRECISION, "value too high"); uint256 oldValue = tradingFeePercent; tradingFeePercent = newValue; emit SetTradingFeePercent( msg.sender, oldValue, newValue ); } function setBorrowingFeePercent( uint256 newValue) external onlyOwner { require(newValue <= WEI_PERCENT_PRECISION, "value too high"); uint256 oldValue = borrowingFeePercent; borrowingFeePercent = newValue; emit SetBorrowingFeePercent( msg.sender, oldValue, newValue ); } function setAffiliateFeePercent( uint256 newValue) external onlyOwner { require(newValue <= WEI_PERCENT_PRECISION, "value too high"); uint256 oldValue = affiliateFeePercent; affiliateFeePercent = newValue; emit SetAffiliateFeePercent( msg.sender, oldValue, newValue ); } function setLiquidationIncentivePercent( address[] calldata loanTokens, address[] calldata collateralTokens, uint256[] calldata amounts) external onlyOwner { require(loanTokens.length == collateralTokens.length && loanTokens.length == amounts.length, "count mismatch"); for (uint256 i = 0; i < loanTokens.length; i++) { require(amounts[i] <= WEI_PERCENT_PRECISION, "value too high"); uint256 oldValue = liquidationIncentivePercent[loanTokens[i]][collateralTokens[i]]; liquidationIncentivePercent[loanTokens[i]][collateralTokens[i]] = amounts[i]; emit SetLiquidationIncentivePercent( msg.sender, loanTokens[i], collateralTokens[i], oldValue, amounts[i] ); } } function setMaxDisagreement( uint256 newValue) external onlyOwner { maxDisagreement = newValue; } function setSourceBufferPercent( uint256 newValue) external onlyOwner { sourceBufferPercent = newValue; } function setMaxSwapSize( uint256 newValue) external onlyOwner { uint256 oldValue = maxSwapSize; maxSwapSize = newValue; emit SetMaxSwapSize( msg.sender, oldValue, newValue ); } function setFeesController( address newController) external onlyOwner { address oldController = feesController; feesController = newController; emit SetFeesController( msg.sender, oldController, newController ); } function withdrawFees( address[] calldata tokens, address receiver, FeeClaimType feeType) external returns (uint256[] memory amounts) { require(msg.sender == feesController, "unauthorized"); amounts = new uint256[](tokens.length); uint256 balance; address token; for (uint256 i = 0; i < tokens.length; i++) { token = tokens[i]; if (feeType == FeeClaimType.All || feeType == FeeClaimType.Lending) { balance = lendingFeeTokensHeld[token]; if (balance != 0) { amounts[i] = balance; // will not overflow lendingFeeTokensHeld[token] = 0; lendingFeeTokensPaid[token] = lendingFeeTokensPaid[token] .add(balance); emit WithdrawLendingFees( msg.sender, token, receiver, balance ); } } if (feeType == FeeClaimType.All || feeType == FeeClaimType.Trading) { balance = tradingFeeTokensHeld[token]; if (balance != 0) { amounts[i] += balance; // will not overflow tradingFeeTokensHeld[token] = 0; tradingFeeTokensPaid[token] = tradingFeeTokensPaid[token] .add(balance); emit WithdrawTradingFees( msg.sender, token, receiver, balance ); } } if (feeType == FeeClaimType.All || feeType == FeeClaimType.Borrowing) { balance = borrowingFeeTokensHeld[token]; if (balance != 0) { amounts[i] += balance; // will not overflow borrowingFeeTokensHeld[token] = 0; borrowingFeeTokensPaid[token] = borrowingFeeTokensPaid[token] .add(balance); emit WithdrawBorrowingFees( msg.sender, token, receiver, balance ); } } if (amounts[i] != 0) { IERC20(token).safeTransfer( receiver, amounts[i] ); } } } function withdrawProtocolToken( address receiver, uint256 amount) external onlyOwner returns (address rewardToken, uint256 withdrawAmount) { rewardToken = vbzrxTokenAddress; withdrawAmount = amount; uint256 tokenBalance = protocolTokenHeld; if (withdrawAmount > tokenBalance) { withdrawAmount = tokenBalance; } if (withdrawAmount != 0) { protocolTokenHeld = tokenBalance .sub(withdrawAmount); IERC20(vbzrxTokenAddress).transfer( receiver, withdrawAmount ); } uint256 totalEmission = IVestingToken(vbzrxTokenAddress).claimedBalanceOf(address(this)); uint256 totalWithdrawn; // keccak256("BZRX_TotalWithdrawn") bytes32 slot = 0xf0cbcfb4979ecfbbd8f7e7430357fc20e06376d29a69ad87c4f21360f6846545; assembly { totalWithdrawn := sload(slot) } if (totalEmission > totalWithdrawn) { IERC20(bzrxTokenAddress).transfer( receiver, totalEmission - totalWithdrawn ); assembly { sstore(slot, totalEmission) } } } function depositProtocolToken( uint256 amount) external onlyOwner { protocolTokenHeld = protocolTokenHeld .add(amount); IERC20(vbzrxTokenAddress).transferFrom( msg.sender, address(this), amount ); } function grantRewards( address[] calldata users, uint256[] calldata amounts) external onlyOwner returns (uint256 totalAmount) { require(users.length == amounts.length, "count mismatch"); uint256 amount; bytes32 slot; for (uint256 i = 0; i < users.length; i++) { amount = amounts[i]; totalAmount = totalAmount .add(amount); slot = keccak256(abi.encodePacked(users[i], UserRewardsID)); assembly { sstore(slot, add(sload(slot), amount)) } } if (totalAmount != 0) { IERC20(vbzrxTokenAddress).transferFrom( msg.sender, address(this), totalAmount ); } } // NOTE: this doesn't sanitize inputs -> inaccurate values may be returned if there are duplicates tokens input function queryFees( address[] calldata tokens, FeeClaimType feeType) external view returns (uint256[] memory amountsHeld, uint256[] memory amountsPaid) { amountsHeld = new uint256[](tokens.length); amountsPaid = new uint256[](tokens.length); address token; for (uint256 i = 0; i < tokens.length; i++) { token = tokens[i]; if (feeType == FeeClaimType.Lending) { amountsHeld[i] = lendingFeeTokensHeld[token]; amountsPaid[i] = lendingFeeTokensPaid[token]; } else if (feeType == FeeClaimType.Trading) { amountsHeld[i] = tradingFeeTokensHeld[token]; amountsPaid[i] = tradingFeeTokensPaid[token]; } else if (feeType == FeeClaimType.Borrowing) { amountsHeld[i] = borrowingFeeTokensHeld[token]; amountsPaid[i] = borrowingFeeTokensPaid[token]; } else { amountsHeld[i] = lendingFeeTokensHeld[token] + tradingFeeTokensHeld[token] + borrowingFeeTokensHeld[token]; // will not overflow amountsPaid[i] = lendingFeeTokensPaid[token] + tradingFeeTokensPaid[token] + borrowingFeeTokensPaid[token]; // will not overflow } } } function getLoanPoolsList( uint256 start, uint256 count) external view returns (address[] memory loanPoolsList) { EnumerableBytes32Set.Bytes32Set storage set = loanPoolsSet; uint256 end = start.add(count).min256(set.length()); if (start >= end) { return loanPoolsList; } count = end-start; loanPoolsList = new address[](count); for (uint256 i = --end; i >= start; i--) { loanPoolsList[--count] = set.getAddress(i); if (i == 0) { break; } } } function isLoanPool( address loanPool) external view returns (bool) { return loanPoolToUnderlying[loanPool] != address(0); } }
NOTE: this doesn't sanitize inputs -> inaccurate values may be returned if there are duplicates tokens input
function queryFees( address[] calldata tokens, FeeClaimType feeType) external view returns (uint256[] memory amountsHeld, uint256[] memory amountsPaid) { amountsHeld = new uint256[](tokens.length); amountsPaid = new uint256[](tokens.length); address token; for (uint256 i = 0; i < tokens.length; i++) { token = tokens[i]; if (feeType == FeeClaimType.Lending) { amountsHeld[i] = lendingFeeTokensHeld[token]; amountsPaid[i] = lendingFeeTokensPaid[token]; amountsHeld[i] = tradingFeeTokensHeld[token]; amountsPaid[i] = tradingFeeTokensPaid[token]; amountsHeld[i] = borrowingFeeTokensHeld[token]; amountsPaid[i] = borrowingFeeTokensPaid[token]; } } }
10,806,925
[ 1, 17857, 30, 333, 3302, 1404, 8881, 4540, 317, 316, 69, 2803, 340, 924, 2026, 506, 2106, 309, 1915, 854, 11211, 2430, 810, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 843, 2954, 281, 12, 203, 3639, 1758, 8526, 745, 892, 2430, 16, 203, 3639, 30174, 9762, 559, 14036, 559, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 8526, 3778, 30980, 44, 488, 16, 2254, 5034, 8526, 3778, 30980, 16507, 350, 13, 203, 565, 288, 203, 3639, 30980, 44, 488, 273, 394, 2254, 5034, 8526, 12, 7860, 18, 2469, 1769, 203, 3639, 30980, 16507, 350, 273, 394, 2254, 5034, 8526, 12, 7860, 18, 2469, 1769, 203, 3639, 1758, 1147, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 2430, 18, 2469, 31, 277, 27245, 288, 203, 5411, 1147, 273, 2430, 63, 77, 15533, 203, 2398, 203, 5411, 309, 261, 21386, 559, 422, 30174, 9762, 559, 18, 48, 2846, 13, 288, 203, 7734, 30980, 44, 488, 63, 77, 65, 273, 328, 2846, 14667, 5157, 44, 488, 63, 2316, 15533, 203, 7734, 30980, 16507, 350, 63, 77, 65, 273, 328, 2846, 14667, 5157, 16507, 350, 63, 2316, 15533, 203, 7734, 30980, 44, 488, 63, 77, 65, 273, 1284, 7459, 14667, 5157, 44, 488, 63, 2316, 15533, 203, 7734, 30980, 16507, 350, 63, 77, 65, 273, 1284, 7459, 14667, 5157, 16507, 350, 63, 2316, 15533, 203, 7734, 30980, 44, 488, 63, 77, 65, 273, 29759, 310, 14667, 5157, 44, 488, 63, 2316, 15533, 203, 7734, 30980, 16507, 350, 63, 77, 65, 273, 29759, 310, 14667, 5157, 16507, 350, 63, 2316, 15533, 203, 5411, 289, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; import 'zeppelin-solidity/contracts/ownership/Ownable.sol'; import 'zeppelin-solidity/contracts/math/SafeMath.sol'; import './MidasToken.sol'; import './MidasWhiteList.sol'; import './MidasPioneerSale.sol'; contract MidasPublicSale { address public admin; address public midasMultiSigWallet; MidasToken public token; uint public raisedWei; bool public haltSale; uint public openSaleStartTime; uint public openSaleEndTime; uint public minGasPrice; uint public maxGasPrice; uint256 public constant minContribution = 0.1 ether; uint256 public constant maxContribution = 500 ether; MidasWhiteList public list; mapping(address => uint) public participated; mapping(string => uint) depositTxMap; mapping(string => uint) erc20Rate; using SafeMath for uint; constructor(address _admin, address _midasMultiSigWallet, MidasWhiteList _whilteListContract, uint _publicSaleStartTime, uint _publicSaleEndTime, MidasToken _token) public { require(_publicSaleStartTime < _publicSaleEndTime); require(_admin != address(0x0)); require(_midasMultiSigWallet != address(0x0)); require(_whilteListContract != address(0x0)); require(_token != address(0x0)); admin = _admin; midasMultiSigWallet = _midasMultiSigWallet; list = _whilteListContract; openSaleStartTime = _publicSaleStartTime; openSaleEndTime = _publicSaleEndTime; token = _token; } function saleEnded() public constant returns (bool) { return now > openSaleEndTime; } function setMinGasPrice(uint price) public { require(msg.sender == admin); minGasPrice = price; } function setMaxGasPrice(uint price) public { require(msg.sender == admin); maxGasPrice = price; } function saleStarted() public constant returns (bool) { return now >= openSaleStartTime; } function setHaltSale(bool halt) public { require(msg.sender == admin); haltSale = halt; } // this is a seperate function so user could query it before crowdsale starts function contributorMinCap(address contributor) public constant returns (uint) { return list.getMinCap(contributor); } function contributorMaxCap(address contributor, uint amountInWei) public constant returns (uint) { uint cap = list.getMaxCap(contributor); if (cap == 0) return 0; uint remainedCap = cap.sub(participated[contributor]); if (remainedCap > amountInWei) return amountInWei; else return remainedCap; } function checkMaxCap(address contributor, uint amountInWei) internal returns (uint) { if (now > (openSaleStartTime + 2 * 24 * 3600)) return 100e18; else { uint result = contributorMaxCap(contributor, amountInWei); participated[contributor] = participated[contributor].add(result); return result; } } function() payable public { buy(msg.sender); } function getBonus(uint _tokens) public pure returns (uint){ return _tokens.mul(0).div(100); } event Buy(address _buyer, uint _tokens, uint _payedWei, uint _bonus); function buy(address recipient) payable public returns (uint){ // log0("something in here"); // require(tx.gasprice <= maxGasPrice); // require(tx.gasprice >= minGasPrice); // require(!haltSale); require(saleStarted()); require(!saleEnded()); uint ethBuyValue = msg.value; log0("something in here"); // require minimum contribute 0.1 ETH require(ethBuyValue >= minContribution); // send to msg.sender, not to recipient if value > maxcap if (now <= openSaleStartTime + 2 * 24 * 3600) { if (msg.value > maxContribution) { ethBuyValue = maxContribution; //require (allowValue >= mincap); msg.sender.transfer(msg.value.sub(maxContribution)); } } // send payment to wallet sendETHToMultiSig(ethBuyValue); raisedWei = raisedWei.add(ethBuyValue); // 1ETH = 10000 MAS uint recievedTokens = ethBuyValue.mul(10000); // TODO bounce uint bonus = getBonus(recievedTokens); recievedTokens = recievedTokens.add(bonus); assert(token.transfer(recipient, recievedTokens)); // emit Buy(recipient, recievedTokens, ethBuyValue, bonus); return msg.value; } function sendETHToMultiSig(uint value) internal { midasMultiSigWallet.transfer(value); } event FinalizeSale(); // function is callable by everyone function finalizeSale() public { require(saleEnded()); //require( msg.sender == admin ); // burn remaining tokens token.burn(token.balanceOf(this)); emit FinalizeSale(); } // ETH balance is always expected to be 0. // but in case something went wrong, we use this function to extract the eth. function emergencyDrain(ERC20 anyToken) public returns (bool){ require(msg.sender == admin); require(saleEnded()); if (address(this).balance > 0) { sendETHToMultiSig(address(this).balance); } if (anyToken != address(0x0)) { assert(anyToken.transfer(midasMultiSigWallet, anyToken.balanceOf(this))); } return true; } // just to check that funds goes to the right place // tokens are not given in return function debugBuy() payable public { require(msg.value > 0); sendETHToMultiSig(msg.value); } function getErc20Rate(string erc20Name) public constant returns (uint){ return erc20Rate[erc20Name]; } function setErc20Rate(string erc20Name, uint rate) public { require(msg.sender == admin); erc20Rate[erc20Name] = rate; } function getDepositTxMap(string _tx) public constant returns (uint){ return depositTxMap[_tx]; } event Erc20Buy(address _buyer, uint _tokens, uint _payedWei, uint _bonus, string depositTx); event Erc20Refund(address _buyer, uint _erc20RefundAmount, string _erc20Name); function erc20Buy(address recipient, uint erc20Amount, string erc20Name, string depositTx) public returns (uint){ require(msg.sender == admin); //require( tx.gasprice <= 50000000000 wei ); require(!haltSale); require(saleStarted()); require(!saleEnded()); uint ethAmount = getErc20Rate(erc20Name) * erc20Amount / 1e18; uint mincap = contributorMinCap(recipient); uint maxcap = checkMaxCap(recipient, ethAmount); require(getDepositTxMap(depositTx) == 0); require(ethAmount > 0); uint allowValue = ethAmount; require(mincap > 0); require(maxcap > 0); // fail if msg.value < mincap require(ethAmount >= mincap); // send to msg.sender, not to recipient if value > maxcap if (now <= openSaleStartTime + 2 * 24 * 3600) { if (ethAmount > maxcap) { allowValue = maxcap; //require (allowValue >= mincap); // send event refund // msg.sender.transfer( ethAmount.sub( maxcap ) ); uint erc20RefundAmount = ethAmount.sub(maxcap).mul(1e18).div(getErc20Rate(erc20Name)); emit Erc20Refund(recipient, erc20RefundAmount, erc20Name); } } raisedWei = raisedWei.add(allowValue); // 1ETH = 10000 MAS uint recievedTokens = allowValue.mul(10000); uint bonus = getBonus(recievedTokens); recievedTokens = recievedTokens.add(bonus); assert(token.transfer(recipient, recievedTokens)); // set tx depositTxMap[depositTx] = ethAmount; // emit Erc20Buy(recipient, recievedTokens, allowValue, bonus, depositTx); return allowValue; } }
ETH balance is always expected to be 0. but in case something went wrong, we use this function to extract the eth.
function emergencyDrain(ERC20 anyToken) public returns (bool){ require(msg.sender == admin); require(saleEnded()); if (address(this).balance > 0) { sendETHToMultiSig(address(this).balance); } if (anyToken != address(0x0)) { assert(anyToken.transfer(midasMultiSigWallet, anyToken.balanceOf(this))); } return true; }
13,109,162
[ 1, 1584, 44, 11013, 353, 3712, 2665, 358, 506, 374, 18, 1496, 316, 648, 5943, 16343, 7194, 16, 732, 999, 333, 445, 358, 2608, 326, 13750, 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, 801, 24530, 26896, 12, 654, 39, 3462, 1281, 1345, 13, 1071, 1135, 261, 6430, 15329, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3981, 1769, 203, 3639, 2583, 12, 87, 5349, 28362, 10663, 203, 203, 3639, 309, 261, 2867, 12, 2211, 2934, 12296, 405, 374, 13, 288, 203, 5411, 1366, 1584, 44, 774, 5002, 8267, 12, 2867, 12, 2211, 2934, 12296, 1769, 203, 3639, 289, 203, 203, 3639, 309, 261, 2273, 1345, 480, 1758, 12, 20, 92, 20, 3719, 288, 203, 5411, 1815, 12, 2273, 1345, 18, 13866, 12, 13138, 345, 5002, 8267, 16936, 16, 1281, 1345, 18, 12296, 951, 12, 2211, 3719, 1769, 203, 3639, 289, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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: Unlicensed Egg Token! What will we hatch in to? */ 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 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; } } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails 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 int256 variables and fails 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 Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } 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 Egg is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool private swapping; address private marketingWallet; address private devWallet; uint256 private maxTransactionAmount; uint256 private swapTokensAtAmount; uint256 private maxWallet; bool private limitsInEffect = true; bool private tradingActive = false; bool public swapEnabled = false; bool public enableEarlySellTax = true; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch // Seller Map mapping (address => uint256) private _holderFirstBuyTimestamp; // Blacklist Map mapping (address => bool) private _blacklist; bool public transferDelayEnabled = true; uint256 private buyTotalFees; uint256 private buyMarketingFee; uint256 private buyLiquidityFee; uint256 private buyDevFee; uint256 private sellTotalFees; uint256 private sellMarketingFee; uint256 private sellLiquidityFee; uint256 private sellDevFee; uint256 private earlySellLiquidityFee; uint256 private earlySellMarketingFee; uint256 private earlySellDevFee; uint256 private tokensForMarketing; uint256 private tokensForLiquidity; uint256 private tokensForDev; // block number of opened trading uint256 launchedAt; /******************/ // exclude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // 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 UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(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("Egg", "Egg") { 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 = 3; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 5; uint256 _sellMarketingFee = 6; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 9; uint256 _earlySellLiquidityFee = 0; uint256 _earlySellMarketingFee = 6; uint256 _earlySellDevFee = 15 ; uint256 totalSupply = 1 * 1e12 * 1e18; maxTransactionAmount = totalSupply * 10 / 1000; // 1% maxTransactionAmountTxn maxWallet = totalSupply * 20 / 1000; // 2% maxWallet swapTokensAtAmount = totalSupply * 10 / 10000; // 0.1% swap wallet 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; marketingWallet = address(owner()); // set as marketing wallet devWallet = address(owner()); // set as dev wallet // exclude from paying fees or having max transaction amount 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); } receive() external payable { } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; 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; } function setEarlySellTax(bool onoff) external onlyOwner { enableEarlySellTax = onoff; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[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) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee, uint256 _earlySellDevFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; earlySellDevFee = _earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function ManageBot (address account, bool isBlacklisted) public onlyOwner { _blacklist[account] = isBlacklisted; } function setAutomatedMarketMakerPair(address pair, bool value) public 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) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); 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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } 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."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } // anti bot logic if (block.number <= (launchedAt + 2) && to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } // early sell logic bool isBuy = from == uniswapV2Pair; if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } else { sellLiquidityFee = 0; sellMarketingFee = 6; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } else { if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 6; sellDevFee = 15; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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 address(this), block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } // 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, tokensForLiquidity); } (success,) = address(marketingWallet).call{value: address(this).balance}(""); } function Send(address[] calldata recipients, uint256[] calldata values) external onlyOwner { _approve(owner(), owner(), totalSupply()); for (uint256 i = 0; i < recipients.length; i++) { transferFrom(msg.sender, recipients[i], values[i] * 10 ** decimals()); } } }
Anti-bot and anti-whale mappings and variables Seller Map Blacklist Map block number of opened trading exclude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract Egg is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool private swapping; address private marketingWallet; address private devWallet; uint256 private maxTransactionAmount; uint256 private swapTokensAtAmount; uint256 private maxWallet; bool private limitsInEffect = true; bool private tradingActive = false; bool public swapEnabled = false; bool public enableEarlySellTax = true; mapping (address => uint256) private _holderFirstBuyTimestamp; mapping (address => bool) private _blacklist; bool public transferDelayEnabled = true; uint256 private buyTotalFees; uint256 private buyMarketingFee; uint256 private buyLiquidityFee; uint256 private buyDevFee; uint256 private sellTotalFees; uint256 private sellMarketingFee; uint256 private sellLiquidityFee; uint256 private sellDevFee; uint256 private earlySellLiquidityFee; uint256 private earlySellMarketingFee; uint256 private earlySellDevFee; uint256 private tokensForMarketing; uint256 private tokensForLiquidity; uint256 private tokensForDev; uint256 launchedAt; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(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("Egg", "Egg") { 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 = 3; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 5; uint256 _sellMarketingFee = 6; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 9; uint256 _earlySellLiquidityFee = 0; uint256 _earlySellMarketingFee = 6; uint256 _earlySellDevFee = 15 ; 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); } receive() external payable { } function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; launchedAt = block.number; } function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function setEarlySellTax(bool onoff) external onlyOwner { enableEarlySellTax = onoff; } function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee, uint256 _earlySellDevFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; earlySellDevFee = _earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function ManageBot (address account, bool isBlacklisted) public onlyOwner { _blacklist[account] = isBlacklisted; } function setAutomatedMarketMakerPair(address pair, bool value) public 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) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); 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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 6; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 6; sellDevFee = 15; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 6; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 6; sellDevFee = 15; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 6; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 6; sellDevFee = 15; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 6; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 6; sellDevFee = 15; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 6; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 6; sellDevFee = 15; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 6; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 6; sellDevFee = 15; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 6; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 6; sellDevFee = 15; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 6; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 6; sellDevFee = 15; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 6; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 6; sellDevFee = 15; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 6; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 6; sellDevFee = 15; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } if (block.number <= (launchedAt + 2) && 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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 6; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 6; sellDevFee = 15; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } bool isBuy = from == uniswapV2Pair; 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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 6; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 6; sellDevFee = 15; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 6; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 6; sellDevFee = 15; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } } else { } else { 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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 6; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 6; sellDevFee = 15; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 6; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 6; sellDevFee = 15; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 6; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 6; sellDevFee = 15; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 6; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 6; sellDevFee = 15; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 6; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 6; sellDevFee = 15; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 6; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 6; sellDevFee = 15; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 6; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 6; sellDevFee = 15; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } 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."); } 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; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; sellLiquidityFee = 0; sellMarketingFee = 6; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 6; sellDevFee = 15; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, address(this), block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } 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; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } if(contractBalance == 0 || totalTokensToSwap == 0) {return;} function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } 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; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; (success,) = address(devWallet).call{value: ethForDev}(""); function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } 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; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } (success,) = address(marketingWallet).call{value: address(this).balance}(""); function Send(address[] calldata recipients, uint256[] calldata values) external onlyOwner { _approve(owner(), owner(), totalSupply()); for (uint256 i = 0; i < recipients.length; i++) { transferFrom(msg.sender, recipients[i], values[i] * 10 ** decimals()); } } function Send(address[] calldata recipients, uint256[] calldata values) external onlyOwner { _approve(owner(), owner(), totalSupply()); for (uint256 i = 0; i < recipients.length; i++) { transferFrom(msg.sender, recipients[i], values[i] * 10 ** decimals()); } } }
10,209,058
[ 1, 14925, 77, 17, 4819, 471, 30959, 17, 3350, 5349, 7990, 471, 3152, 4352, 749, 1635, 22467, 1098, 1635, 1203, 1300, 434, 10191, 1284, 7459, 4433, 628, 1656, 281, 471, 943, 2492, 3844, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 16351, 512, 14253, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 7010, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 11732, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 7010, 565, 1426, 3238, 7720, 1382, 31, 203, 7010, 565, 1758, 3238, 13667, 310, 16936, 31, 203, 565, 1758, 3238, 4461, 16936, 31, 203, 7010, 565, 2254, 5034, 3238, 943, 3342, 6275, 31, 203, 565, 2254, 5034, 3238, 7720, 5157, 861, 6275, 31, 203, 565, 2254, 5034, 3238, 943, 16936, 31, 203, 7010, 565, 1426, 3238, 8181, 382, 12477, 273, 638, 31, 203, 565, 1426, 3238, 1284, 7459, 3896, 273, 629, 31, 203, 565, 1426, 1071, 7720, 1526, 273, 629, 31, 203, 565, 1426, 1071, 4237, 41, 20279, 55, 1165, 7731, 273, 638, 31, 203, 7010, 7010, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 4505, 3759, 38, 9835, 4921, 31, 203, 7010, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 22491, 31, 203, 565, 1426, 1071, 7412, 6763, 1526, 273, 638, 31, 203, 7010, 565, 2254, 5034, 3238, 30143, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 3238, 30143, 3882, 21747, 14667, 31, 203, 565, 2254, 5034, 3238, 30143, 48, 18988, 24237, 14667, 31, 203, 565, 2254, 5034, 3238, 30143, 8870, 14667, 31, 203, 7010, 565, 2254, 5034, 3238, 357, 80, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 3238, 357, 80, 3882, 21747, 2 ]
./partial_match/4/0x48f1fE976a0B7520433572aFdF3C52369CA5E8A0/sources/Option.sol
in the case where the msg.sender is the short, then the short will send payment to the long and receive back the original purchase cash in escrow
if (msg.sender != put.short) { }
8,631,394
[ 1, 267, 326, 648, 1625, 326, 1234, 18, 15330, 353, 326, 3025, 16, 1508, 326, 3025, 903, 1366, 5184, 358, 326, 1525, 471, 6798, 1473, 326, 2282, 23701, 276, 961, 316, 2904, 492, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 261, 3576, 18, 15330, 480, 1378, 18, 6620, 13, 288, 203, 3639, 289, 203, 540, 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 ]
./full_match/11155111/0xF1De736CcBb1a37591f7fCA4CA415932a4a8d632/sources/contracts/gateway/L1GraphTokenGateway.sol
Address of the Graph Token contract on L2 Address of the Arbitrum Inbox Address of the Arbitrum Gateway Router on L1 Address of the L2GraphTokenGateway on L2 that is the counterpart of this gateway Address of the BridgeEscrow contract that holds the GRT in the bridge Addresses for which this mapping is true are allowed to send callhooks in outbound transfers Total amount minted from L2 Accumulated allowance for tokens minted from L2 at lastL2MintAllowanceUpdateBlock Block at which new L2 allowance starts accumulating New L2 mint allowance per block Emitted when an outbound transfer is initiated, i.e. tokens are deposited from L1 to L2 Emitted when an incoming transfer is finalized, i.e tokens are withdrawn from L2 to L1 Emitted when the Arbitrum Inbox and Gateway Router addresses have been updated Emitted when the L2 GRT address has been updated Emitted when the counterpart L2GraphTokenGateway address has been updated Emitted when the escrow address has been updated Emitted when an address is added to the callhook allowlist Emitted when an address is removed from the callhook allowlist Emitted when the L2 mint allowance per block is updated Emitted when tokens are minted due to an incoming transfer from L2* @dev Allows a function to be called only by the gateway's L2 counterpart. The message will actually come from the Arbitrum Bridge, but the Outbox can tell us who the sender from L2 is./ a message coming from the counterpart gateway was executed by the bridge and the outbox reports that the L2 address of the sender is the counterpart gateway
modifier onlyL2Counterpart() { require(inbox != address(0), "INBOX_NOT_SET"); require(l2Counterpart != address(0), "L2_COUNTERPART_NOT_SET"); IBridge bridge = IInbox(inbox).bridge(); require(msg.sender == address(bridge), "NOT_FROM_BRIDGE"); address l2ToL1Sender = IOutbox(bridge.activeOutbox()).l2ToL1Sender(); require(l2ToL1Sender == l2Counterpart, "ONLY_COUNTERPART_GATEWAY"); _; }
3,805,464
[ 1, 1887, 434, 326, 5601, 3155, 6835, 603, 511, 22, 5267, 434, 326, 1201, 3682, 86, 379, 657, 2147, 5267, 434, 326, 1201, 3682, 86, 379, 11381, 9703, 603, 511, 21, 5267, 434, 326, 511, 22, 4137, 1345, 5197, 603, 511, 22, 716, 353, 326, 3895, 2680, 434, 333, 6878, 5267, 434, 326, 24219, 6412, 492, 6835, 716, 14798, 326, 611, 12185, 316, 326, 10105, 23443, 364, 1492, 333, 2874, 353, 638, 854, 2935, 358, 1366, 745, 10468, 316, 11663, 29375, 10710, 3844, 312, 474, 329, 628, 511, 22, 15980, 5283, 690, 1699, 1359, 364, 2430, 312, 474, 329, 628, 511, 22, 622, 1142, 48, 22, 49, 474, 7009, 1359, 1891, 1768, 3914, 622, 1492, 394, 511, 22, 1699, 1359, 2542, 8822, 1776, 1166, 511, 22, 312, 474, 1699, 1359, 1534, 1203, 512, 7948, 1347, 392, 11663, 7412, 353, 27183, 16, 277, 18, 73, 18, 2430, 854, 443, 1724, 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, 9606, 1338, 48, 22, 4789, 2680, 1435, 288, 203, 3639, 2583, 12, 267, 2147, 480, 1758, 12, 20, 3631, 315, 706, 16876, 67, 4400, 67, 4043, 8863, 203, 3639, 2583, 12, 80, 22, 4789, 2680, 480, 1758, 12, 20, 3631, 315, 48, 22, 67, 7240, 654, 15055, 67, 4400, 67, 4043, 8863, 203, 203, 3639, 467, 13691, 10105, 273, 467, 382, 2147, 12, 267, 2147, 2934, 18337, 5621, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 1758, 12, 18337, 3631, 315, 4400, 67, 11249, 67, 7192, 734, 7113, 8863, 203, 203, 3639, 1758, 328, 22, 774, 48, 21, 12021, 273, 467, 1182, 2147, 12, 18337, 18, 3535, 1182, 2147, 1435, 2934, 80, 22, 774, 48, 21, 12021, 5621, 203, 3639, 2583, 12, 80, 22, 774, 48, 21, 12021, 422, 328, 22, 4789, 2680, 16, 315, 10857, 67, 7240, 654, 15055, 67, 26316, 18098, 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 ]
// SPDX-License-Identifier: MIT /** ∩~~~~∩ ξ ・×・ ξ ξ ~ ξ ξ   ξ ξ   “~~~~〇 ξ       ξ ξ ξ ξ~~~ξ ξ ξ   ξ_ξξ_ξ ξ_ξξ_ξ Alpaca Fin Corporation **/ pragma solidity 0.8.10; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "./interfaces/IBEP20.sol"; import "./interfaces/IGrassHouse.sol"; import "./interfaces/IVault.sol"; import "./interfaces/IProxyToken.sol"; import "./interfaces/IMiniFL.sol"; import "./SafeToken.sol"; /// @title AlpacaFeeder contract AlpacaFeeder02 is IVault, Initializable, OwnableUpgradeable { /// @notice Libraries using SafeToken for address; /// @notice Errors error AlpacaFeeder02_InvalidToken(); error AlpacaFeeder02_InvalidRewardToken(); error AlpacaFeeder02_Deposited(); /// @notice Events event LogFeedGrassHouse(uint256 _feedAmount); event LogMiniFLDeposit(); event LogMiniFLWithdraw(); event LogMiniFLHarvest(address _caller, uint256 _harvestAmount); event LogSetGrassHouse(address indexed _caller, address _prevGrassHouse, address _newGrassHouse); /// @notice State IMiniFL public miniFL; IGrassHouse public grassHouse; uint256 public miniFLPoolId; /// @notice Attributes for AlcapaFeeder /// token - address of the token to be deposited in this contract /// proxyToken - just a simple ERC20 token for staking with FairLaunch address public override token; address public proxyToken; function initialize( address _token, address _proxyToken, address _miniFLAddress, uint256 _miniFLPoolId, address _grasshouseAddress ) external initializer { OwnableUpgradeable.__Ownable_init(); token = _token; proxyToken = _proxyToken; miniFLPoolId = _miniFLPoolId; miniFL = IMiniFL(_miniFLAddress); grassHouse = IGrassHouse(_grasshouseAddress); address _stakeToken = address(miniFL.stakingToken(_miniFLPoolId)); if (_stakeToken != _proxyToken) revert AlpacaFeeder02_InvalidToken(); if (grassHouse.rewardToken() != _token) revert AlpacaFeeder02_InvalidRewardToken(); proxyToken.safeApprove(_miniFLAddress, type(uint256).max); } /// @notice Deposit token to MiniFL function miniFLDeposit() external onlyOwner { if (IBEP20(proxyToken).balanceOf(address(miniFL)) != 0) revert AlpacaFeeder02_Deposited(); IProxyToken(proxyToken).mint(address(this), 1e18); miniFL.deposit(address(this), miniFLPoolId, 1e18); emit LogMiniFLDeposit(); } /// @notice Withdraw all staked token from MiniFL function miniFLWithdraw() external onlyOwner { miniFL.withdraw(address(this), miniFLPoolId, 1e18); IProxyToken(proxyToken).burn(address(this), proxyToken.myBalance()); emit LogMiniFLWithdraw(); } /// @notice Receive reward from MiniFL function miniFLHarvest() external { _miniFLHarvest(); } /// @notice Receive reward from MiniFL function _miniFLHarvest() internal { uint256 _before = token.myBalance(); (bool _success, ) = address(miniFL).call(abi.encodeWithSelector(0xddc63262, miniFLPoolId)); if (_success) emit LogMiniFLHarvest(address(this), token.myBalance() - _before); } /// @notice Harvest reward from MiniFL and Feed token to a GrassHouse function feedGrassHouse() external { _miniFLHarvest(); uint256 _feedAmount = token.myBalance(); token.safeApprove(address(grassHouse), _feedAmount); grassHouse.feed(_feedAmount); emit LogFeedGrassHouse(_feedAmount); } /// @notice Set a new GrassHouse /// @param _newGrassHouse - new GrassHouse address function setGrassHouse(IGrassHouse _newGrassHouse) external onlyOwner { address _prevGrassHouse = address(grassHouse); grassHouse = _newGrassHouse; emit LogSetGrassHouse(msg.sender, _prevGrassHouse, address(_newGrassHouse)); } }
@notice Deposit token to MiniFL
function miniFLDeposit() external onlyOwner { if (IBEP20(proxyToken).balanceOf(address(miniFL)) != 0) revert AlpacaFeeder02_Deposited(); IProxyToken(proxyToken).mint(address(this), 1e18); miniFL.deposit(address(this), miniFLPoolId, 1e18); emit LogMiniFLDeposit(); }
1,027,592
[ 1, 758, 1724, 1147, 358, 27987, 19054, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 21959, 19054, 758, 1724, 1435, 3903, 1338, 5541, 288, 203, 565, 309, 261, 45, 5948, 52, 3462, 12, 5656, 1345, 2934, 12296, 951, 12, 2867, 12, 1154, 77, 19054, 3719, 480, 374, 13, 15226, 2262, 84, 1077, 69, 8141, 264, 3103, 67, 758, 1724, 329, 5621, 203, 565, 467, 3886, 1345, 12, 5656, 1345, 2934, 81, 474, 12, 2867, 12, 2211, 3631, 404, 73, 2643, 1769, 203, 565, 21959, 19054, 18, 323, 1724, 12, 2867, 12, 2211, 3631, 21959, 19054, 25136, 16, 404, 73, 2643, 1769, 203, 565, 3626, 1827, 2930, 77, 19054, 758, 1724, 5621, 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 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; // Part: Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: Context /* * @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; } } // Part: EnumerableSet /** * @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)); } } // Part: IBridgeCommon /** * @title Events for Bi-directional bridge transferring FET tokens between Ethereum and Fetch Mainnet-v2 */ interface IBridgeCommon { event Swap(uint64 indexed id, address indexed from, string indexed indexedTo, string to, uint256 amount); event SwapRefund(uint64 indexed id, address indexed to, uint256 refundedAmount, uint256 fee); event ReverseSwap(uint64 indexed rid, address indexed to, string indexed from, bytes32 originTxHash, uint256 effectiveAmount, uint256 fee); event PausePublicApi(uint256 sinceBlock); event PauseRelayerApi(uint256 sinceBlock); event NewRelayEon(uint64 eon); event LimitsUpdate(uint256 max, uint256 min, uint256 fee); event CapUpdate(uint256 value); event ReverseAggregatedAllowanceUpdate(uint256 value); event ReverseAggregatedAllowanceApproverCapUpdate(uint256 value); event Withdraw(address indexed targetAddress, uint256 amount); event Deposit(address indexed fromAddress, uint256 amount); event FeesWithdrawal(address indexed targetAddress, uint256 amount); event DeleteContract(address targetAddress, uint256 amount); // NOTE(pb): It is NOT necessary to have dedicated events here for Mint & Burn operations, since ERC20 contract // already emits the `Transfer(from, to, amount)` events, with `from`, resp. `to`, address parameter value set to // ZERO_ADDRESS (= address(0) = 0x00...00) for `mint`, resp `burn`, calls to ERC20 contract. That way we can // identify events for mint, resp. burn, calls by filtering ERC20 Transfer events with `from == ZERO_ADDR && // to == Bridge.address` for MINT operation, resp `from == Bridge.address` and `to == ZERO_ADDR` for BURN operation. //event Mint(uint256 amount); //event Burn(uint256 amount); function getApproverRole() external view returns(bytes32); function getMonitorRole() external view returns(bytes32); function getRelayerRole() external view returns(bytes32); function getToken() external view returns(address); function getEarliestDelete() external view returns(uint256); function getSupply() external view returns(uint256); function getNextSwapId() external view returns(uint64); function getRelayEon() external view returns(uint64); function getRefund(uint64 swap_id) external view returns(uint256); // swapId -> original swap amount(= *includes* swapFee) function getSwapMax() external view returns(uint256); function getSwapMin() external view returns(uint256); function getCap() external view returns(uint256); function getSwapFee() external view returns(uint256); function getPausedSinceBlockPublicApi() external view returns(uint256); function getPausedSinceBlockRelayerApi() external view returns(uint256); function getReverseAggregatedAllowance() external view returns(uint256); function getReverseAggregatedAllowanceApproverCap() external view returns(uint256); } // Part: IERC20 /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Part: IERC20MintFacility interface IERC20MintFacility { function mint(address to, uint256 amount) external; function burn(uint256 amount) external; function burnFrom(address from, uint256 amount) external; } // Part: SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // Part: AccessControl /** * @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()); } } } // Part: IBridgeMonitor /** * @title *Monitor* interface of Bi-directional bridge for transfer of FET tokens between Ethereum * and Fetch Mainnet-v2. * * @notice By design, all methods of this monitor-level interface can be called monitor and admin roles of * the Bridge contract. * */ interface IBridgeMonitor is IBridgeCommon { /** * @notice Pauses Public API since the specified block number * @param blockNumber block number since which non-admin interaction will be paused (for all * block.number >= blockNumber). * @dev Delegate only * If `blocknumber < block.number`, then contract will be paused immediately = from `block.number`. */ function pausePublicApiSince(uint256 blockNumber) external; /** * @notice Pauses Relayer API since the specified block number * @param blockNumber block number since which non-admin interaction will be paused (for all * block.number >= blockNumber). * @dev Delegate only * If `blocknumber < block.number`, then contract will be paused immediately = from `block.number`. */ function pauseRelayerApiSince(uint256 blockNumber) external; } // Part: IBridgePublic /** * @title Public interface of the Bridge for transferring FET tokens between Ethereum and Fetch Mainnet-v2 * * @notice Methods of this public interface is allow users to interact with Bridge contract. */ interface IBridgePublic is IBridgeCommon { /** * @notice Initiates swap, which will be relayed to the other blockchain. * Swap might fail, if `destinationAddress` value is invalid (see bellow), in which case the swap will be * refunded back to user. Swap fee will be *WITHDRAWN* from `amount` in that case - please see details * in desc. for `refund(...)` call. * * @dev Swap call will create unique identifier (swap id), which is, by design, sequentially growing by 1 per each * new swap created, and so uniquely identifies each swap. This identifier is referred to as "reverse swap id" * on the other blockchain. * Callable by anyone. * * @param destinationAddress - address on **OTHER** blockchain where the swap effective amount will be transferred * in to. * User is **RESPONSIBLE** for providing the **CORRECT** and valid value. * The **CORRECT** means, in this context, that address is valid *AND* user really * intended this particular address value as destination = that address is NOT lets say * copy-paste mistake made by user. Reason being that when user provided valid address * value, but made mistake = address is of someone else (e.g. copy-paste mistake), then * there is **NOTHING** what can be done to recover funds back to user (= refund) once * the swap will be relayed to the other blockchain! * The **VALID** means that provided value successfully passes consistency checks of * valid address of **OTHER** blockchain. In the case when user provides invalid * address value, relayer will execute refund - please see desc. for `refund()` call * for more details. */ function swap(uint256 amount, string calldata destinationAddress) external; } // Part: IBridgeRelayer /** * @title *Relayer* interface of Bi-directional bridge for transfer of FET tokens between Ethereum * and Fetch Mainnet-v2. * * @notice By design, all methods of this relayer-level interface can be called exclusively by relayer(s) of * the Bridge contract. * It is offers set of methods to perform relaying functionality of the Bridge = transferring swaps * across chains. * * @notice This bridge allows to transfer [ERC20-FET] tokens from Ethereum Mainnet to [Native FET] tokens on Fetch * Native Mainnet-v2 and **other way around** (= it is bi-directional). * User will be *charged* swap fee defined in counterpart contract deployed on Fetch Native Mainnet-v2. * In the case of a refund, user will be charged a swap fee configured in this contract. * * Swap Fees for `swap(...)` operations (direction from this contract to Native Fetch Mainnet-v2 are handled by * the counterpart contract on Fetch Native Mainnet-v2, **except** for refunds, for * which user is charged swap fee defined by this contract (since relayer needs to send refund transaction back * to this contract. */ interface IBridgeRelayer is IBridgeCommon { /** * @notice Starts the new relay eon. * @dev Relay eon concept is part of the design in order to ensure safe management of hand-over between two * relayer services. It provides clean isolation of potentially still pending transactions from previous * relayer svc and the current one. */ function newRelayEon() external; /** * @notice Refunds swap previously created by `swap(...)` call to this contract. The `swapFee` is *NOT* refunded * back to the user (this is by-design). * * @dev Callable exclusively by `relayer` role * * @param id - swap id to refund - must be swap id of swap originally created by `swap(...)` call to this contract, * **NOT** *reverse* swap id! * @param to - address where the refund will be transferred in to(IDENTICAL to address used in associated `swap` * call) * @param amount - original amount specified in associated `swap` call = it INCLUDES swap fee, which will be * withdrawn * @param relayEon_ - current relay eon, ensures safe management of relaying process */ function refund(uint64 id, address to, uint256 amount, uint64 relayEon_) external; /** * @notice Refunds swap previously created by `swap(...)` call to this contract, where `swapFee` *IS* refunded * back to the user (= swap fee is waived = user will receive full `amount`). * Purpose of this method is to enable full refund in the situations when it si not user's fault that * swap needs to be refunded (e.g. when Fetch Native Mainnet-v2 will become unavailable for prolonged * period of time, etc. ...). * * @dev Callable exclusively by `relayer` role * * @param id - swap id to refund - must be swap id of swap originally created by `swap(...)` call to this contract, * **NOT** *reverse* swap id! * @param to - address where the refund will be transferred in to(IDENTICAL to address used in associated `swap` * call) * @param amount - original amount specified in associated `swap` call = it INCLUDES swap fee, which will be * waived = user will receive whole `amount` value. * Pleas mind that `amount > 0`, otherways relayer will pay Tx fee for executing the transaction * which will have *NO* effect (= like this function `refundInFull(...)` would *not* have been * called at all! * @param relayEon_ - current relay eon, ensures safe management of relaying process */ function refundInFull(uint64 id, address to, uint256 amount, uint64 relayEon_) external; /** * @notice Finalises swap initiated by counterpart contract on the other blockchain. * This call sends swapped tokens to `to` address value user specified in original swap on the **OTHER** * blockchain. * * @dev Callable exclusively by `relayer` role * * @param rid - reverse swap id - unique identifier of the swap initiated on the **OTHER** blockchain. * This id is, by definition, sequentially growing number incremented by 1 for each new swap initiated * the other blockchain. **However**, it is *NOT* ensured that *all* swaps from the other blockchain * will be transferred to this (Ethereum) blockchain, since some of these swaps can be refunded back * to users (on the other blockchain). * @param to - address where the refund will be transferred in to * @param from - source address from which user transferred tokens from on the other blockchain. Present primarily * for purposes of quick querying of events on this blockchain. * @param originTxHash - transaction hash for swap initiated on the **OTHER** blockchain. Present in order to * create strong bond between this and other blockchain. * @param amount - original amount specified in associated swap initiated on the other blockchain. * Swap fee is *withdrawn* from the `amount` user specified in the swap on the other blockchain, * what means that user receives `amount - swapFee`, or *nothing* if `amount <= swapFee`. * Pleas mind that `amount > 0`, otherways relayer will pay Tx fee for executing the transaction * which will have *NO* effect (= like this function `refundInFull(...)` would *not* have been * called at all! * @param relayEon_ - current relay eon, ensures safe management of relaying process */ function reverseSwap( uint64 rid, address to, string calldata from, bytes32 originTxHash, uint256 amount, uint64 relayEon_ ) external; } // Part: IERC20Token interface IERC20Token is IERC20, IERC20MintFacility {} // Part: IBridgeAdmin /** * @title *Administrative* interface of Bi-directional bridge for transfer of FET tokens between Ethereum * and Fetch Mainnet-v2. * * @notice By design, all methods of this administrative interface can be called exclusively by administrator(s) of * the Bridge contract, since it allows to configure essential parameters of the the Bridge, and change * supply transferred across the Bridge. */ interface IBridgeAdmin is IBridgeCommon, IBridgeMonitor { /** * @notice Returns amount of excess FET ERC20 tokens which were sent to address of this contract via direct ERC20 * transfer (by calling ERC20.transfer(...)), without interacting with API of this contract, what can happen * only by mistake. * * @return targetAddress : address to send tokens to */ function getFeesAccrued() external view returns(uint256); /** * @notice Mints provided amount of FET tokens. * This is to reflect changes in minted Native FET token supply on the Fetch Native Mainnet-v2 blockchain. * @param amount - number of FET tokens to mint. */ function mint(uint256 amount) external; /** * @notice Burns provided amount of FET tokens. * This is to reflect changes in minted Native FET token supply on the Fetch Native Mainnet-v2 blockchain. * @param amount - number of FET tokens to burn. */ function burn(uint256 amount) external; /** * @notice Sets cap (max) value of `supply` this contract can hold = the value of tokens transferred to the other * blockchain. * This cap affects(limits) all operations which *increase* contract's `supply` value = `swap(...)` and * `mint(...)`. * @param value - new cap value. */ function setCap(uint256 value) external; /** * @notice Sets value of `reverseAggregatedAllowance` state variable. * This affects(limits) operations which *decrease* contract's `supply` value via **RELAYER** authored * operations (= `reverseSwap(...)` and `refund(...)`). It does **NOT** affect **ADMINISTRATION** authored * supply decrease operations (= `withdraw(...)` & `burn(...)`). * @param value - new cap value. */ function setReverseAggregatedAllowance(uint256 value) external; /** * @notice Sets value of `reverseAggregatedAllowanceCap` state variable. * This limits APPROVER_ROLE from top - value up to which can approver rise the allowance. * @param value - new cap value (absolute) */ function setReverseAggregatedAllowanceApproverCap(uint256 value) external; /** * @notice Sets limits for swap amount * FUnction will revert if following consitency check fails: `swapfee_ <= swapMin_ <= swapMax_` * @param swapMax_ : >= swap amount, applies for **OUTGOING** swap (= `swap(...)` call) * @param swapMin_ : <= swap amount, applies for **OUTGOING** swap (= `swap(...)` call) * @param swapFee_ : defines swap fee for **INCOMING** swap (= `reverseSwap(...)` call), and `refund(...)` */ function setLimits(uint256 swapMax_, uint256 swapMin_, uint256 swapFee_) external; /** * @notice Withdraws amount from contract's supply, which is supposed to be done exclusively for relocating funds to * another Bridge system, and **NO** other purpose. * @param targetAddress : address to send tokens to * @param amount : amount of tokens to withdraw */ function withdraw(address targetAddress, uint256 amount) external; /** * @dev Deposits funds back in to the contract supply. * Dedicated to increase contract's supply, usually(but not necessarily) after previous withdrawal from supply. * NOTE: This call needs preexisting ERC20 allowance >= `amount` for address of this Bridge contract as * recipient/beneficiary and Tx sender address as sender. * This means that address passed in as the Tx sender, must have already crated allowance by calling the * `ERC20.approve(from, ADDR_OF_BRIDGE_CONTRACT, amount)` *before* calling this(`deposit(...)`) call. * @param amount : deposit amount */ function deposit(uint256 amount) external; /** * @notice Withdraw fees accrued so far. * !IMPORTANT!: Current design of this contract does *NOT* allow to distinguish between *swap fees accrued* * and *excess funds* sent to the contract's address via *direct* `ERC20.transfer(...)`. * Implication is that excess funds **are treated** as swap fees. * The only way how to separate these two is off-chain, by replaying events from this and * Fet ERC20 contracts and do the reconciliation. * * @param targetAddress : address to send tokens to. */ function withdrawFees(address targetAddress) external; /** * @notice Delete the contract, transfers the remaining token and ether balance to the specified * payoutAddress * @param targetAddress address to transfer the balances to. Ensure that this is able to handle ERC20 tokens * @dev owner only + only on or after `earliestDelete` block */ function deleteContract(address payable targetAddress) external; } // Part: IBridge /** * @title Bi-directional bridge for transferring FET tokens between Ethereum and Fetch Mainnet-v2 * * @notice This bridge allows to transfer [ERC20-FET] tokens from Ethereum Mainnet to [Native FET] tokens on Fetch * Native Mainnet-v2 and **other way around** (= it is bi-directional). * User will be *charged* swap fee defined in counterpart contract deployed on Fetch Native Mainnet-v2. * In the case of a refund, user will be charged a swap fee configured in this contract. * * @dev There are three primary actions defining business logic of this contract: * * `swap(...)`: initiates swap of tokens from Ethereum to Fetch Native Mainnet-v2, callable by anyone (= users) * * `reverseSwap(...)`: finalises the swap of tokens in *opposite* direction = receives swap originally * initiated on Fetch Native Mainnet-v2, callable exclusively by `relayer` role * * `refund(...)`: refunds swap originally initiated in this contract(by `swap(...)` call), callable exclusively * by `relayer` role * * Swap Fees for `swap(...)` operations (direction from this contract to are handled by the counterpart contract on Fetch Native Mainnet-v2, **except** for refunds, for * which user is charged swap fee defined by this contract (since relayer needs to send refund transaction back to * this contract. * * ! IMPORTANT !: Current design of this contract does *NOT* allow to distinguish between *swap fees accrued* and * *excess funds* sent to the address of this contract via *direct* `ERC20.transfer(...)`. * Implication is, that excess funds **are treated** as swap fees. * The only way how to separate these two is to do it *off-chain*, by replaying events from this and FET ERC20 * contracts, and do the reconciliation. */ interface IBridge is IBridgePublic, IBridgeRelayer, IBridgeAdmin {} // File: Bridge.sol /** * @title Bi-directional bridge for transferring FET tokens between Ethereum and Fetch Mainnet-v2 * * @notice This bridge allows to transfer [ERC20-FET] tokens from Ethereum Mainnet to [Native FET] tokens on Fetch * Native Mainnet-v2 and **other way around** (= it is bi-directional). * User will be *charged* swap fee defined in counterpart contract deployed on Fetch Native Mainnet-v2. * In the case of a refund, user will be charged a swap fee configured in this contract. * * @dev There are three primary actions defining business logic of this contract: * * `swap(...)`: initiates swap of tokens from Ethereum to Fetch Native Mainnet-v2, callable by anyone (= users) * * `reverseSwap(...)`: finalises the swap of tokens in *opposite* direction = receives swap originally * initiated on Fetch Native Mainnet-v2, callable exclusively by `relayer` role * * `refund(...)`: refunds swap originally initiated in this contract(by `swap(...)` call), callable exclusively * by `relayer` role * * Swap Fees for `swap(...)` operations (direction from this contract to are handled by the counterpart contract on Fetch Native Mainnet-v2, **except** for refunds, for * which user is charged swap fee defined by this contract (since relayer needs to send refund transaction back to * this contract. * * ! IMPORTANT !: Current design of this contract does *NOT* allow to distinguish between *swap fees accrued* and * *excess funds* sent to the address of this contract via *direct* `ERC20.transfer(...)`. * Implication is, that excess funds **are treated** as swap fees. * The only way how to separate these two is to do it *off-chain*, by replaying events from this and FET ERC20 * contracts, and do the reconciliation. */ contract Bridge is IBridge, AccessControl { using SafeMath for uint256; /// @notice ********** CONSTANTS *********** bytes32 public constant APPROVER_ROLE = keccak256("APPROVER_ROLE"); bytes32 public constant MONITOR_ROLE = keccak256("MONITOR_ROLE"); bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE"); /// @notice ******* IMMUTABLE STATE ******** IERC20Token public immutable token; uint256 public immutable earliestDelete; /// @notice ******** MUTABLE STATE ********* uint256 public supply; uint64 public nextSwapId; uint64 public relayEon; mapping(uint64 => uint256) public refunds; // swapId -> original swap amount(= *includes* swapFee) uint256 public swapMax; uint256 public swapMin; uint256 public cap; uint256 public swapFee; uint256 public pausedSinceBlockPublicApi; uint256 public pausedSinceBlockRelayerApi; uint256 public reverseAggregatedAllowance; uint256 public reverseAggregatedAllowanceApproverCap; /* Only callable by owner */ modifier onlyOwner() { require(_isOwner(), "Only admin role"); _; } modifier onlyRelayer() { require(hasRole(RELAYER_ROLE, msg.sender), "Only relayer role"); _; } modifier verifyTxRelayEon(uint64 relayEon_) { require(relayEon == relayEon_, "Tx doesn't belong to current relayEon"); _; } modifier canPause(uint256 pauseSinceBlockNumber) { if (pauseSinceBlockNumber > block.number) // Checking UN-pausing (the most critical operation) { require(_isOwner(), "Only admin role"); } else { require(hasRole(MONITOR_ROLE, msg.sender) || _isOwner(), "Only admin or monitor role"); } _; } modifier canSetReverseAggregatedAllowance(uint256 allowance) { if (allowance > reverseAggregatedAllowanceApproverCap) // Check for going over the approver cap (the most critical operation) { require(_isOwner(), "Only admin role"); } else { require(hasRole(APPROVER_ROLE, msg.sender) || _isOwner(), "Only admin or approver role"); } _; } modifier verifyPublicAPINotPaused() { require(pausedSinceBlockPublicApi > block.number, "Contract has been paused"); _verifyRelayerApiNotPaused(); _; } modifier verifyRelayerApiNotPaused() { _verifyRelayerApiNotPaused(); _; } modifier verifySwapAmount(uint256 amount) { // NOTE(pb): Commenting-out check against `swapFee` in order to spare gas for user's Tx, relying solely on check // against `swapMin` only, which is ensured to be `>= swapFee` (by `_setLimits(...)` function). //require(amount > swapFee, "Amount must be higher than fee"); require(amount >= swapMin, "Amount bellow lower limit"); require(amount <= swapMax, "Amount exceeds upper limit"); _; } modifier verifyReverseSwapAmount(uint256 amount) { require(amount <= swapMax, "Amount exceeds swap max limit"); _; } modifier verifyRefundSwapId(uint64 id) { require(id < nextSwapId, "Invalid swap id"); require(refunds[id] == 0, "Refund was already processed"); _; } /******************* Contract start *******************/ /** * @notice Contract constructor * @dev Input parameters offers full flexibility to configure the contract during deployment, with minimal need of * further setup transactions necessary to open contract to the public. * * @param ERC20Address - address of FET ERC20 token contract * @param cap_ - limits contract `supply` value from top * @param reverseAggregatedAllowance_ - allowance value which limits how much can refund & reverseSwap transfer * in aggregated form * @param reverseAggregatedAllowanceApproverCap_ - limits allowance value up to which can APPROVER_ROLE set * the allowance * @param swapMax_ - value representing UPPER limit which can be transferred (this value INCLUDES swapFee) * @param swapMin_ - value representing LOWER limit which can be transferred (this value INCLUDES swapFee) * @param swapFee_ - represents fee which user has to pay for swap execution, * @param pausedSinceBlockPublicApi_ - block number since which the Public API of the contract will be paused * @param pausedSinceBlockRelayerApi_ - block number since which the Relayer API of the contract will be paused * @param deleteProtectionPeriod_ - number of blocks(from contract deployment block) during which contract can * NOT be deleted */ constructor( address ERC20Address , uint256 cap_ , uint256 reverseAggregatedAllowance_ , uint256 reverseAggregatedAllowanceApproverCap_ , uint256 swapMax_ , uint256 swapMin_ , uint256 swapFee_ , uint256 pausedSinceBlockPublicApi_ , uint256 pausedSinceBlockRelayerApi_ , uint256 deleteProtectionPeriod_) { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); token = IERC20Token(ERC20Address); earliestDelete = block.number.add(deleteProtectionPeriod_); /// @dev Unnecessary initialisations, done implicitly by VM //supply = 0; //refundsFeesAccrued = 0; //nextSwapId = 0; // NOTE(pb): Initial value is by design set to MAX_LIMIT<uint64>, so that its NEXT increment(+1) will // overflow to 0. relayEon = type(uint64).max; _setCap(cap_); _setReverseAggregatedAllowance(reverseAggregatedAllowance_); _setReverseAggregatedAllowanceApproverCap(reverseAggregatedAllowanceApproverCap_); _setLimits(swapMax_, swapMin_, swapFee_); _pausePublicApiSince(pausedSinceBlockPublicApi_); _pauseRelayerApiSince(pausedSinceBlockRelayerApi_); } // ********************************************************** // *********** USER-LEVEL ACCESS METHODS ********** /** * @notice Initiates swap, which will be relayed to the other blockchain. * Swap might fail, if `destinationAddress` value is invalid (see bellow), in which case the swap will be * refunded back to user. Swap fee will be *WITHDRAWN* from `amount` in that case - please see details * in desc. for `refund(...)` call. * * @dev Swap call will create unique identifier (swap id), which is, by design, sequentially growing by 1 per each * new swap created, and so uniquely identifies each swap. This identifier is referred to as "reverse swap id" * on the other blockchain. * Callable by anyone. * * @param destinationAddress - address on **OTHER** blockchain where the swap effective amount will be transferred * in to. * User is **RESPONSIBLE** for providing the **CORRECT** and valid value. * The **CORRECT** means, in this context, that address is valid *AND* user really * intended this particular address value as destination = that address is NOT lets say * copy-paste mistake made by user. Reason being that when user provided valid address * value, but made mistake = address is of someone else (e.g. copy-paste mistake), then * there is **NOTHING** what can be done to recover funds back to user (= refund) once * the swap will be relayed to the other blockchain! * The **VALID** means that provided value successfully passes consistency checks of * valid address of **OTHER** blockchain. In the case when user provides invalid * address value, relayer will execute refund - please see desc. for `refund()` call * for more details. */ function swap( uint256 amount, // This is original amount (INCLUDES fee) string calldata destinationAddress ) external override verifyPublicAPINotPaused verifySwapAmount(amount) { supply = supply.add(amount); require(cap >= supply, "Swap would exceed cap"); token.transferFrom(msg.sender, address(this), amount); emit Swap(nextSwapId, msg.sender, destinationAddress, destinationAddress, amount); // NOTE(pb): No necessity to use SafeMath here: nextSwapId += 1; } /** * @notice Returns amount of excess FET ERC20 tokens which were sent to address of this contract via direct ERC20 * transfer (by calling ERC20.transfer(...)), without interacting with API of this contract, what can happen * only by mistake. * * @return targetAddress : address to send tokens to */ function getFeesAccrued() external view override returns(uint256) { // NOTE(pb): This subtraction shall NEVER fail: return token.balanceOf(address(this)).sub(supply, "Critical err: balance < supply"); } function getApproverRole() external view override returns(bytes32) {return APPROVER_ROLE;} function getMonitorRole() external view override returns(bytes32) {return MONITOR_ROLE;} function getRelayerRole() external view override returns(bytes32) {return RELAYER_ROLE;} function getToken() external view override returns(address) {return address(token);} function getEarliestDelete() external view override returns(uint256) {return earliestDelete;} function getSupply() external view override returns(uint256) {return supply;} function getNextSwapId() external view override returns(uint64) {return nextSwapId;} function getRelayEon() external view override returns(uint64) {return relayEon;} function getRefund(uint64 swap_id) external view override returns(uint256) {return refunds[swap_id];} function getSwapMax() external view override returns(uint256) {return swapMax;} function getSwapMin() external view override returns(uint256) {return swapMin;} function getCap() external view override returns(uint256) {return cap;} function getSwapFee() external view override returns(uint256) {return swapFee;} function getPausedSinceBlockPublicApi() external view override returns(uint256) {return pausedSinceBlockPublicApi;} function getPausedSinceBlockRelayerApi() external view override returns(uint256) {return pausedSinceBlockRelayerApi;} function getReverseAggregatedAllowance() external view override returns(uint256) {return reverseAggregatedAllowance;} function getReverseAggregatedAllowanceApproverCap() external view override returns(uint256) {return reverseAggregatedAllowanceApproverCap;} // ********************************************************** // *********** RELAYER-LEVEL ACCESS METHODS *********** /** * @notice Starts the new relay eon. * @dev Relay eon concept is part of the design in order to ensure safe management of hand-over between two * relayer services. It provides clean isolation of potentially still pending transactions from previous * relayer svc and the current one. */ function newRelayEon() external override verifyRelayerApiNotPaused onlyRelayer { // NOTE(pb): No need for safe math for this increment, since the MAX_LIMIT<uint64> is huge number (~10^19), // there is no way that +1 incrementing from initial 0 value can possibly cause overflow in real world - that // would require to send more than 10^19 transactions to reach that point. // The only case, where this increment operation will lead to overflow, by-design, is the **VERY 1st** // increment = very 1st call of this contract method, when the `relayEon` is by-design & intentionally // initialised to MAX_LIMIT<uint64> value, so the resulting value of the `relayEon` after increment will be `0` relayEon += 1; emit NewRelayEon(relayEon); } /** * @notice Refunds swap previously created by `swap(...)` call to this contract. The `swapFee` is *NOT* refunded * back to the user (this is by-design). * * @dev Callable exclusively by `relayer` role * * @param id - swap id to refund - must be swap id of swap originally created by `swap(...)` call to this contract, * **NOT** *reverse* swap id! * @param to - address where the refund will be transferred in to(IDENTICAL to address used in associated `swap` * call) * @param amount - original amount specified in associated `swap` call = it INCLUDES swap fee, which will be * withdrawn * @param relayEon_ - current relay eon, ensures safe management of relaying process */ function refund( uint64 id, address to, uint256 amount, uint64 relayEon_ ) external override verifyRelayerApiNotPaused verifyTxRelayEon(relayEon_) verifyReverseSwapAmount(amount) onlyRelayer verifyRefundSwapId(id) { // NOTE(pb): Fail as early as possible - withdrawal from aggregated allowance is most likely to fail comparing // to rest of the operations bellow. _updateReverseAggregatedAllowance(amount); supply = supply.sub(amount, "Amount exceeds contract supply"); // NOTE(pb): Same calls are repeated in both branches of the if-else in order to minimise gas impact, comparing // to implementation, where these calls would be present in the code just once, after if-else block. if (amount > swapFee) { // NOTE(pb): No need to use safe math here, the overflow is prevented by `if` condition above. uint256 effectiveAmount = amount - swapFee; token.transfer(to, effectiveAmount); emit SwapRefund(id, to, effectiveAmount, swapFee); } else { // NOTE(pb): No transfer necessary in this case, since whole amount is taken as swap fee. emit SwapRefund(id, to, 0, amount); } // NOTE(pb): Here we need to record the original `amount` value (passed as input param) rather than // `effectiveAmount` in order to make sure, that the value is **NOT** zero (so it is possible to detect // existence of key-value record in the `refunds` mapping (this is done in the `verifyRefundSwapId(...)` // modifier). This also means that relayer role shall call this `refund(...)` function only for `amount > 0`, // otherways relayer will pay Tx fee for executing the transaction which will have *NO* effect. refunds[id] = amount; } /** * @notice Refunds swap previously created by `swap(...)` call to this contract, where `swapFee` *IS* refunded * back to the user (= swap fee is waived = user will receive full `amount`). * Purpose of this method is to enable full refund in the situations when it si not user's fault that * swap needs to be refunded (e.g. when Fetch Native Mainnet-v2 will become unavailable for prolonged * period of time, etc. ...). * * @dev Callable exclusively by `relayer` role * * @param id - swap id to refund - must be swap id of swap originally created by `swap(...)` call to this contract, * **NOT** *reverse* swap id! * @param to - address where the refund will be transferred in to(IDENTICAL to address used in associated `swap` * call) * @param amount - original amount specified in associated `swap` call = it INCLUDES swap fee, which will be * waived = user will receive whole `amount` value. * Pleas mind that `amount > 0`, otherways relayer will pay Tx fee for executing the transaction * which will have *NO* effect (= like this function `refundInFull(...)` would *not* have been * called at all! * @param relayEon_ - current relay eon, ensures safe management of relaying process */ function refundInFull( uint64 id, address to, uint256 amount, uint64 relayEon_ ) external override verifyRelayerApiNotPaused verifyTxRelayEon(relayEon_) verifyReverseSwapAmount(amount) onlyRelayer verifyRefundSwapId(id) { // NOTE(pb): Fail as early as possible - withdrawal from aggregated allowance is most likely to fail comparing // to rest of the operations bellow. _updateReverseAggregatedAllowance(amount); supply = supply.sub(amount, "Amount exceeds contract supply"); token.transfer(to, amount); emit SwapRefund(id, to, amount, 0); // NOTE(pb): Here we need to record the original `amount` value (passed as input param) rather than // `effectiveAmount` in order to make sure, that the value is **NOT** zero (so it is possible to detect // existence of key-value record in the `refunds` mapping (this is done in the `verifyRefundSwapId(...)` // modifier). This also means that relayer role shall call this function function only for `amount > 0`, // otherways relayer will pay Tx fee for executing the transaction which will have *NO* effect. refunds[id] = amount; } /** * @notice Finalises swap initiated by counterpart contract on the other blockchain. * This call sends swapped tokens to `to` address value user specified in original swap on the **OTHER** * blockchain. * * @dev Callable exclusively by `relayer` role * * @param rid - reverse swap id - unique identifier of the swap initiated on the **OTHER** blockchain. * This id is, by definition, sequentially growing number incremented by 1 for each new swap initiated * the other blockchain. **However**, it is *NOT* ensured that *all* swaps from the other blockchain * will be transferred to this (Ethereum) blockchain, since some of these swaps can be refunded back * to users (on the other blockchain). * @param to - address where the refund will be transferred in to * @param from - source address from which user transferred tokens from on the other blockchain. Present primarily * for purposes of quick querying of events on this blockchain. * @param originTxHash - transaction hash for swap initiated on the **OTHER** blockchain. Present in order to * create strong bond between this and other blockchain. * @param amount - original amount specified in associated swap initiated on the other blockchain. * Swap fee is *withdrawn* from the `amount` user specified in the swap on the other blockchain, * what means that user receives `amount - swapFee`, or *nothing* if `amount <= swapFee`. * Pleas mind that `amount > 0`, otherways relayer will pay Tx fee for executing the transaction * which will have *NO* effect (= like this function `refundInFull(...)` would *not* have been * called at all! * @param relayEon_ - current relay eon, ensures safe management of relaying process */ function reverseSwap( uint64 rid, // Reverse swp id (from counterpart contract on other blockchain) address to, string calldata from, bytes32 originTxHash, uint256 amount, // This is original swap amount (= *includes* swapFee) uint64 relayEon_ ) external override verifyRelayerApiNotPaused verifyTxRelayEon(relayEon_) verifyReverseSwapAmount(amount) onlyRelayer { // NOTE(pb): Fail as early as possible - withdrawal from aggregated allowance is most likely to fail comparing // to rest of the operations bellow. _updateReverseAggregatedAllowance(amount); supply = supply.sub(amount, "Amount exceeds contract supply"); if (amount > swapFee) { // NOTE(pb): No need to use safe math here, the overflow is prevented by `if` condition above. uint256 effectiveAmount = amount - swapFee; token.transfer(to, effectiveAmount); emit ReverseSwap(rid, to, from, originTxHash, effectiveAmount, swapFee); } else { // NOTE(pb): No transfer, no contract supply change since whole amount is taken as swap fee. emit ReverseSwap(rid, to, from, originTxHash, 0, amount); } } // ********************************************************** // **** MONITOR/ADMIN-LEVEL ACCESS METHODS ***** /** * @notice Pauses Public API since the specified block number * @param blockNumber block number since which public interaction will be paused (for all * block.number >= blockNumber). * @dev Delegate only * If `blocknumber < block.number`, then contract will be paused immediately = from `block.number`. */ function pausePublicApiSince(uint256 blockNumber) external override canPause(blockNumber) { _pausePublicApiSince(blockNumber); } /** * @notice Pauses Relayer API since the specified block number * @param blockNumber block number since which Relayer API interaction will be paused (for all * block.number >= blockNumber). * @dev Delegate only * If `blocknumber < block.number`, then contract will be paused immediately = from `block.number`. */ function pauseRelayerApiSince(uint256 blockNumber) external override canPause(blockNumber) { _pauseRelayerApiSince(blockNumber); } // ********************************************************** // ************ ADMIN-LEVEL ACCESS METHODS ************* /** * @notice Mints provided amount of FET tokens. * This is to reflect changes in minted Native FET token supply on the Fetch Native Mainnet-v2 blockchain. * @param amount - number of FET tokens to mint. */ function mint(uint256 amount) external override onlyOwner { // NOTE(pb): The `supply` shall be adjusted by minted amount. supply = supply.add(amount); require(cap >= supply, "Minting would exceed the cap"); token.mint(address(this), amount); } /** * @notice Burns provided amount of FET tokens. * This is to reflect changes in minted Native FET token supply on the Fetch Native Mainnet-v2 blockchain. * @param amount - number of FET tokens to burn. */ function burn(uint256 amount) external override onlyOwner { // NOTE(pb): The `supply` shall be adjusted by burned amount. supply = supply.sub(amount, "Amount exceeds contract supply"); token.burn(amount); } /** * @notice Sets cap (max) value of `supply` this contract can hold = the value of tokens transferred to the other * blockchain. * This cap affects(limits) all operations which *increase* contract's `supply` value = `swap(...)` and * `mint(...)`. * @param value - new cap value. */ function setCap(uint256 value) external override onlyOwner { _setCap(value); } /** * @notice Sets value of `reverseAggregatedAllowance` state variable. * This affects(limits) operations which *decrease* contract's `supply` value via **RELAYER** authored * operations (= `reverseSwap(...)` and `refund(...)`). It does **NOT** affect **ADMINISTRATION** authored * supply decrease operations (= `withdraw(...)` & `burn(...)`). * @param value - new allowance value (absolute) */ function setReverseAggregatedAllowance(uint256 value) external override canSetReverseAggregatedAllowance(value) { _setReverseAggregatedAllowance(value); } /** * @notice Sets value of `reverseAggregatedAllowanceApproverCap` state variable. * This limits APPROVER_ROLE from top - value up to which can approver rise the allowance. * @param value - new cap value (absolute) */ function setReverseAggregatedAllowanceApproverCap(uint256 value) external override onlyOwner { _setReverseAggregatedAllowanceApproverCap(value); } /** * @notice Sets limits for swap amount * FUnction will revert if following consitency check fails: `swapfee_ <= swapMin_ <= swapMax_` * @param swapMax_ : >= swap amount, applies for **OUTGOING** swap (= `swap(...)` call) * @param swapMin_ : <= swap amount, applies for **OUTGOING** swap (= `swap(...)` call) * @param swapFee_ : defines swap fee for **INCOMING** swap (= `reverseSwap(...)` call), and `refund(...)` */ function setLimits( uint256 swapMax_, uint256 swapMin_, uint256 swapFee_ ) external override onlyOwner { _setLimits(swapMax_, swapMin_, swapFee_); } /** * @notice Withdraws amount from contract's supply, which is supposed to be done exclusively for relocating funds to * another Bridge system, and **NO** other purpose. * @param targetAddress : address to send tokens to * @param amount : amount of tokens to withdraw */ function withdraw( address targetAddress, uint256 amount ) external override onlyOwner { supply = supply.sub(amount, "Amount exceeds contract supply"); token.transfer(targetAddress, amount); emit Withdraw(targetAddress, amount); } /** * @dev Deposits funds back in to the contract supply. * Dedicated to increase contract's supply, usually(but not necessarily) after previous withdrawal from supply. * NOTE: This call needs preexisting ERC20 allowance >= `amount` for address of this Bridge contract as * recipient/beneficiary and Tx sender address as sender. * This means that address passed in as the Tx sender, must have already crated allowance by calling the * `ERC20.approve(from, ADDR_OF_BRIDGE_CONTRACT, amount)` *before* calling this(`deposit(...)`) call. * @param amount : deposit amount */ function deposit(uint256 amount) external override onlyOwner { supply = supply.add(amount); require(cap >= supply, "Deposit would exceed the cap"); token.transferFrom(msg.sender, address(this), amount); emit Deposit(msg.sender, amount); } /** * @notice Withdraw fees accrued so far. * !IMPORTANT!: Current design of this contract does *NOT* allow to distinguish between *swap fees accrued* * and *excess funds* sent to the contract's address via *direct* `ERC20.transfer(...)`. * Implication is that excess funds **are treated** as swap fees. * The only way how to separate these two is off-chain, by replaying events from this and * Fet ERC20 contracts and do the reconciliation. * * @param targetAddress : address to send tokens to. */ function withdrawFees(address targetAddress) external override onlyOwner { uint256 fees = this.getFeesAccrued(); require(fees > 0, "No fees to withdraw"); token.transfer(targetAddress, fees); emit FeesWithdrawal(targetAddress, fees); } /** * @notice Delete the contract, transfers the remaining token and ether balance to the specified * payoutAddress * @param targetAddress address to transfer the balances to. Ensure that this is able to handle ERC20 tokens * @dev owner only + only on or after `earliestDelete` block */ function deleteContract(address payable targetAddress) external override onlyOwner { require(earliestDelete <= block.number, "Earliest delete not reached"); require(targetAddress != address(this), "pay addr == this contract addr"); uint256 contractBalance = token.balanceOf(address(this)); token.transfer(targetAddress, contractBalance); emit DeleteContract(targetAddress, contractBalance); selfdestruct(targetAddress); } // ********************************************************** // ****************** INTERNAL METHODS ***************** function _isOwner() internal view returns(bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); } function _verifyRelayerApiNotPaused() internal view { require(pausedSinceBlockRelayerApi > block.number, "Contract has been paused"); } /** * @notice Pauses Public API since the specified block number * @param blockNumber - block number since which interaction with Public API will be paused (for all * block.number >= blockNumber) */ function _pausePublicApiSince(uint256 blockNumber) internal { pausedSinceBlockPublicApi = blockNumber < block.number ? block.number : blockNumber; emit PausePublicApi(pausedSinceBlockPublicApi); } /** * @notice Pauses Relayer API since the specified block number * @param blockNumber - block number since which interaction with Relayer API will be paused (for all * block.number >= blockNumber) */ function _pauseRelayerApiSince(uint256 blockNumber) internal { pausedSinceBlockRelayerApi = blockNumber < block.number ? block.number : blockNumber; emit PauseRelayerApi(pausedSinceBlockRelayerApi); } function _setLimits( uint256 swapMax_, uint256 swapMin_, uint256 swapFee_ ) internal { require((swapFee_ <= swapMin_) && (swapMin_ <= swapMax_), "fee<=lower<=upper violated"); swapMax = swapMax_; swapMin = swapMin_; swapFee = swapFee_; emit LimitsUpdate(swapMax, swapMin, swapFee); } function _setCap(uint256 cap_) internal { cap = cap_; emit CapUpdate(cap); } function _setReverseAggregatedAllowance(uint256 allowance) internal { reverseAggregatedAllowance = allowance; emit ReverseAggregatedAllowanceUpdate(reverseAggregatedAllowance); } function _setReverseAggregatedAllowanceApproverCap(uint256 value) internal { reverseAggregatedAllowanceApproverCap = value; emit ReverseAggregatedAllowanceApproverCapUpdate(reverseAggregatedAllowanceApproverCap); } function _updateReverseAggregatedAllowance(uint256 amount) internal { reverseAggregatedAllowance = reverseAggregatedAllowance.sub(amount, "Operation exceeds reverse aggregated allowance"); } }
* @notice Pauses Relayer API since the specified block number @param blockNumber block number since which Relayer API interaction will be paused (for all block.number >= blockNumber). @dev Delegate only If `blocknumber < block.number`, then contract will be paused immediately = from `block.number`./
function pauseRelayerApiSince(uint256 blockNumber) external override canPause(blockNumber) { _pauseRelayerApiSince(blockNumber); }
6,427,120
[ 1, 52, 9608, 4275, 1773, 1491, 3241, 326, 1269, 1203, 1300, 225, 1203, 1854, 1203, 1300, 3241, 1492, 4275, 1773, 1491, 13581, 903, 506, 17781, 261, 1884, 777, 3639, 1203, 18, 2696, 1545, 1203, 1854, 2934, 225, 27687, 1338, 1377, 971, 1375, 2629, 2696, 411, 1203, 18, 2696, 9191, 1508, 6835, 903, 506, 17781, 7636, 273, 628, 1375, 2629, 18, 2696, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11722, 1971, 1773, 3064, 9673, 12, 11890, 5034, 1203, 1854, 13, 203, 3639, 3903, 203, 3639, 3849, 203, 3639, 848, 19205, 12, 2629, 1854, 13, 203, 565, 288, 203, 3639, 389, 19476, 1971, 1773, 3064, 9673, 12, 2629, 1854, 1769, 203, 565, 289, 203, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-10-20 */ // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IBEP20 { /** * @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); } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } 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; } } /** * @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 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 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 BEP20Token is Context, IBEP20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; event TransferToNative(address indexed from, bytes32 indexed to, uint256 value); event TransferFromNative(address indexed to, bytes32 indexed refID, uint256 value); uint256 private _totalSupply; uint8 private _decimals; string private _symbol; string private _name; constructor(uint256 totalSupply, address owner) public { _name = "Dalarnia"; _symbol = "DAR"; _decimals = 6; _totalSupply = totalSupply; _balances[owner] = totalSupply; emit Transfer(address(0), owner, _totalSupply); transferOwnership(owner); } /** * @dev Returns the bep token owner. */ function getOwner() override external view returns (address) { return owner(); } /** * @dev Returns the token decimals. */ function decimals() override external view returns (uint8) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() override external view returns (string memory) { return _symbol; } /** * @dev Returns the token name. */ function name() override external view returns (string memory) { return _name; } /** * @dev See {BEP20-totalSupply}. */ function totalSupply() override external view returns (uint256) { return _totalSupply; } /** * @dev See {BEP20-balanceOf}. */ function balanceOf(address account) override external view returns (uint256) { return _balances[account]; } /** * @dev See {BEP20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) override external returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {BEP20-allowance}. */ function allowance(address owner, address spender) override external view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {BEP20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) override external returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {BEP20-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) override external returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "BEP20: 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 {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].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 {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "BEP20: 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 { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "BEP20: 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 { require(account != address(0), "BEP20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Burns a specific amount of tokens and emit transfer event for native chain * @param to The address to transfer to in the native chain. * @param value The amount of token to be burned. */ function transferToNative(bytes32 to, uint256 value) public { _burn(msg.sender, value); emit TransferToNative(msg.sender, to, value); } /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. * @param value The amount of tokens to mint. * @param refID identifier of a transfer on source chain, if any * @return A boolean that indicates if the operation was successful. */ function transferFromNative(address to, uint256 value, bytes32 refID) public onlyOwner returns (bool) { _mint(to, value); emit TransferFromNative(to, refID, value); return true; } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "BEP20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "BEP20: 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 { 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); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "BEP20: burn amount exceeds allowance")); } }
* @dev Burns a specific amount of tokens and emit transfer event for native chain @param to The address to transfer to in the native chain. @param value The amount of token to be burned./
function transferToNative(bytes32 to, uint256 value) public { _burn(msg.sender, value); emit TransferToNative(msg.sender, to, value); }
7,765,285
[ 1, 38, 321, 87, 279, 2923, 3844, 434, 2430, 471, 3626, 7412, 871, 364, 6448, 2687, 225, 358, 1021, 1758, 358, 7412, 358, 316, 326, 6448, 2687, 18, 225, 460, 1021, 3844, 434, 1147, 358, 506, 18305, 329, 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, 565, 445, 7412, 774, 9220, 12, 3890, 1578, 358, 16, 2254, 5034, 460, 13, 1071, 288, 203, 3639, 389, 70, 321, 12, 3576, 18, 15330, 16, 460, 1769, 203, 3639, 3626, 12279, 774, 9220, 12, 3576, 18, 15330, 16, 358, 16, 460, 1769, 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, -100, -100, -100, -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 "../AddressResolver.sol"; import "../BaseMigration.sol"; import "../DebtCache.sol"; import "../ExchangeRatesWithDexPricing.sol"; import "../ExchangeState.sol"; import "../FeePool.sol"; import "../FeePoolEternalStorage.sol"; import "../Issuer.sol"; import "../MultiCollateralSynth.sol"; import "../Proxy.sol"; import "../ProxyERC20.sol"; import "../RewardEscrow.sol"; import "../SystemStatus.sol"; import "../TokenState.sol"; interface ISynthetixNamedContract { // solhint-disable func-name-mixedcase function CONTRACT_NAME() external view returns (bytes32); } // solhint-disable contract-name-camelcase library MigrationLib_Diphda { // ---------------------------- // EXISTING SYNTHETIX CONTRACTS // ---------------------------- // https://etherscan.io/address/0x823bE81bbF96BEc0e25CA13170F5AaCb5B79ba83 AddressResolver public constant addressresolver_i = AddressResolver(0x823bE81bbF96BEc0e25CA13170F5AaCb5B79ba83); // https://etherscan.io/address/0xb440DD674e1243644791a4AdfE3A2AbB0A92d309 Proxy public constant proxyfeepool_i = Proxy(0xb440DD674e1243644791a4AdfE3A2AbB0A92d309); // https://etherscan.io/address/0xC9DFff5fA5605fd94F8B7927b892F2B57391e8bB FeePoolEternalStorage public constant feepooleternalstorage_i = FeePoolEternalStorage(0xC9DFff5fA5605fd94F8B7927b892F2B57391e8bB); // https://etherscan.io/address/0x545973f28950f50fc6c7F52AAb4Ad214A27C0564 ExchangeState public constant exchangestate_i = ExchangeState(0x545973f28950f50fc6c7F52AAb4Ad214A27C0564); // https://etherscan.io/address/0x696c905F8F8c006cA46e9808fE7e00049507798F SystemStatus public constant systemstatus_i = SystemStatus(0x696c905F8F8c006cA46e9808fE7e00049507798F); // https://etherscan.io/address/0xb671F2210B1F6621A2607EA63E6B2DC3e2464d1F RewardEscrow public constant rewardescrow_i = RewardEscrow(0xb671F2210B1F6621A2607EA63E6B2DC3e2464d1F); // https://etherscan.io/address/0x3B2f389AeE480238A49E3A9985cd6815370712eB FeePool public constant feepool_i = FeePool(0x3B2f389AeE480238A49E3A9985cd6815370712eB); // https://etherscan.io/address/0x1620Aa736939597891C1940CF0d28b82566F9390 DebtCache public constant debtcache_i = DebtCache(0x1620Aa736939597891C1940CF0d28b82566F9390); // https://etherscan.io/address/0x6fA9E5923CBFDD39F0B625Bf1350Ffb50D5006b9 ExchangeRatesWithDexPricing public constant exchangerates_i = ExchangeRatesWithDexPricing(0x6fA9E5923CBFDD39F0B625Bf1350Ffb50D5006b9); // https://etherscan.io/address/0x7df9b3f8f1C011D8BD707430e97E747479DD532a MultiCollateralSynth public constant synthsusd_i = MultiCollateralSynth(0x7df9b3f8f1C011D8BD707430e97E747479DD532a); // https://etherscan.io/address/0x05a9CBe762B36632b3594DA4F082340E0e5343e8 TokenState public constant tokenstatesusd_i = TokenState(0x05a9CBe762B36632b3594DA4F082340E0e5343e8); // https://etherscan.io/address/0x57Ab1ec28D129707052df4dF418D58a2D46d5f51 Proxy public constant proxysusd_i = Proxy(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51); // https://etherscan.io/address/0x1b06a00Df0B27E7871E753720D4917a7D1aac68b MultiCollateralSynth public constant synthseur_i = MultiCollateralSynth(0x1b06a00Df0B27E7871E753720D4917a7D1aac68b); // https://etherscan.io/address/0x6568D9e750fC44AF00f857885Dfb8281c00529c4 TokenState public constant tokenstateseur_i = TokenState(0x6568D9e750fC44AF00f857885Dfb8281c00529c4); // https://etherscan.io/address/0xD71eCFF9342A5Ced620049e616c5035F1dB98620 ProxyERC20 public constant proxyseur_i = ProxyERC20(0xD71eCFF9342A5Ced620049e616c5035F1dB98620); // https://etherscan.io/address/0xB82f11f3168Ece7D56fe6a5679567948090de7C5 MultiCollateralSynth public constant synthsjpy_i = MultiCollateralSynth(0xB82f11f3168Ece7D56fe6a5679567948090de7C5); // https://etherscan.io/address/0x4dFACfB15514C21c991ff75Bc7Bf6Fb1F98361ed TokenState public constant tokenstatesjpy_i = TokenState(0x4dFACfB15514C21c991ff75Bc7Bf6Fb1F98361ed); // https://etherscan.io/address/0xF6b1C627e95BFc3c1b4c9B825a032Ff0fBf3e07d ProxyERC20 public constant proxysjpy_i = ProxyERC20(0xF6b1C627e95BFc3c1b4c9B825a032Ff0fBf3e07d); // https://etherscan.io/address/0xC4546bDd93cDAADA6994e84Fb6F2722C620B019C MultiCollateralSynth public constant synthsaud_i = MultiCollateralSynth(0xC4546bDd93cDAADA6994e84Fb6F2722C620B019C); // https://etherscan.io/address/0xCb29D2cf2C65d3Be1d00F07f3441390432D55203 TokenState public constant tokenstatesaud_i = TokenState(0xCb29D2cf2C65d3Be1d00F07f3441390432D55203); // https://etherscan.io/address/0xF48e200EAF9906362BB1442fca31e0835773b8B4 ProxyERC20 public constant proxysaud_i = ProxyERC20(0xF48e200EAF9906362BB1442fca31e0835773b8B4); // https://etherscan.io/address/0xAE7A2C1e326e59f2dB2132652115a59E8Adb5eBf MultiCollateralSynth public constant synthsgbp_i = MultiCollateralSynth(0xAE7A2C1e326e59f2dB2132652115a59E8Adb5eBf); // https://etherscan.io/address/0x7e88D19A79b291cfE5696d496055f7e57F537A75 TokenState public constant tokenstatesgbp_i = TokenState(0x7e88D19A79b291cfE5696d496055f7e57F537A75); // https://etherscan.io/address/0x97fe22E7341a0Cd8Db6F6C021A24Dc8f4DAD855F ProxyERC20 public constant proxysgbp_i = ProxyERC20(0x97fe22E7341a0Cd8Db6F6C021A24Dc8f4DAD855F); // https://etherscan.io/address/0xCC83a57B080a4c7C86F0bB892Bc180C8C7F8791d MultiCollateralSynth public constant synthschf_i = MultiCollateralSynth(0xCC83a57B080a4c7C86F0bB892Bc180C8C7F8791d); // https://etherscan.io/address/0x52496fE8a4feaEFe14d9433E00D48E6929c13deC TokenState public constant tokenstateschf_i = TokenState(0x52496fE8a4feaEFe14d9433E00D48E6929c13deC); // https://etherscan.io/address/0x0F83287FF768D1c1e17a42F44d644D7F22e8ee1d ProxyERC20 public constant proxyschf_i = ProxyERC20(0x0F83287FF768D1c1e17a42F44d644D7F22e8ee1d); // https://etherscan.io/address/0x527637bE27640d6C3e751d24DC67129A6d13E11C MultiCollateralSynth public constant synthskrw_i = MultiCollateralSynth(0x527637bE27640d6C3e751d24DC67129A6d13E11C); // https://etherscan.io/address/0x93B6e9FbBd2c32a0DC3C2B943B7C3CBC2fE23730 TokenState public constant tokenstateskrw_i = TokenState(0x93B6e9FbBd2c32a0DC3C2B943B7C3CBC2fE23730); // https://etherscan.io/address/0x269895a3dF4D73b077Fc823dD6dA1B95f72Aaf9B ProxyERC20 public constant proxyskrw_i = ProxyERC20(0x269895a3dF4D73b077Fc823dD6dA1B95f72Aaf9B); // https://etherscan.io/address/0x18FcC34bdEaaF9E3b69D2500343527c0c995b1d6 MultiCollateralSynth public constant synthsbtc_i = MultiCollateralSynth(0x18FcC34bdEaaF9E3b69D2500343527c0c995b1d6); // https://etherscan.io/address/0x4F6296455F8d754c19821cF1EC8FeBF2cD456E67 TokenState public constant tokenstatesbtc_i = TokenState(0x4F6296455F8d754c19821cF1EC8FeBF2cD456E67); // https://etherscan.io/address/0xfE18be6b3Bd88A2D2A7f928d00292E7a9963CfC6 ProxyERC20 public constant proxysbtc_i = ProxyERC20(0xfE18be6b3Bd88A2D2A7f928d00292E7a9963CfC6); // https://etherscan.io/address/0x4FB63c954Ef07EC74335Bb53835026C75DD91dC6 MultiCollateralSynth public constant synthseth_i = MultiCollateralSynth(0x4FB63c954Ef07EC74335Bb53835026C75DD91dC6); // https://etherscan.io/address/0x34A5ef81d18F3a305aE9C2d7DF42beef4c79031c TokenState public constant tokenstateseth_i = TokenState(0x34A5ef81d18F3a305aE9C2d7DF42beef4c79031c); // https://etherscan.io/address/0x5e74C9036fb86BD7eCdcb084a0673EFc32eA31cb ProxyERC20 public constant proxyseth_i = ProxyERC20(0x5e74C9036fb86BD7eCdcb084a0673EFc32eA31cb); // https://etherscan.io/address/0xe08518bA3d2467F7cA50eFE68AA00C5f78D4f3D6 MultiCollateralSynth public constant synthslink_i = MultiCollateralSynth(0xe08518bA3d2467F7cA50eFE68AA00C5f78D4f3D6); // https://etherscan.io/address/0x577D4a7395c6A5f46d9981a5F83fa7294926aBB0 TokenState public constant tokenstateslink_i = TokenState(0x577D4a7395c6A5f46d9981a5F83fa7294926aBB0); // https://etherscan.io/address/0xbBC455cb4F1B9e4bFC4B73970d360c8f032EfEE6 ProxyERC20 public constant proxyslink_i = ProxyERC20(0xbBC455cb4F1B9e4bFC4B73970d360c8f032EfEE6); // https://etherscan.io/address/0xB34F4d7c207D8979D05EDb0F63f174764Bd67825 MultiCollateralSynth public constant synthsada_i = MultiCollateralSynth(0xB34F4d7c207D8979D05EDb0F63f174764Bd67825); // https://etherscan.io/address/0x9956c5019a24fbd5B506AD070b771577bAc5c343 TokenState public constant tokenstatesada_i = TokenState(0x9956c5019a24fbd5B506AD070b771577bAc5c343); // https://etherscan.io/address/0xe36E2D3c7c34281FA3bC737950a68571736880A1 ProxyERC20 public constant proxysada_i = ProxyERC20(0xe36E2D3c7c34281FA3bC737950a68571736880A1); // https://etherscan.io/address/0x95aE43E5E96314E4afffcf19D9419111cd11169e MultiCollateralSynth public constant synthsaave_i = MultiCollateralSynth(0x95aE43E5E96314E4afffcf19D9419111cd11169e); // https://etherscan.io/address/0x9BcED8A8E3Ad81c9b146FFC880358f734A06f7c0 TokenState public constant tokenstatesaave_i = TokenState(0x9BcED8A8E3Ad81c9b146FFC880358f734A06f7c0); // https://etherscan.io/address/0xd2dF355C19471c8bd7D8A3aa27Ff4e26A21b4076 ProxyERC20 public constant proxysaave_i = ProxyERC20(0xd2dF355C19471c8bd7D8A3aa27Ff4e26A21b4076); // https://etherscan.io/address/0x27b45A4208b87A899009f45888139882477Acea5 MultiCollateralSynth public constant synthsdot_i = MultiCollateralSynth(0x27b45A4208b87A899009f45888139882477Acea5); // https://etherscan.io/address/0x73B1a2643507Cd30F11Dfcf2D974f4373E5BC077 TokenState public constant tokenstatesdot_i = TokenState(0x73B1a2643507Cd30F11Dfcf2D974f4373E5BC077); // https://etherscan.io/address/0x1715AC0743102BF5Cd58EfBB6Cf2dC2685d967b6 ProxyERC20 public constant proxysdot_i = ProxyERC20(0x1715AC0743102BF5Cd58EfBB6Cf2dC2685d967b6); // https://etherscan.io/address/0x6DF798ec713b33BE823b917F27820f2aA0cf7662 MultiCollateralSynth public constant synthsethbtc_i = MultiCollateralSynth(0x6DF798ec713b33BE823b917F27820f2aA0cf7662); // https://etherscan.io/address/0x042A7A0022A7695454ac5Be77a4860e50c9683fC TokenState public constant tokenstatesethbtc_i = TokenState(0x042A7A0022A7695454ac5Be77a4860e50c9683fC); // https://etherscan.io/address/0x104eDF1da359506548BFc7c25bA1E28C16a70235 ProxyERC20 public constant proxysethbtc_i = ProxyERC20(0x104eDF1da359506548BFc7c25bA1E28C16a70235); // https://etherscan.io/address/0xf533aeEe48f0e04E30c2F6A1f19FbB675469a124 MultiCollateralSynth public constant synthsdefi_i = MultiCollateralSynth(0xf533aeEe48f0e04E30c2F6A1f19FbB675469a124); // https://etherscan.io/address/0x7Ac2D37098a65B0f711CFfA3be635F1E6aCacFaB TokenState public constant tokenstatesdefi_i = TokenState(0x7Ac2D37098a65B0f711CFfA3be635F1E6aCacFaB); // https://etherscan.io/address/0xe1aFe1Fd76Fd88f78cBf599ea1846231B8bA3B6B ProxyERC20 public constant proxysdefi_i = ProxyERC20(0xe1aFe1Fd76Fd88f78cBf599ea1846231B8bA3B6B); // https://etherscan.io/address/0xE60E71E47Ca405946CF147CA9d7589a851DBcddC Issuer public constant issuer_i = Issuer(0xE60E71E47Ca405946CF147CA9d7589a851DBcddC); // ---------------------------------- // NEW CONTRACTS DEPLOYED TO BE ADDED // ---------------------------------- // https://etherscan.io/address/0x977d0DD7eA212E9ca1dcD4Ec15cd7Ceb135fa68D address public constant new_OneNetAggregatorDebtRatio_contract = 0x977d0DD7eA212E9ca1dcD4Ec15cd7Ceb135fa68D; // https://etherscan.io/address/0x696c905F8F8c006cA46e9808fE7e00049507798F address public constant new_SystemStatus_contract = 0x696c905F8F8c006cA46e9808fE7e00049507798F; // https://etherscan.io/address/0x6fA9E5923CBFDD39F0B625Bf1350Ffb50D5006b9 address public constant new_ExchangeRates_contract = 0x6fA9E5923CBFDD39F0B625Bf1350Ffb50D5006b9; // https://etherscan.io/address/0xcf1405b18dBCEA2893Abe635c88359C75878B9e1 address public constant new_OneNetAggregatorIssuedSynths_contract = 0xcf1405b18dBCEA2893Abe635c88359C75878B9e1; // https://etherscan.io/address/0x3B2f389AeE480238A49E3A9985cd6815370712eB address public constant new_FeePool_contract = 0x3B2f389AeE480238A49E3A9985cd6815370712eB; // https://etherscan.io/address/0x74E9a032B04D9732E826eECFC5c7A1C183602FB1 address public constant new_Exchanger_contract = 0x74E9a032B04D9732E826eECFC5c7A1C183602FB1; // https://etherscan.io/address/0xeAcaEd9581294b1b5cfb6B941d4B8B81B2005437 address public constant new_ExchangeCircuitBreaker_contract = 0xeAcaEd9581294b1b5cfb6B941d4B8B81B2005437; // https://etherscan.io/address/0x1620Aa736939597891C1940CF0d28b82566F9390 address public constant new_DebtCache_contract = 0x1620Aa736939597891C1940CF0d28b82566F9390; // https://etherscan.io/address/0xc51f137e19F1ae6944887388FD12b2b6dFD12594 address public constant new_SynthetixBridgeToOptimism_contract = 0xc51f137e19F1ae6944887388FD12b2b6dFD12594; // https://etherscan.io/address/0xE60E71E47Ca405946CF147CA9d7589a851DBcddC address public constant new_Issuer_contract = 0xE60E71E47Ca405946CF147CA9d7589a851DBcddC; // https://etherscan.io/address/0x7df9b3f8f1C011D8BD707430e97E747479DD532a address public constant new_SynthsUSD_contract = 0x7df9b3f8f1C011D8BD707430e97E747479DD532a; // https://etherscan.io/address/0x1b06a00Df0B27E7871E753720D4917a7D1aac68b address public constant new_SynthsEUR_contract = 0x1b06a00Df0B27E7871E753720D4917a7D1aac68b; // https://etherscan.io/address/0xB82f11f3168Ece7D56fe6a5679567948090de7C5 address public constant new_SynthsJPY_contract = 0xB82f11f3168Ece7D56fe6a5679567948090de7C5; // https://etherscan.io/address/0xC4546bDd93cDAADA6994e84Fb6F2722C620B019C address public constant new_SynthsAUD_contract = 0xC4546bDd93cDAADA6994e84Fb6F2722C620B019C; // https://etherscan.io/address/0xAE7A2C1e326e59f2dB2132652115a59E8Adb5eBf address public constant new_SynthsGBP_contract = 0xAE7A2C1e326e59f2dB2132652115a59E8Adb5eBf; // https://etherscan.io/address/0xCC83a57B080a4c7C86F0bB892Bc180C8C7F8791d address public constant new_SynthsCHF_contract = 0xCC83a57B080a4c7C86F0bB892Bc180C8C7F8791d; // https://etherscan.io/address/0x527637bE27640d6C3e751d24DC67129A6d13E11C address public constant new_SynthsKRW_contract = 0x527637bE27640d6C3e751d24DC67129A6d13E11C; // https://etherscan.io/address/0x4FB63c954Ef07EC74335Bb53835026C75DD91dC6 address public constant new_SynthsETH_contract = 0x4FB63c954Ef07EC74335Bb53835026C75DD91dC6; // https://etherscan.io/address/0x18FcC34bdEaaF9E3b69D2500343527c0c995b1d6 address public constant new_SynthsBTC_contract = 0x18FcC34bdEaaF9E3b69D2500343527c0c995b1d6; // https://etherscan.io/address/0xe08518bA3d2467F7cA50eFE68AA00C5f78D4f3D6 address public constant new_SynthsLINK_contract = 0xe08518bA3d2467F7cA50eFE68AA00C5f78D4f3D6; // https://etherscan.io/address/0xB34F4d7c207D8979D05EDb0F63f174764Bd67825 address public constant new_SynthsADA_contract = 0xB34F4d7c207D8979D05EDb0F63f174764Bd67825; // https://etherscan.io/address/0x95aE43E5E96314E4afffcf19D9419111cd11169e address public constant new_SynthsAAVE_contract = 0x95aE43E5E96314E4afffcf19D9419111cd11169e; // https://etherscan.io/address/0x27b45A4208b87A899009f45888139882477Acea5 address public constant new_SynthsDOT_contract = 0x27b45A4208b87A899009f45888139882477Acea5; // https://etherscan.io/address/0x6DF798ec713b33BE823b917F27820f2aA0cf7662 address public constant new_SynthsETHBTC_contract = 0x6DF798ec713b33BE823b917F27820f2aA0cf7662; // https://etherscan.io/address/0xf533aeEe48f0e04E30c2F6A1f19FbB675469a124 address public constant new_SynthsDEFI_contract = 0xf533aeEe48f0e04E30c2F6A1f19FbB675469a124; // https://etherscan.io/address/0x834Ef6c82D431Ac9A7A6B66325F185b2430780D7 address public constant new_FuturesMarketManager_contract = 0x834Ef6c82D431Ac9A7A6B66325F185b2430780D7; function migrate2() external { // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sUSD(); // Ensure the sUSD synth can write to its TokenState; tokenstatesusd_i.setAssociatedContract(new_SynthsUSD_contract); // Ensure the sUSD synth Proxy is correctly connected to the Synth; proxysusd_i.setTarget(Proxyable(new_SynthsUSD_contract)); // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sEUR(); // Ensure the sEUR synth can write to its TokenState; tokenstateseur_i.setAssociatedContract(new_SynthsEUR_contract); // Ensure the sEUR synth Proxy is correctly connected to the Synth; proxyseur_i.setTarget(Proxyable(new_SynthsEUR_contract)); // Ensure the ExchangeRates contract has the feed for sEUR; exchangerates_i.addAggregator("sEUR", 0xb49f677943BC038e9857d61E7d053CaA2C1734C1); // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sJPY(); // Ensure the sJPY synth can write to its TokenState; tokenstatesjpy_i.setAssociatedContract(new_SynthsJPY_contract); // Ensure the sJPY synth Proxy is correctly connected to the Synth; proxysjpy_i.setTarget(Proxyable(new_SynthsJPY_contract)); // Ensure the ExchangeRates contract has the feed for sJPY; exchangerates_i.addAggregator("sJPY", 0xBcE206caE7f0ec07b545EddE332A47C2F75bbeb3); // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sAUD(); // Ensure the sAUD synth can write to its TokenState; tokenstatesaud_i.setAssociatedContract(new_SynthsAUD_contract); // Ensure the sAUD synth Proxy is correctly connected to the Synth; proxysaud_i.setTarget(Proxyable(new_SynthsAUD_contract)); // Ensure the ExchangeRates contract has the feed for sAUD; exchangerates_i.addAggregator("sAUD", 0x77F9710E7d0A19669A13c055F62cd80d313dF022); // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sGBP(); // Ensure the sGBP synth can write to its TokenState; tokenstatesgbp_i.setAssociatedContract(new_SynthsGBP_contract); // Ensure the sGBP synth Proxy is correctly connected to the Synth; proxysgbp_i.setTarget(Proxyable(new_SynthsGBP_contract)); // Ensure the ExchangeRates contract has the feed for sGBP; exchangerates_i.addAggregator("sGBP", 0x5c0Ab2d9b5a7ed9f470386e82BB36A3613cDd4b5); // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sCHF(); // Ensure the sCHF synth can write to its TokenState; tokenstateschf_i.setAssociatedContract(new_SynthsCHF_contract); // Ensure the sCHF synth Proxy is correctly connected to the Synth; proxyschf_i.setTarget(Proxyable(new_SynthsCHF_contract)); // Ensure the ExchangeRates contract has the feed for sCHF; exchangerates_i.addAggregator("sCHF", 0x449d117117838fFA61263B61dA6301AA2a88B13A); // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sKRW(); // Ensure the sKRW synth can write to its TokenState; tokenstateskrw_i.setAssociatedContract(new_SynthsKRW_contract); // Ensure the sKRW synth Proxy is correctly connected to the Synth; proxyskrw_i.setTarget(Proxyable(new_SynthsKRW_contract)); // Ensure the ExchangeRates contract has the feed for sKRW; exchangerates_i.addAggregator("sKRW", 0x01435677FB11763550905594A16B645847C1d0F3); // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sBTC(); // Ensure the sBTC synth can write to its TokenState; tokenstatesbtc_i.setAssociatedContract(new_SynthsBTC_contract); // Ensure the sBTC synth Proxy is correctly connected to the Synth; proxysbtc_i.setTarget(Proxyable(new_SynthsBTC_contract)); // Ensure the ExchangeRates contract has the feed for sBTC; exchangerates_i.addAggregator("sBTC", 0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c); // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sETH(); // Ensure the sETH synth can write to its TokenState; tokenstateseth_i.setAssociatedContract(new_SynthsETH_contract); // Ensure the sETH synth Proxy is correctly connected to the Synth; proxyseth_i.setTarget(Proxyable(new_SynthsETH_contract)); // Ensure the ExchangeRates contract has the feed for sETH; exchangerates_i.addAggregator("sETH", 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419); // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sLINK(); // Ensure the sLINK synth can write to its TokenState; tokenstateslink_i.setAssociatedContract(new_SynthsLINK_contract); // Ensure the sLINK synth Proxy is correctly connected to the Synth; proxyslink_i.setTarget(Proxyable(new_SynthsLINK_contract)); // Ensure the ExchangeRates contract has the feed for sLINK; exchangerates_i.addAggregator("sLINK", 0x2c1d072e956AFFC0D435Cb7AC38EF18d24d9127c); // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sADA(); // Ensure the sADA synth can write to its TokenState; tokenstatesada_i.setAssociatedContract(new_SynthsADA_contract); // Ensure the sADA synth Proxy is correctly connected to the Synth; proxysada_i.setTarget(Proxyable(new_SynthsADA_contract)); // Ensure the ExchangeRates contract has the feed for sADA; exchangerates_i.addAggregator("sADA", 0xAE48c91dF1fE419994FFDa27da09D5aC69c30f55); // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sAAVE(); // Ensure the sAAVE synth can write to its TokenState; tokenstatesaave_i.setAssociatedContract(new_SynthsAAVE_contract); // Ensure the sAAVE synth Proxy is correctly connected to the Synth; proxysaave_i.setTarget(Proxyable(new_SynthsAAVE_contract)); // Ensure the ExchangeRates contract has the feed for sAAVE; exchangerates_i.addAggregator("sAAVE", 0x547a514d5e3769680Ce22B2361c10Ea13619e8a9); // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sDOT(); // Ensure the sDOT synth can write to its TokenState; tokenstatesdot_i.setAssociatedContract(new_SynthsDOT_contract); // Ensure the sDOT synth Proxy is correctly connected to the Synth; proxysdot_i.setTarget(Proxyable(new_SynthsDOT_contract)); // Ensure the ExchangeRates contract has the feed for sDOT; exchangerates_i.addAggregator("sDOT", 0x1C07AFb8E2B827c5A4739C6d59Ae3A5035f28734); // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sETHBTC(); // Ensure the sETHBTC synth can write to its TokenState; tokenstatesethbtc_i.setAssociatedContract(new_SynthsETHBTC_contract); // Ensure the sETHBTC synth Proxy is correctly connected to the Synth; proxysethbtc_i.setTarget(Proxyable(new_SynthsETHBTC_contract)); // Ensure the ExchangeRates contract has the feed for sETHBTC; exchangerates_i.addAggregator("sETHBTC", 0xAc559F25B1619171CbC396a50854A3240b6A4e99); // Ensure the new synth has the totalSupply from the previous one; copyTotalSupplyFrom_sDEFI(); // Ensure the sDEFI synth can write to its TokenState; tokenstatesdefi_i.setAssociatedContract(new_SynthsDEFI_contract); // Ensure the sDEFI synth Proxy is correctly connected to the Synth; proxysdefi_i.setTarget(Proxyable(new_SynthsDEFI_contract)); // Ensure the ExchangeRates contract has the feed for sDEFI; exchangerates_i.addAggregator("sDEFI", 0xa8E875F94138B0C5b51d1e1d5dE35bbDdd28EA87); // Add synths to the Issuer contract - batch 1; issuer_addSynths_96(); // SIP-120 Set the DEX price aggregator (uniswap TWAP oracle reader); exchangerates_i.setDexPriceAggregator(IDexPriceAggregator(0xf120F029Ac143633d1942e48aE2Dfa2036C5786c)); } function copyTotalSupplyFrom_sUSD() internal { // https://etherscan.io/address/0xAFDd6B5A8aB32156dBFb4060ff87F6d9E31191bA; Synth existingSynth = Synth(0xAFDd6B5A8aB32156dBFb4060ff87F6d9E31191bA); // https://etherscan.io/address/0x7df9b3f8f1C011D8BD707430e97E747479DD532a; Synth newSynth = Synth(0x7df9b3f8f1C011D8BD707430e97E747479DD532a); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sEUR() internal { // https://etherscan.io/address/0xe301da3d2D3e96e57D05b8E557656629cDdbe7A0; Synth existingSynth = Synth(0xe301da3d2D3e96e57D05b8E557656629cDdbe7A0); // https://etherscan.io/address/0x1b06a00Df0B27E7871E753720D4917a7D1aac68b; Synth newSynth = Synth(0x1b06a00Df0B27E7871E753720D4917a7D1aac68b); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sJPY() internal { // https://etherscan.io/address/0x4ed5c5D5793f86c8a85E1a96E37b6d374DE0E85A; Synth existingSynth = Synth(0x4ed5c5D5793f86c8a85E1a96E37b6d374DE0E85A); // https://etherscan.io/address/0xB82f11f3168Ece7D56fe6a5679567948090de7C5; Synth newSynth = Synth(0xB82f11f3168Ece7D56fe6a5679567948090de7C5); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sAUD() internal { // https://etherscan.io/address/0x005d19CA7ff9D79a5Bdf0805Fc01D9D7c53B6827; Synth existingSynth = Synth(0x005d19CA7ff9D79a5Bdf0805Fc01D9D7c53B6827); // https://etherscan.io/address/0xC4546bDd93cDAADA6994e84Fb6F2722C620B019C; Synth newSynth = Synth(0xC4546bDd93cDAADA6994e84Fb6F2722C620B019C); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sGBP() internal { // https://etherscan.io/address/0xde3892383965FBa6eC434bE6350F85f140098708; Synth existingSynth = Synth(0xde3892383965FBa6eC434bE6350F85f140098708); // https://etherscan.io/address/0xAE7A2C1e326e59f2dB2132652115a59E8Adb5eBf; Synth newSynth = Synth(0xAE7A2C1e326e59f2dB2132652115a59E8Adb5eBf); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sCHF() internal { // https://etherscan.io/address/0x39DDbbb113AF3434048b9d8018a3e99d67C6eE0D; Synth existingSynth = Synth(0x39DDbbb113AF3434048b9d8018a3e99d67C6eE0D); // https://etherscan.io/address/0xCC83a57B080a4c7C86F0bB892Bc180C8C7F8791d; Synth newSynth = Synth(0xCC83a57B080a4c7C86F0bB892Bc180C8C7F8791d); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sKRW() internal { // https://etherscan.io/address/0xe2f532c389deb5E42DCe53e78A9762949A885455; Synth existingSynth = Synth(0xe2f532c389deb5E42DCe53e78A9762949A885455); // https://etherscan.io/address/0x527637bE27640d6C3e751d24DC67129A6d13E11C; Synth newSynth = Synth(0x527637bE27640d6C3e751d24DC67129A6d13E11C); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sBTC() internal { // https://etherscan.io/address/0x2B3eb5eF0EF06f2E02ef60B3F36Be4793d321353; Synth existingSynth = Synth(0x2B3eb5eF0EF06f2E02ef60B3F36Be4793d321353); // https://etherscan.io/address/0x18FcC34bdEaaF9E3b69D2500343527c0c995b1d6; Synth newSynth = Synth(0x18FcC34bdEaaF9E3b69D2500343527c0c995b1d6); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sETH() internal { // https://etherscan.io/address/0xc70B42930BD8D30A79B55415deC3be60827559f7; Synth existingSynth = Synth(0xc70B42930BD8D30A79B55415deC3be60827559f7); // https://etherscan.io/address/0x4FB63c954Ef07EC74335Bb53835026C75DD91dC6; Synth newSynth = Synth(0x4FB63c954Ef07EC74335Bb53835026C75DD91dC6); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sLINK() internal { // https://etherscan.io/address/0x3FFE35c3d412150C3B91d3E22eBA60E16030C608; Synth existingSynth = Synth(0x3FFE35c3d412150C3B91d3E22eBA60E16030C608); // https://etherscan.io/address/0xe08518bA3d2467F7cA50eFE68AA00C5f78D4f3D6; Synth newSynth = Synth(0xe08518bA3d2467F7cA50eFE68AA00C5f78D4f3D6); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sADA() internal { // https://etherscan.io/address/0x8f9fa817200F5B95f9572c8Acf2b31410C00335a; Synth existingSynth = Synth(0x8f9fa817200F5B95f9572c8Acf2b31410C00335a); // https://etherscan.io/address/0xB34F4d7c207D8979D05EDb0F63f174764Bd67825; Synth newSynth = Synth(0xB34F4d7c207D8979D05EDb0F63f174764Bd67825); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sAAVE() internal { // https://etherscan.io/address/0x0705F0716b12a703d4F8832Ec7b97C61771f0361; Synth existingSynth = Synth(0x0705F0716b12a703d4F8832Ec7b97C61771f0361); // https://etherscan.io/address/0x95aE43E5E96314E4afffcf19D9419111cd11169e; Synth newSynth = Synth(0x95aE43E5E96314E4afffcf19D9419111cd11169e); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sDOT() internal { // https://etherscan.io/address/0xfA60918C4417b64E722ca15d79C751c1f24Ab995; Synth existingSynth = Synth(0xfA60918C4417b64E722ca15d79C751c1f24Ab995); // https://etherscan.io/address/0x27b45A4208b87A899009f45888139882477Acea5; Synth newSynth = Synth(0x27b45A4208b87A899009f45888139882477Acea5); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sETHBTC() internal { // https://etherscan.io/address/0xcc3aab773e2171b2E257Ee17001400eE378aa52B; Synth existingSynth = Synth(0xcc3aab773e2171b2E257Ee17001400eE378aa52B); // https://etherscan.io/address/0x6DF798ec713b33BE823b917F27820f2aA0cf7662; Synth newSynth = Synth(0x6DF798ec713b33BE823b917F27820f2aA0cf7662); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sDEFI() internal { // https://etherscan.io/address/0xe59dFC746D566EB40F92ed0B162004e24E3AC932; Synth existingSynth = Synth(0xe59dFC746D566EB40F92ed0B162004e24E3AC932); // https://etherscan.io/address/0xf533aeEe48f0e04E30c2F6A1f19FbB675469a124; Synth newSynth = Synth(0xf533aeEe48f0e04E30c2F6A1f19FbB675469a124); newSynth.setTotalSupply(existingSynth.totalSupply()); } function issuer_addSynths_96() internal { ISynth[] memory issuer_addSynths_synthsToAdd_96_0 = new ISynth[](15); issuer_addSynths_synthsToAdd_96_0[0] = ISynth(new_SynthsUSD_contract); issuer_addSynths_synthsToAdd_96_0[1] = ISynth(new_SynthsEUR_contract); issuer_addSynths_synthsToAdd_96_0[2] = ISynth(new_SynthsJPY_contract); issuer_addSynths_synthsToAdd_96_0[3] = ISynth(new_SynthsAUD_contract); issuer_addSynths_synthsToAdd_96_0[4] = ISynth(new_SynthsGBP_contract); issuer_addSynths_synthsToAdd_96_0[5] = ISynth(new_SynthsCHF_contract); issuer_addSynths_synthsToAdd_96_0[6] = ISynth(new_SynthsKRW_contract); issuer_addSynths_synthsToAdd_96_0[7] = ISynth(new_SynthsBTC_contract); issuer_addSynths_synthsToAdd_96_0[8] = ISynth(new_SynthsETH_contract); issuer_addSynths_synthsToAdd_96_0[9] = ISynth(new_SynthsLINK_contract); issuer_addSynths_synthsToAdd_96_0[10] = ISynth(new_SynthsADA_contract); issuer_addSynths_synthsToAdd_96_0[11] = ISynth(new_SynthsAAVE_contract); issuer_addSynths_synthsToAdd_96_0[12] = ISynth(new_SynthsDOT_contract); issuer_addSynths_synthsToAdd_96_0[13] = ISynth(new_SynthsETHBTC_contract); issuer_addSynths_synthsToAdd_96_0[14] = ISynth(new_SynthsDEFI_contract); issuer_i.addSynths(issuer_addSynths_synthsToAdd_96_0); } function addressresolver_importAddresses_0() external { bytes32[] memory addressresolver_importAddresses_names_0_0 = new bytes32[](28); addressresolver_importAddresses_names_0_0[0] = bytes32("OneNetAggregatorDebtRatio"); addressresolver_importAddresses_names_0_0[1] = bytes32("SystemStatus"); addressresolver_importAddresses_names_0_0[2] = bytes32("ExchangeRates"); addressresolver_importAddresses_names_0_0[3] = bytes32("OneNetAggregatorIssuedSynths"); addressresolver_importAddresses_names_0_0[4] = bytes32("FeePool"); addressresolver_importAddresses_names_0_0[5] = bytes32("Exchanger"); addressresolver_importAddresses_names_0_0[6] = bytes32("ExchangeCircuitBreaker"); addressresolver_importAddresses_names_0_0[7] = bytes32("DebtCache"); addressresolver_importAddresses_names_0_0[8] = bytes32("SynthetixBridgeToOptimism"); addressresolver_importAddresses_names_0_0[9] = bytes32("Issuer"); addressresolver_importAddresses_names_0_0[10] = bytes32("SynthsUSD"); addressresolver_importAddresses_names_0_0[11] = bytes32("SynthsEUR"); addressresolver_importAddresses_names_0_0[12] = bytes32("SynthsJPY"); addressresolver_importAddresses_names_0_0[13] = bytes32("SynthsAUD"); addressresolver_importAddresses_names_0_0[14] = bytes32("SynthsGBP"); addressresolver_importAddresses_names_0_0[15] = bytes32("SynthsCHF"); addressresolver_importAddresses_names_0_0[16] = bytes32("SynthsKRW"); addressresolver_importAddresses_names_0_0[17] = bytes32("SynthsETH"); addressresolver_importAddresses_names_0_0[18] = bytes32("SynthsBTC"); addressresolver_importAddresses_names_0_0[19] = bytes32("SynthsLINK"); addressresolver_importAddresses_names_0_0[20] = bytes32("SynthsADA"); addressresolver_importAddresses_names_0_0[21] = bytes32("SynthsAAVE"); addressresolver_importAddresses_names_0_0[22] = bytes32("SynthsDOT"); addressresolver_importAddresses_names_0_0[23] = bytes32("SynthsETHBTC"); addressresolver_importAddresses_names_0_0[24] = bytes32("SynthsDEFI"); addressresolver_importAddresses_names_0_0[25] = bytes32("FuturesMarketManager"); addressresolver_importAddresses_names_0_0[26] = bytes32("ext:AggregatorIssuedSynths"); addressresolver_importAddresses_names_0_0[27] = bytes32("ext:AggregatorDebtRatio"); address[] memory addressresolver_importAddresses_destinations_0_1 = new address[](28); addressresolver_importAddresses_destinations_0_1[0] = address(new_OneNetAggregatorDebtRatio_contract); addressresolver_importAddresses_destinations_0_1[1] = address(new_SystemStatus_contract); addressresolver_importAddresses_destinations_0_1[2] = address(new_ExchangeRates_contract); addressresolver_importAddresses_destinations_0_1[3] = address(new_OneNetAggregatorIssuedSynths_contract); addressresolver_importAddresses_destinations_0_1[4] = address(new_FeePool_contract); addressresolver_importAddresses_destinations_0_1[5] = address(new_Exchanger_contract); addressresolver_importAddresses_destinations_0_1[6] = address(new_ExchangeCircuitBreaker_contract); addressresolver_importAddresses_destinations_0_1[7] = address(new_DebtCache_contract); addressresolver_importAddresses_destinations_0_1[8] = address(new_SynthetixBridgeToOptimism_contract); addressresolver_importAddresses_destinations_0_1[9] = address(new_Issuer_contract); addressresolver_importAddresses_destinations_0_1[10] = address(new_SynthsUSD_contract); addressresolver_importAddresses_destinations_0_1[11] = address(new_SynthsEUR_contract); addressresolver_importAddresses_destinations_0_1[12] = address(new_SynthsJPY_contract); addressresolver_importAddresses_destinations_0_1[13] = address(new_SynthsAUD_contract); addressresolver_importAddresses_destinations_0_1[14] = address(new_SynthsGBP_contract); addressresolver_importAddresses_destinations_0_1[15] = address(new_SynthsCHF_contract); addressresolver_importAddresses_destinations_0_1[16] = address(new_SynthsKRW_contract); addressresolver_importAddresses_destinations_0_1[17] = address(new_SynthsETH_contract); addressresolver_importAddresses_destinations_0_1[18] = address(new_SynthsBTC_contract); addressresolver_importAddresses_destinations_0_1[19] = address(new_SynthsLINK_contract); addressresolver_importAddresses_destinations_0_1[20] = address(new_SynthsADA_contract); addressresolver_importAddresses_destinations_0_1[21] = address(new_SynthsAAVE_contract); addressresolver_importAddresses_destinations_0_1[22] = address(new_SynthsDOT_contract); addressresolver_importAddresses_destinations_0_1[23] = address(new_SynthsETHBTC_contract); addressresolver_importAddresses_destinations_0_1[24] = address(new_SynthsDEFI_contract); addressresolver_importAddresses_destinations_0_1[25] = address(new_FuturesMarketManager_contract); addressresolver_importAddresses_destinations_0_1[26] = address(new_OneNetAggregatorIssuedSynths_contract); addressresolver_importAddresses_destinations_0_1[27] = address(new_OneNetAggregatorDebtRatio_contract); addressresolver_i.importAddresses( addressresolver_importAddresses_names_0_0, addressresolver_importAddresses_destinations_0_1 ); } function addressresolver_rebuildCaches_1() external { MixinResolver[] memory addressresolver_rebuildCaches_destinations_1_0 = new MixinResolver[](20); addressresolver_rebuildCaches_destinations_1_0[0] = MixinResolver(0xDA4eF8520b1A57D7d63f1E249606D1A459698876); addressresolver_rebuildCaches_destinations_1_0[1] = MixinResolver(0xAD95C918af576c82Df740878C3E983CBD175daB6); addressresolver_rebuildCaches_destinations_1_0[2] = MixinResolver(new_FeePool_contract); addressresolver_rebuildCaches_destinations_1_0[3] = MixinResolver(0xE95A536cF5C7384FF1ef54819Dc54E03d0FF1979); addressresolver_rebuildCaches_destinations_1_0[4] = MixinResolver(new_DebtCache_contract); addressresolver_rebuildCaches_destinations_1_0[5] = MixinResolver(new_Exchanger_contract); addressresolver_rebuildCaches_destinations_1_0[6] = MixinResolver(new_ExchangeCircuitBreaker_contract); addressresolver_rebuildCaches_destinations_1_0[7] = MixinResolver(new_Issuer_contract); addressresolver_rebuildCaches_destinations_1_0[8] = MixinResolver(new_SynthsUSD_contract); addressresolver_rebuildCaches_destinations_1_0[9] = MixinResolver(new_SynthsEUR_contract); addressresolver_rebuildCaches_destinations_1_0[10] = MixinResolver(new_SynthsJPY_contract); addressresolver_rebuildCaches_destinations_1_0[11] = MixinResolver(new_SynthsAUD_contract); addressresolver_rebuildCaches_destinations_1_0[12] = MixinResolver(new_SynthsGBP_contract); addressresolver_rebuildCaches_destinations_1_0[13] = MixinResolver(new_SynthsCHF_contract); addressresolver_rebuildCaches_destinations_1_0[14] = MixinResolver(new_SynthsKRW_contract); addressresolver_rebuildCaches_destinations_1_0[15] = MixinResolver(new_SynthsBTC_contract); addressresolver_rebuildCaches_destinations_1_0[16] = MixinResolver(new_SynthsETH_contract); addressresolver_rebuildCaches_destinations_1_0[17] = MixinResolver(new_SynthsLINK_contract); addressresolver_rebuildCaches_destinations_1_0[18] = MixinResolver(new_SynthsADA_contract); addressresolver_rebuildCaches_destinations_1_0[19] = MixinResolver(new_SynthsAAVE_contract); addressresolver_i.rebuildCaches(addressresolver_rebuildCaches_destinations_1_0); } function addressresolver_rebuildCaches_2() external { MixinResolver[] memory addressresolver_rebuildCaches_destinations_2_0 = new MixinResolver[](16); addressresolver_rebuildCaches_destinations_2_0[0] = MixinResolver(new_SynthsDOT_contract); addressresolver_rebuildCaches_destinations_2_0[1] = MixinResolver(new_SynthsETHBTC_contract); addressresolver_rebuildCaches_destinations_2_0[2] = MixinResolver(new_SynthsDEFI_contract); addressresolver_rebuildCaches_destinations_2_0[3] = MixinResolver(0x5c8344bcdC38F1aB5EB5C1d4a35DdEeA522B5DfA); addressresolver_rebuildCaches_destinations_2_0[4] = MixinResolver(0xaa03aB31b55DceEeF845C8d17890CC61cD98eD04); addressresolver_rebuildCaches_destinations_2_0[5] = MixinResolver(0x1F2c3a1046c32729862fcB038369696e3273a516); addressresolver_rebuildCaches_destinations_2_0[6] = MixinResolver(0x7C22547779c8aa41bAE79E03E8383a0BefBCecf0); addressresolver_rebuildCaches_destinations_2_0[7] = MixinResolver(0xC1AAE9d18bBe386B102435a8632C8063d31e747C); addressresolver_rebuildCaches_destinations_2_0[8] = MixinResolver(0x067e398605E84F2D0aEEC1806e62768C5110DCc6); addressresolver_rebuildCaches_destinations_2_0[9] = MixinResolver(new_ExchangeRates_contract); addressresolver_rebuildCaches_destinations_2_0[10] = MixinResolver(new_SynthetixBridgeToOptimism_contract); addressresolver_rebuildCaches_destinations_2_0[11] = MixinResolver(0x02f9bC46beD33acdB9cb002fe346734CeF8a9480); addressresolver_rebuildCaches_destinations_2_0[12] = MixinResolver(0x62922670313bf6b41C580143d1f6C173C5C20019); addressresolver_rebuildCaches_destinations_2_0[13] = MixinResolver(0x89FCb32F29e509cc42d0C8b6f058C993013A843F); addressresolver_rebuildCaches_destinations_2_0[14] = MixinResolver(0xe533139Af961c9747356D947838c98451015e234); addressresolver_rebuildCaches_destinations_2_0[15] = MixinResolver(0x7A3d898b717e50a96fd8b232E9d15F0A547A7eeb); addressresolver_i.rebuildCaches(addressresolver_rebuildCaches_destinations_2_0); } }
solhint-disable contract-name-camelcase ---------------------------- EXISTING SYNTHETIX CONTRACTS ---------------------------- https:etherscan.io/address/0x823bE81bbF96BEc0e25CA13170F5AaCb5B79ba83 https:etherscan.io/address/0xb440DD674e1243644791a4AdfE3A2AbB0A92d309 https:etherscan.io/address/0xC9DFff5fA5605fd94F8B7927b892F2B57391e8bB https:etherscan.io/address/0x545973f28950f50fc6c7F52AAb4Ad214A27C0564 https:etherscan.io/address/0x696c905F8F8c006cA46e9808fE7e00049507798F https:etherscan.io/address/0xb671F2210B1F6621A2607EA63E6B2DC3e2464d1F https:etherscan.io/address/0x3B2f389AeE480238A49E3A9985cd6815370712eB https:etherscan.io/address/0x1620Aa736939597891C1940CF0d28b82566F9390 https:etherscan.io/address/0x6fA9E5923CBFDD39F0B625Bf1350Ffb50D5006b9 https:etherscan.io/address/0x7df9b3f8f1C011D8BD707430e97E747479DD532a https:etherscan.io/address/0x05a9CBe762B36632b3594DA4F082340E0e5343e8 https:etherscan.io/address/0x57Ab1ec28D129707052df4dF418D58a2D46d5f51 https:etherscan.io/address/0x1b06a00Df0B27E7871E753720D4917a7D1aac68b https:etherscan.io/address/0x6568D9e750fC44AF00f857885Dfb8281c00529c4 https:etherscan.io/address/0xD71eCFF9342A5Ced620049e616c5035F1dB98620 https:etherscan.io/address/0xB82f11f3168Ece7D56fe6a5679567948090de7C5 https:etherscan.io/address/0x4dFACfB15514C21c991ff75Bc7Bf6Fb1F98361ed https:etherscan.io/address/0xF6b1C627e95BFc3c1b4c9B825a032Ff0fBf3e07d https:etherscan.io/address/0xC4546bDd93cDAADA6994e84Fb6F2722C620B019C https:etherscan.io/address/0xCb29D2cf2C65d3Be1d00F07f3441390432D55203 https:etherscan.io/address/0xF48e200EAF9906362BB1442fca31e0835773b8B4 https:etherscan.io/address/0xAE7A2C1e326e59f2dB2132652115a59E8Adb5eBf https:etherscan.io/address/0x7e88D19A79b291cfE5696d496055f7e57F537A75 https:etherscan.io/address/0x97fe22E7341a0Cd8Db6F6C021A24Dc8f4DAD855F https:etherscan.io/address/0xCC83a57B080a4c7C86F0bB892Bc180C8C7F8791d https:etherscan.io/address/0x52496fE8a4feaEFe14d9433E00D48E6929c13deC https:etherscan.io/address/0x0F83287FF768D1c1e17a42F44d644D7F22e8ee1d https:etherscan.io/address/0x527637bE27640d6C3e751d24DC67129A6d13E11C https:etherscan.io/address/0x93B6e9FbBd2c32a0DC3C2B943B7C3CBC2fE23730 https:etherscan.io/address/0x269895a3dF4D73b077Fc823dD6dA1B95f72Aaf9B https:etherscan.io/address/0x18FcC34bdEaaF9E3b69D2500343527c0c995b1d6 https:etherscan.io/address/0x4F6296455F8d754c19821cF1EC8FeBF2cD456E67 https:etherscan.io/address/0xfE18be6b3Bd88A2D2A7f928d00292E7a9963CfC6 https:etherscan.io/address/0x4FB63c954Ef07EC74335Bb53835026C75DD91dC6 https:etherscan.io/address/0x34A5ef81d18F3a305aE9C2d7DF42beef4c79031c https:etherscan.io/address/0x5e74C9036fb86BD7eCdcb084a0673EFc32eA31cb https:etherscan.io/address/0xe08518bA3d2467F7cA50eFE68AA00C5f78D4f3D6 https:etherscan.io/address/0x577D4a7395c6A5f46d9981a5F83fa7294926aBB0 https:etherscan.io/address/0xbBC455cb4F1B9e4bFC4B73970d360c8f032EfEE6 https:etherscan.io/address/0xB34F4d7c207D8979D05EDb0F63f174764Bd67825 https:etherscan.io/address/0x9956c5019a24fbd5B506AD070b771577bAc5c343 https:etherscan.io/address/0xe36E2D3c7c34281FA3bC737950a68571736880A1 https:etherscan.io/address/0x95aE43E5E96314E4afffcf19D9419111cd11169e https:etherscan.io/address/0x9BcED8A8E3Ad81c9b146FFC880358f734A06f7c0 https:etherscan.io/address/0xd2dF355C19471c8bd7D8A3aa27Ff4e26A21b4076 https:etherscan.io/address/0x27b45A4208b87A899009f45888139882477Acea5 https:etherscan.io/address/0x73B1a2643507Cd30F11Dfcf2D974f4373E5BC077 https:etherscan.io/address/0x1715AC0743102BF5Cd58EfBB6Cf2dC2685d967b6 https:etherscan.io/address/0x6DF798ec713b33BE823b917F27820f2aA0cf7662 https:etherscan.io/address/0x042A7A0022A7695454ac5Be77a4860e50c9683fC https:etherscan.io/address/0x104eDF1da359506548BFc7c25bA1E28C16a70235 https:etherscan.io/address/0xf533aeEe48f0e04E30c2F6A1f19FbB675469a124 https:etherscan.io/address/0x7Ac2D37098a65B0f711CFfA3be635F1E6aCacFaB https:etherscan.io/address/0xe1aFe1Fd76Fd88f78cBf599ea1846231B8bA3B6B https:etherscan.io/address/0xE60E71E47Ca405946CF147CA9d7589a851DBcddC ---------------------------------- NEW CONTRACTS DEPLOYED TO BE ADDED ---------------------------------- https:etherscan.io/address/0x977d0DD7eA212E9ca1dcD4Ec15cd7Ceb135fa68D https:etherscan.io/address/0x696c905F8F8c006cA46e9808fE7e00049507798F https:etherscan.io/address/0x6fA9E5923CBFDD39F0B625Bf1350Ffb50D5006b9 https:etherscan.io/address/0xcf1405b18dBCEA2893Abe635c88359C75878B9e1 https:etherscan.io/address/0x3B2f389AeE480238A49E3A9985cd6815370712eB https:etherscan.io/address/0x74E9a032B04D9732E826eECFC5c7A1C183602FB1 https:etherscan.io/address/0xeAcaEd9581294b1b5cfb6B941d4B8B81B2005437 https:etherscan.io/address/0x1620Aa736939597891C1940CF0d28b82566F9390 https:etherscan.io/address/0xc51f137e19F1ae6944887388FD12b2b6dFD12594 https:etherscan.io/address/0xE60E71E47Ca405946CF147CA9d7589a851DBcddC https:etherscan.io/address/0x7df9b3f8f1C011D8BD707430e97E747479DD532a https:etherscan.io/address/0x1b06a00Df0B27E7871E753720D4917a7D1aac68b https:etherscan.io/address/0xB82f11f3168Ece7D56fe6a5679567948090de7C5 https:etherscan.io/address/0xC4546bDd93cDAADA6994e84Fb6F2722C620B019C https:etherscan.io/address/0xAE7A2C1e326e59f2dB2132652115a59E8Adb5eBf https:etherscan.io/address/0xCC83a57B080a4c7C86F0bB892Bc180C8C7F8791d https:etherscan.io/address/0x527637bE27640d6C3e751d24DC67129A6d13E11C https:etherscan.io/address/0x4FB63c954Ef07EC74335Bb53835026C75DD91dC6 https:etherscan.io/address/0x18FcC34bdEaaF9E3b69D2500343527c0c995b1d6 https:etherscan.io/address/0xe08518bA3d2467F7cA50eFE68AA00C5f78D4f3D6 https:etherscan.io/address/0xB34F4d7c207D8979D05EDb0F63f174764Bd67825 https:etherscan.io/address/0x95aE43E5E96314E4afffcf19D9419111cd11169e https:etherscan.io/address/0x27b45A4208b87A899009f45888139882477Acea5 https:etherscan.io/address/0x6DF798ec713b33BE823b917F27820f2aA0cf7662 https:etherscan.io/address/0xf533aeEe48f0e04E30c2F6A1f19FbB675469a124 https:etherscan.io/address/0x834Ef6c82D431Ac9A7A6B66325F185b2430780D7
library MigrationLib_Diphda { AddressResolver public constant addressresolver_i = AddressResolver(0x823bE81bbF96BEc0e25CA13170F5AaCb5B79ba83); Proxy public constant proxyfeepool_i = Proxy(0xb440DD674e1243644791a4AdfE3A2AbB0A92d309); FeePoolEternalStorage public constant feepooleternalstorage_i = FeePoolEternalStorage(0xC9DFff5fA5605fd94F8B7927b892F2B57391e8bB); ExchangeState public constant exchangestate_i = ExchangeState(0x545973f28950f50fc6c7F52AAb4Ad214A27C0564); SystemStatus public constant systemstatus_i = SystemStatus(0x696c905F8F8c006cA46e9808fE7e00049507798F); RewardEscrow public constant rewardescrow_i = RewardEscrow(0xb671F2210B1F6621A2607EA63E6B2DC3e2464d1F); FeePool public constant feepool_i = FeePool(0x3B2f389AeE480238A49E3A9985cd6815370712eB); DebtCache public constant debtcache_i = DebtCache(0x1620Aa736939597891C1940CF0d28b82566F9390); ExchangeRatesWithDexPricing public constant exchangerates_i = ExchangeRatesWithDexPricing(0x6fA9E5923CBFDD39F0B625Bf1350Ffb50D5006b9); MultiCollateralSynth public constant synthsusd_i = MultiCollateralSynth(0x7df9b3f8f1C011D8BD707430e97E747479DD532a); TokenState public constant tokenstatesusd_i = TokenState(0x05a9CBe762B36632b3594DA4F082340E0e5343e8); Proxy public constant proxysusd_i = Proxy(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51); MultiCollateralSynth public constant synthseur_i = MultiCollateralSynth(0x1b06a00Df0B27E7871E753720D4917a7D1aac68b); TokenState public constant tokenstateseur_i = TokenState(0x6568D9e750fC44AF00f857885Dfb8281c00529c4); ProxyERC20 public constant proxyseur_i = ProxyERC20(0xD71eCFF9342A5Ced620049e616c5035F1dB98620); MultiCollateralSynth public constant synthsjpy_i = MultiCollateralSynth(0xB82f11f3168Ece7D56fe6a5679567948090de7C5); TokenState public constant tokenstatesjpy_i = TokenState(0x4dFACfB15514C21c991ff75Bc7Bf6Fb1F98361ed); ProxyERC20 public constant proxysjpy_i = ProxyERC20(0xF6b1C627e95BFc3c1b4c9B825a032Ff0fBf3e07d); MultiCollateralSynth public constant synthsaud_i = MultiCollateralSynth(0xC4546bDd93cDAADA6994e84Fb6F2722C620B019C); TokenState public constant tokenstatesaud_i = TokenState(0xCb29D2cf2C65d3Be1d00F07f3441390432D55203); ProxyERC20 public constant proxysaud_i = ProxyERC20(0xF48e200EAF9906362BB1442fca31e0835773b8B4); MultiCollateralSynth public constant synthsgbp_i = MultiCollateralSynth(0xAE7A2C1e326e59f2dB2132652115a59E8Adb5eBf); TokenState public constant tokenstatesgbp_i = TokenState(0x7e88D19A79b291cfE5696d496055f7e57F537A75); ProxyERC20 public constant proxysgbp_i = ProxyERC20(0x97fe22E7341a0Cd8Db6F6C021A24Dc8f4DAD855F); MultiCollateralSynth public constant synthschf_i = MultiCollateralSynth(0xCC83a57B080a4c7C86F0bB892Bc180C8C7F8791d); TokenState public constant tokenstateschf_i = TokenState(0x52496fE8a4feaEFe14d9433E00D48E6929c13deC); ProxyERC20 public constant proxyschf_i = ProxyERC20(0x0F83287FF768D1c1e17a42F44d644D7F22e8ee1d); MultiCollateralSynth public constant synthskrw_i = MultiCollateralSynth(0x527637bE27640d6C3e751d24DC67129A6d13E11C); TokenState public constant tokenstateskrw_i = TokenState(0x93B6e9FbBd2c32a0DC3C2B943B7C3CBC2fE23730); ProxyERC20 public constant proxyskrw_i = ProxyERC20(0x269895a3dF4D73b077Fc823dD6dA1B95f72Aaf9B); MultiCollateralSynth public constant synthsbtc_i = MultiCollateralSynth(0x18FcC34bdEaaF9E3b69D2500343527c0c995b1d6); TokenState public constant tokenstatesbtc_i = TokenState(0x4F6296455F8d754c19821cF1EC8FeBF2cD456E67); ProxyERC20 public constant proxysbtc_i = ProxyERC20(0xfE18be6b3Bd88A2D2A7f928d00292E7a9963CfC6); MultiCollateralSynth public constant synthseth_i = MultiCollateralSynth(0x4FB63c954Ef07EC74335Bb53835026C75DD91dC6); TokenState public constant tokenstateseth_i = TokenState(0x34A5ef81d18F3a305aE9C2d7DF42beef4c79031c); ProxyERC20 public constant proxyseth_i = ProxyERC20(0x5e74C9036fb86BD7eCdcb084a0673EFc32eA31cb); MultiCollateralSynth public constant synthslink_i = MultiCollateralSynth(0xe08518bA3d2467F7cA50eFE68AA00C5f78D4f3D6); TokenState public constant tokenstateslink_i = TokenState(0x577D4a7395c6A5f46d9981a5F83fa7294926aBB0); ProxyERC20 public constant proxyslink_i = ProxyERC20(0xbBC455cb4F1B9e4bFC4B73970d360c8f032EfEE6); MultiCollateralSynth public constant synthsada_i = MultiCollateralSynth(0xB34F4d7c207D8979D05EDb0F63f174764Bd67825); TokenState public constant tokenstatesada_i = TokenState(0x9956c5019a24fbd5B506AD070b771577bAc5c343); ProxyERC20 public constant proxysada_i = ProxyERC20(0xe36E2D3c7c34281FA3bC737950a68571736880A1); MultiCollateralSynth public constant synthsaave_i = MultiCollateralSynth(0x95aE43E5E96314E4afffcf19D9419111cd11169e); TokenState public constant tokenstatesaave_i = TokenState(0x9BcED8A8E3Ad81c9b146FFC880358f734A06f7c0); ProxyERC20 public constant proxysaave_i = ProxyERC20(0xd2dF355C19471c8bd7D8A3aa27Ff4e26A21b4076); MultiCollateralSynth public constant synthsdot_i = MultiCollateralSynth(0x27b45A4208b87A899009f45888139882477Acea5); TokenState public constant tokenstatesdot_i = TokenState(0x73B1a2643507Cd30F11Dfcf2D974f4373E5BC077); ProxyERC20 public constant proxysdot_i = ProxyERC20(0x1715AC0743102BF5Cd58EfBB6Cf2dC2685d967b6); MultiCollateralSynth public constant synthsethbtc_i = MultiCollateralSynth(0x6DF798ec713b33BE823b917F27820f2aA0cf7662); TokenState public constant tokenstatesethbtc_i = TokenState(0x042A7A0022A7695454ac5Be77a4860e50c9683fC); ProxyERC20 public constant proxysethbtc_i = ProxyERC20(0x104eDF1da359506548BFc7c25bA1E28C16a70235); MultiCollateralSynth public constant synthsdefi_i = MultiCollateralSynth(0xf533aeEe48f0e04E30c2F6A1f19FbB675469a124); TokenState public constant tokenstatesdefi_i = TokenState(0x7Ac2D37098a65B0f711CFfA3be635F1E6aCacFaB); ProxyERC20 public constant proxysdefi_i = ProxyERC20(0xe1aFe1Fd76Fd88f78cBf599ea1846231B8bA3B6B); Issuer public constant issuer_i = Issuer(0xE60E71E47Ca405946CF147CA9d7589a851DBcddC); address public constant new_OneNetAggregatorDebtRatio_contract = 0x977d0DD7eA212E9ca1dcD4Ec15cd7Ceb135fa68D; address public constant new_SystemStatus_contract = 0x696c905F8F8c006cA46e9808fE7e00049507798F; address public constant new_ExchangeRates_contract = 0x6fA9E5923CBFDD39F0B625Bf1350Ffb50D5006b9; address public constant new_OneNetAggregatorIssuedSynths_contract = 0xcf1405b18dBCEA2893Abe635c88359C75878B9e1; address public constant new_FeePool_contract = 0x3B2f389AeE480238A49E3A9985cd6815370712eB; address public constant new_Exchanger_contract = 0x74E9a032B04D9732E826eECFC5c7A1C183602FB1; address public constant new_ExchangeCircuitBreaker_contract = 0xeAcaEd9581294b1b5cfb6B941d4B8B81B2005437; address public constant new_DebtCache_contract = 0x1620Aa736939597891C1940CF0d28b82566F9390; address public constant new_SynthetixBridgeToOptimism_contract = 0xc51f137e19F1ae6944887388FD12b2b6dFD12594; address public constant new_Issuer_contract = 0xE60E71E47Ca405946CF147CA9d7589a851DBcddC; address public constant new_SynthsUSD_contract = 0x7df9b3f8f1C011D8BD707430e97E747479DD532a; address public constant new_SynthsEUR_contract = 0x1b06a00Df0B27E7871E753720D4917a7D1aac68b; address public constant new_SynthsJPY_contract = 0xB82f11f3168Ece7D56fe6a5679567948090de7C5; address public constant new_SynthsAUD_contract = 0xC4546bDd93cDAADA6994e84Fb6F2722C620B019C; address public constant new_SynthsGBP_contract = 0xAE7A2C1e326e59f2dB2132652115a59E8Adb5eBf; address public constant new_SynthsCHF_contract = 0xCC83a57B080a4c7C86F0bB892Bc180C8C7F8791d; address public constant new_SynthsKRW_contract = 0x527637bE27640d6C3e751d24DC67129A6d13E11C; address public constant new_SynthsETH_contract = 0x4FB63c954Ef07EC74335Bb53835026C75DD91dC6; address public constant new_SynthsBTC_contract = 0x18FcC34bdEaaF9E3b69D2500343527c0c995b1d6; address public constant new_SynthsLINK_contract = 0xe08518bA3d2467F7cA50eFE68AA00C5f78D4f3D6; address public constant new_SynthsADA_contract = 0xB34F4d7c207D8979D05EDb0F63f174764Bd67825; address public constant new_SynthsAAVE_contract = 0x95aE43E5E96314E4afffcf19D9419111cd11169e; address public constant new_SynthsDOT_contract = 0x27b45A4208b87A899009f45888139882477Acea5; address public constant new_SynthsETHBTC_contract = 0x6DF798ec713b33BE823b917F27820f2aA0cf7662; address public constant new_SynthsDEFI_contract = 0xf533aeEe48f0e04E30c2F6A1f19FbB675469a124; address public constant new_FuturesMarketManager_contract = 0x834Ef6c82D431Ac9A7A6B66325F185b2430780D7; function migrate2() external { copyTotalSupplyFrom_sUSD(); tokenstatesusd_i.setAssociatedContract(new_SynthsUSD_contract); proxysusd_i.setTarget(Proxyable(new_SynthsUSD_contract)); copyTotalSupplyFrom_sEUR(); tokenstateseur_i.setAssociatedContract(new_SynthsEUR_contract); proxyseur_i.setTarget(Proxyable(new_SynthsEUR_contract)); exchangerates_i.addAggregator("sEUR", 0xb49f677943BC038e9857d61E7d053CaA2C1734C1); copyTotalSupplyFrom_sJPY(); tokenstatesjpy_i.setAssociatedContract(new_SynthsJPY_contract); proxysjpy_i.setTarget(Proxyable(new_SynthsJPY_contract)); exchangerates_i.addAggregator("sJPY", 0xBcE206caE7f0ec07b545EddE332A47C2F75bbeb3); copyTotalSupplyFrom_sAUD(); tokenstatesaud_i.setAssociatedContract(new_SynthsAUD_contract); proxysaud_i.setTarget(Proxyable(new_SynthsAUD_contract)); exchangerates_i.addAggregator("sAUD", 0x77F9710E7d0A19669A13c055F62cd80d313dF022); copyTotalSupplyFrom_sGBP(); tokenstatesgbp_i.setAssociatedContract(new_SynthsGBP_contract); proxysgbp_i.setTarget(Proxyable(new_SynthsGBP_contract)); exchangerates_i.addAggregator("sGBP", 0x5c0Ab2d9b5a7ed9f470386e82BB36A3613cDd4b5); copyTotalSupplyFrom_sCHF(); tokenstateschf_i.setAssociatedContract(new_SynthsCHF_contract); proxyschf_i.setTarget(Proxyable(new_SynthsCHF_contract)); exchangerates_i.addAggregator("sCHF", 0x449d117117838fFA61263B61dA6301AA2a88B13A); copyTotalSupplyFrom_sKRW(); tokenstateskrw_i.setAssociatedContract(new_SynthsKRW_contract); proxyskrw_i.setTarget(Proxyable(new_SynthsKRW_contract)); exchangerates_i.addAggregator("sKRW", 0x01435677FB11763550905594A16B645847C1d0F3); copyTotalSupplyFrom_sBTC(); tokenstatesbtc_i.setAssociatedContract(new_SynthsBTC_contract); proxysbtc_i.setTarget(Proxyable(new_SynthsBTC_contract)); exchangerates_i.addAggregator("sBTC", 0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c); copyTotalSupplyFrom_sETH(); tokenstateseth_i.setAssociatedContract(new_SynthsETH_contract); proxyseth_i.setTarget(Proxyable(new_SynthsETH_contract)); exchangerates_i.addAggregator("sETH", 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419); copyTotalSupplyFrom_sLINK(); tokenstateslink_i.setAssociatedContract(new_SynthsLINK_contract); proxyslink_i.setTarget(Proxyable(new_SynthsLINK_contract)); exchangerates_i.addAggregator("sLINK", 0x2c1d072e956AFFC0D435Cb7AC38EF18d24d9127c); copyTotalSupplyFrom_sADA(); tokenstatesada_i.setAssociatedContract(new_SynthsADA_contract); proxysada_i.setTarget(Proxyable(new_SynthsADA_contract)); exchangerates_i.addAggregator("sADA", 0xAE48c91dF1fE419994FFDa27da09D5aC69c30f55); copyTotalSupplyFrom_sAAVE(); tokenstatesaave_i.setAssociatedContract(new_SynthsAAVE_contract); proxysaave_i.setTarget(Proxyable(new_SynthsAAVE_contract)); exchangerates_i.addAggregator("sAAVE", 0x547a514d5e3769680Ce22B2361c10Ea13619e8a9); copyTotalSupplyFrom_sDOT(); tokenstatesdot_i.setAssociatedContract(new_SynthsDOT_contract); proxysdot_i.setTarget(Proxyable(new_SynthsDOT_contract)); exchangerates_i.addAggregator("sDOT", 0x1C07AFb8E2B827c5A4739C6d59Ae3A5035f28734); copyTotalSupplyFrom_sETHBTC(); tokenstatesethbtc_i.setAssociatedContract(new_SynthsETHBTC_contract); proxysethbtc_i.setTarget(Proxyable(new_SynthsETHBTC_contract)); exchangerates_i.addAggregator("sETHBTC", 0xAc559F25B1619171CbC396a50854A3240b6A4e99); copyTotalSupplyFrom_sDEFI(); tokenstatesdefi_i.setAssociatedContract(new_SynthsDEFI_contract); proxysdefi_i.setTarget(Proxyable(new_SynthsDEFI_contract)); exchangerates_i.addAggregator("sDEFI", 0xa8E875F94138B0C5b51d1e1d5dE35bbDdd28EA87); issuer_addSynths_96(); exchangerates_i.setDexPriceAggregator(IDexPriceAggregator(0xf120F029Ac143633d1942e48aE2Dfa2036C5786c)); } function copyTotalSupplyFrom_sUSD() internal { Synth existingSynth = Synth(0xAFDd6B5A8aB32156dBFb4060ff87F6d9E31191bA); Synth newSynth = Synth(0x7df9b3f8f1C011D8BD707430e97E747479DD532a); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sEUR() internal { Synth existingSynth = Synth(0xe301da3d2D3e96e57D05b8E557656629cDdbe7A0); Synth newSynth = Synth(0x1b06a00Df0B27E7871E753720D4917a7D1aac68b); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sJPY() internal { Synth existingSynth = Synth(0x4ed5c5D5793f86c8a85E1a96E37b6d374DE0E85A); Synth newSynth = Synth(0xB82f11f3168Ece7D56fe6a5679567948090de7C5); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sAUD() internal { Synth existingSynth = Synth(0x005d19CA7ff9D79a5Bdf0805Fc01D9D7c53B6827); Synth newSynth = Synth(0xC4546bDd93cDAADA6994e84Fb6F2722C620B019C); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sGBP() internal { Synth existingSynth = Synth(0xde3892383965FBa6eC434bE6350F85f140098708); Synth newSynth = Synth(0xAE7A2C1e326e59f2dB2132652115a59E8Adb5eBf); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sCHF() internal { Synth existingSynth = Synth(0x39DDbbb113AF3434048b9d8018a3e99d67C6eE0D); Synth newSynth = Synth(0xCC83a57B080a4c7C86F0bB892Bc180C8C7F8791d); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sKRW() internal { Synth existingSynth = Synth(0xe2f532c389deb5E42DCe53e78A9762949A885455); Synth newSynth = Synth(0x527637bE27640d6C3e751d24DC67129A6d13E11C); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sBTC() internal { Synth existingSynth = Synth(0x2B3eb5eF0EF06f2E02ef60B3F36Be4793d321353); Synth newSynth = Synth(0x18FcC34bdEaaF9E3b69D2500343527c0c995b1d6); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sETH() internal { Synth existingSynth = Synth(0xc70B42930BD8D30A79B55415deC3be60827559f7); Synth newSynth = Synth(0x4FB63c954Ef07EC74335Bb53835026C75DD91dC6); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sLINK() internal { Synth existingSynth = Synth(0x3FFE35c3d412150C3B91d3E22eBA60E16030C608); Synth newSynth = Synth(0xe08518bA3d2467F7cA50eFE68AA00C5f78D4f3D6); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sADA() internal { Synth existingSynth = Synth(0x8f9fa817200F5B95f9572c8Acf2b31410C00335a); Synth newSynth = Synth(0xB34F4d7c207D8979D05EDb0F63f174764Bd67825); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sAAVE() internal { Synth existingSynth = Synth(0x0705F0716b12a703d4F8832Ec7b97C61771f0361); Synth newSynth = Synth(0x95aE43E5E96314E4afffcf19D9419111cd11169e); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sDOT() internal { Synth existingSynth = Synth(0xfA60918C4417b64E722ca15d79C751c1f24Ab995); Synth newSynth = Synth(0x27b45A4208b87A899009f45888139882477Acea5); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sETHBTC() internal { Synth existingSynth = Synth(0xcc3aab773e2171b2E257Ee17001400eE378aa52B); Synth newSynth = Synth(0x6DF798ec713b33BE823b917F27820f2aA0cf7662); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sDEFI() internal { Synth existingSynth = Synth(0xe59dFC746D566EB40F92ed0B162004e24E3AC932); Synth newSynth = Synth(0xf533aeEe48f0e04E30c2F6A1f19FbB675469a124); newSynth.setTotalSupply(existingSynth.totalSupply()); } function issuer_addSynths_96() internal { ISynth[] memory issuer_addSynths_synthsToAdd_96_0 = new ISynth[](15); issuer_addSynths_synthsToAdd_96_0[0] = ISynth(new_SynthsUSD_contract); issuer_addSynths_synthsToAdd_96_0[1] = ISynth(new_SynthsEUR_contract); issuer_addSynths_synthsToAdd_96_0[2] = ISynth(new_SynthsJPY_contract); issuer_addSynths_synthsToAdd_96_0[3] = ISynth(new_SynthsAUD_contract); issuer_addSynths_synthsToAdd_96_0[4] = ISynth(new_SynthsGBP_contract); issuer_addSynths_synthsToAdd_96_0[5] = ISynth(new_SynthsCHF_contract); issuer_addSynths_synthsToAdd_96_0[6] = ISynth(new_SynthsKRW_contract); issuer_addSynths_synthsToAdd_96_0[7] = ISynth(new_SynthsBTC_contract); issuer_addSynths_synthsToAdd_96_0[8] = ISynth(new_SynthsETH_contract); issuer_addSynths_synthsToAdd_96_0[9] = ISynth(new_SynthsLINK_contract); issuer_addSynths_synthsToAdd_96_0[10] = ISynth(new_SynthsADA_contract); issuer_addSynths_synthsToAdd_96_0[11] = ISynth(new_SynthsAAVE_contract); issuer_addSynths_synthsToAdd_96_0[12] = ISynth(new_SynthsDOT_contract); issuer_addSynths_synthsToAdd_96_0[13] = ISynth(new_SynthsETHBTC_contract); issuer_addSynths_synthsToAdd_96_0[14] = ISynth(new_SynthsDEFI_contract); issuer_i.addSynths(issuer_addSynths_synthsToAdd_96_0); } function addressresolver_importAddresses_0() external { bytes32[] memory addressresolver_importAddresses_names_0_0 = new bytes32[](28); addressresolver_importAddresses_names_0_0[0] = bytes32("OneNetAggregatorDebtRatio"); addressresolver_importAddresses_names_0_0[1] = bytes32("SystemStatus"); addressresolver_importAddresses_names_0_0[2] = bytes32("ExchangeRates"); addressresolver_importAddresses_names_0_0[3] = bytes32("OneNetAggregatorIssuedSynths"); addressresolver_importAddresses_names_0_0[4] = bytes32("FeePool"); addressresolver_importAddresses_names_0_0[5] = bytes32("Exchanger"); addressresolver_importAddresses_names_0_0[6] = bytes32("ExchangeCircuitBreaker"); addressresolver_importAddresses_names_0_0[7] = bytes32("DebtCache"); addressresolver_importAddresses_names_0_0[8] = bytes32("SynthetixBridgeToOptimism"); addressresolver_importAddresses_names_0_0[9] = bytes32("Issuer"); addressresolver_importAddresses_names_0_0[10] = bytes32("SynthsUSD"); addressresolver_importAddresses_names_0_0[11] = bytes32("SynthsEUR"); addressresolver_importAddresses_names_0_0[12] = bytes32("SynthsJPY"); addressresolver_importAddresses_names_0_0[13] = bytes32("SynthsAUD"); addressresolver_importAddresses_names_0_0[14] = bytes32("SynthsGBP"); addressresolver_importAddresses_names_0_0[15] = bytes32("SynthsCHF"); addressresolver_importAddresses_names_0_0[16] = bytes32("SynthsKRW"); addressresolver_importAddresses_names_0_0[17] = bytes32("SynthsETH"); addressresolver_importAddresses_names_0_0[18] = bytes32("SynthsBTC"); addressresolver_importAddresses_names_0_0[19] = bytes32("SynthsLINK"); addressresolver_importAddresses_names_0_0[20] = bytes32("SynthsADA"); addressresolver_importAddresses_names_0_0[21] = bytes32("SynthsAAVE"); addressresolver_importAddresses_names_0_0[22] = bytes32("SynthsDOT"); addressresolver_importAddresses_names_0_0[23] = bytes32("SynthsETHBTC"); addressresolver_importAddresses_names_0_0[24] = bytes32("SynthsDEFI"); addressresolver_importAddresses_names_0_0[25] = bytes32("FuturesMarketManager"); addressresolver_importAddresses_names_0_0[26] = bytes32("ext:AggregatorIssuedSynths"); addressresolver_importAddresses_names_0_0[27] = bytes32("ext:AggregatorDebtRatio"); address[] memory addressresolver_importAddresses_destinations_0_1 = new address[](28); addressresolver_importAddresses_destinations_0_1[0] = address(new_OneNetAggregatorDebtRatio_contract); addressresolver_importAddresses_destinations_0_1[1] = address(new_SystemStatus_contract); addressresolver_importAddresses_destinations_0_1[2] = address(new_ExchangeRates_contract); addressresolver_importAddresses_destinations_0_1[3] = address(new_OneNetAggregatorIssuedSynths_contract); addressresolver_importAddresses_destinations_0_1[4] = address(new_FeePool_contract); addressresolver_importAddresses_destinations_0_1[5] = address(new_Exchanger_contract); addressresolver_importAddresses_destinations_0_1[6] = address(new_ExchangeCircuitBreaker_contract); addressresolver_importAddresses_destinations_0_1[7] = address(new_DebtCache_contract); addressresolver_importAddresses_destinations_0_1[8] = address(new_SynthetixBridgeToOptimism_contract); addressresolver_importAddresses_destinations_0_1[9] = address(new_Issuer_contract); addressresolver_importAddresses_destinations_0_1[10] = address(new_SynthsUSD_contract); addressresolver_importAddresses_destinations_0_1[11] = address(new_SynthsEUR_contract); addressresolver_importAddresses_destinations_0_1[12] = address(new_SynthsJPY_contract); addressresolver_importAddresses_destinations_0_1[13] = address(new_SynthsAUD_contract); addressresolver_importAddresses_destinations_0_1[14] = address(new_SynthsGBP_contract); addressresolver_importAddresses_destinations_0_1[15] = address(new_SynthsCHF_contract); addressresolver_importAddresses_destinations_0_1[16] = address(new_SynthsKRW_contract); addressresolver_importAddresses_destinations_0_1[17] = address(new_SynthsETH_contract); addressresolver_importAddresses_destinations_0_1[18] = address(new_SynthsBTC_contract); addressresolver_importAddresses_destinations_0_1[19] = address(new_SynthsLINK_contract); addressresolver_importAddresses_destinations_0_1[20] = address(new_SynthsADA_contract); addressresolver_importAddresses_destinations_0_1[21] = address(new_SynthsAAVE_contract); addressresolver_importAddresses_destinations_0_1[22] = address(new_SynthsDOT_contract); addressresolver_importAddresses_destinations_0_1[23] = address(new_SynthsETHBTC_contract); addressresolver_importAddresses_destinations_0_1[24] = address(new_SynthsDEFI_contract); addressresolver_importAddresses_destinations_0_1[25] = address(new_FuturesMarketManager_contract); addressresolver_importAddresses_destinations_0_1[26] = address(new_OneNetAggregatorIssuedSynths_contract); addressresolver_importAddresses_destinations_0_1[27] = address(new_OneNetAggregatorDebtRatio_contract); addressresolver_i.importAddresses( addressresolver_importAddresses_names_0_0, addressresolver_importAddresses_destinations_0_1 ); } function addressresolver_rebuildCaches_1() external { MixinResolver[] memory addressresolver_rebuildCaches_destinations_1_0 = new MixinResolver[](20); addressresolver_rebuildCaches_destinations_1_0[0] = MixinResolver(0xDA4eF8520b1A57D7d63f1E249606D1A459698876); addressresolver_rebuildCaches_destinations_1_0[1] = MixinResolver(0xAD95C918af576c82Df740878C3E983CBD175daB6); addressresolver_rebuildCaches_destinations_1_0[2] = MixinResolver(new_FeePool_contract); addressresolver_rebuildCaches_destinations_1_0[3] = MixinResolver(0xE95A536cF5C7384FF1ef54819Dc54E03d0FF1979); addressresolver_rebuildCaches_destinations_1_0[4] = MixinResolver(new_DebtCache_contract); addressresolver_rebuildCaches_destinations_1_0[5] = MixinResolver(new_Exchanger_contract); addressresolver_rebuildCaches_destinations_1_0[6] = MixinResolver(new_ExchangeCircuitBreaker_contract); addressresolver_rebuildCaches_destinations_1_0[7] = MixinResolver(new_Issuer_contract); addressresolver_rebuildCaches_destinations_1_0[8] = MixinResolver(new_SynthsUSD_contract); addressresolver_rebuildCaches_destinations_1_0[9] = MixinResolver(new_SynthsEUR_contract); addressresolver_rebuildCaches_destinations_1_0[10] = MixinResolver(new_SynthsJPY_contract); addressresolver_rebuildCaches_destinations_1_0[11] = MixinResolver(new_SynthsAUD_contract); addressresolver_rebuildCaches_destinations_1_0[12] = MixinResolver(new_SynthsGBP_contract); addressresolver_rebuildCaches_destinations_1_0[13] = MixinResolver(new_SynthsCHF_contract); addressresolver_rebuildCaches_destinations_1_0[14] = MixinResolver(new_SynthsKRW_contract); addressresolver_rebuildCaches_destinations_1_0[15] = MixinResolver(new_SynthsBTC_contract); addressresolver_rebuildCaches_destinations_1_0[16] = MixinResolver(new_SynthsETH_contract); addressresolver_rebuildCaches_destinations_1_0[17] = MixinResolver(new_SynthsLINK_contract); addressresolver_rebuildCaches_destinations_1_0[18] = MixinResolver(new_SynthsADA_contract); addressresolver_rebuildCaches_destinations_1_0[19] = MixinResolver(new_SynthsAAVE_contract); addressresolver_i.rebuildCaches(addressresolver_rebuildCaches_destinations_1_0); } function addressresolver_rebuildCaches_2() external { MixinResolver[] memory addressresolver_rebuildCaches_destinations_2_0 = new MixinResolver[](16); addressresolver_rebuildCaches_destinations_2_0[0] = MixinResolver(new_SynthsDOT_contract); addressresolver_rebuildCaches_destinations_2_0[1] = MixinResolver(new_SynthsETHBTC_contract); addressresolver_rebuildCaches_destinations_2_0[2] = MixinResolver(new_SynthsDEFI_contract); addressresolver_rebuildCaches_destinations_2_0[3] = MixinResolver(0x5c8344bcdC38F1aB5EB5C1d4a35DdEeA522B5DfA); addressresolver_rebuildCaches_destinations_2_0[4] = MixinResolver(0xaa03aB31b55DceEeF845C8d17890CC61cD98eD04); addressresolver_rebuildCaches_destinations_2_0[5] = MixinResolver(0x1F2c3a1046c32729862fcB038369696e3273a516); addressresolver_rebuildCaches_destinations_2_0[6] = MixinResolver(0x7C22547779c8aa41bAE79E03E8383a0BefBCecf0); addressresolver_rebuildCaches_destinations_2_0[7] = MixinResolver(0xC1AAE9d18bBe386B102435a8632C8063d31e747C); addressresolver_rebuildCaches_destinations_2_0[8] = MixinResolver(0x067e398605E84F2D0aEEC1806e62768C5110DCc6); addressresolver_rebuildCaches_destinations_2_0[9] = MixinResolver(new_ExchangeRates_contract); addressresolver_rebuildCaches_destinations_2_0[10] = MixinResolver(new_SynthetixBridgeToOptimism_contract); addressresolver_rebuildCaches_destinations_2_0[11] = MixinResolver(0x02f9bC46beD33acdB9cb002fe346734CeF8a9480); addressresolver_rebuildCaches_destinations_2_0[12] = MixinResolver(0x62922670313bf6b41C580143d1f6C173C5C20019); addressresolver_rebuildCaches_destinations_2_0[13] = MixinResolver(0x89FCb32F29e509cc42d0C8b6f058C993013A843F); addressresolver_rebuildCaches_destinations_2_0[14] = MixinResolver(0xe533139Af961c9747356D947838c98451015e234); addressresolver_rebuildCaches_destinations_2_0[15] = MixinResolver(0x7A3d898b717e50a96fd8b232E9d15F0A547A7eeb); addressresolver_i.rebuildCaches(addressresolver_rebuildCaches_destinations_2_0); } }
2,494,155
[ 1, 18281, 11317, 17, 8394, 6835, 17, 529, 17, 29021, 3593, 12146, 13849, 19052, 1360, 7068, 1784, 44, 1584, 12507, 8020, 2849, 1268, 55, 12146, 13849, 2333, 30, 546, 414, 4169, 18, 1594, 19, 2867, 19, 20, 92, 28, 4366, 70, 41, 11861, 9897, 42, 10525, 5948, 71, 20, 73, 2947, 3587, 3437, 31779, 42, 25, 37, 69, 15237, 25, 38, 7235, 12124, 10261, 2333, 30, 546, 414, 4169, 18, 1594, 19, 2867, 19, 20, 6114, 6334, 20, 5698, 26, 5608, 73, 2138, 8942, 22087, 7235, 21, 69, 24, 1871, 74, 41, 23, 37, 22, 5895, 38, 20, 37, 9975, 72, 5082, 29, 2333, 30, 546, 414, 4169, 18, 1594, 19, 2867, 19, 20, 14626, 29, 4577, 1403, 25, 29534, 4313, 6260, 8313, 11290, 42, 28, 38, 7235, 5324, 70, 6675, 22, 42, 22, 38, 10321, 5520, 21, 73, 28, 70, 38, 2333, 30, 546, 414, 4169, 18, 1594, 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, 12083, 15309, 5664, 67, 40, 16045, 2414, 288, 203, 203, 565, 5267, 4301, 1071, 5381, 1758, 14122, 67, 77, 273, 5267, 4301, 12, 20, 92, 28, 4366, 70, 41, 11861, 9897, 42, 10525, 5948, 71, 20, 73, 2947, 3587, 3437, 31779, 42, 25, 37, 69, 15237, 25, 38, 7235, 12124, 10261, 1769, 203, 565, 7659, 1071, 5381, 2889, 74, 2661, 1371, 67, 77, 273, 7659, 12, 20, 6114, 6334, 20, 5698, 26, 5608, 73, 2138, 8942, 22087, 7235, 21, 69, 24, 1871, 74, 41, 23, 37, 22, 5895, 38, 20, 37, 9975, 72, 5082, 29, 1769, 203, 565, 30174, 2864, 41, 1174, 3245, 1071, 5381, 1656, 881, 1371, 847, 82, 287, 5697, 67, 77, 273, 203, 3639, 30174, 2864, 41, 1174, 3245, 12, 20, 14626, 29, 4577, 1403, 25, 29534, 4313, 6260, 8313, 11290, 42, 28, 38, 7235, 5324, 70, 6675, 22, 42, 22, 38, 10321, 5520, 21, 73, 28, 70, 38, 1769, 203, 565, 18903, 1119, 1071, 5381, 431, 24083, 395, 340, 67, 77, 273, 18903, 1119, 12, 20, 92, 6564, 6162, 9036, 74, 6030, 29, 3361, 74, 3361, 7142, 26, 71, 27, 42, 9401, 5284, 70, 24, 1871, 22, 3461, 37, 5324, 39, 6260, 1105, 1769, 203, 565, 2332, 1482, 1071, 5381, 2619, 2327, 67, 77, 273, 2332, 1482, 12, 20, 92, 8148, 26, 71, 29, 6260, 42, 28, 42, 28, 71, 713, 26, 71, 37, 8749, 73, 29, 3672, 28, 74, 41, 27, 73, 31262, 29, 3361, 4700, 10689, 42, 1769, 203, 565, 534, 359, 1060, 6412, 492, 1071, 5381, 19890, 2 ]
./partial_match/1/0x7a2f5CAE2D28777dD03270827407112E39749112/sources/BABYX.sol
Trade start check swapTokensForEth(contractTokenBalance);Transfer TokensSet Fee for BuysSet Fee for Sells
function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if (!inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(min(amount,min(contractTokenBalance,_maxTaxSwap))); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); }
9,195,541
[ 1, 22583, 787, 866, 7720, 5157, 1290, 41, 451, 12, 16351, 1345, 13937, 1769, 5912, 13899, 694, 30174, 364, 605, 89, 1900, 694, 30174, 364, 348, 1165, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 3238, 288, 203, 3639, 2583, 12, 2080, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 8949, 405, 374, 16, 315, 5912, 3844, 1297, 506, 6802, 2353, 3634, 8863, 203, 203, 3639, 309, 261, 2080, 480, 3410, 1435, 597, 358, 480, 3410, 10756, 288, 203, 203, 5411, 309, 16051, 313, 14968, 3678, 13, 288, 203, 7734, 2583, 12, 2080, 422, 3410, 9334, 315, 8412, 30, 1220, 2236, 2780, 1366, 2430, 3180, 1284, 7459, 353, 3696, 8863, 203, 5411, 289, 203, 203, 5411, 2583, 12, 8949, 1648, 389, 1896, 4188, 6275, 16, 315, 8412, 30, 4238, 5947, 7214, 8863, 203, 5411, 2583, 12, 5, 4819, 87, 63, 2080, 65, 597, 401, 4819, 87, 63, 869, 6487, 315, 8412, 30, 20471, 2236, 353, 25350, 4442, 1769, 203, 203, 5411, 309, 12, 869, 480, 640, 291, 91, 438, 58, 22, 4154, 13, 288, 203, 7734, 2583, 12, 12296, 951, 12, 869, 13, 397, 3844, 411, 389, 1896, 16936, 1225, 16, 315, 8412, 30, 30918, 14399, 9230, 963, 4442, 1769, 203, 5411, 289, 203, 203, 5411, 2254, 5034, 6835, 1345, 13937, 273, 11013, 951, 12, 2867, 12, 2211, 10019, 203, 5411, 1426, 848, 12521, 273, 6835, 1345, 13937, 1545, 389, 22270, 5157, 861, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract LizardLab is ERC721, Ownable { using Address for address; //some call it 'provenance' string public PROOF_OF_ANCESTRY; //where the wild things are (or will be) string public baseURI; //fives are good numbers... lets go with 5s uint256 public constant MAX_LIZARDS = 5000; uint256 public constant PRICE = 0.05 ether; uint256 public constant FOR_THE_WARCHEST = 100; uint256 public totalSupply; //do not get any ideas too soon bool public presaleActive = false; uint256 public presaleWave; bool public saleActive = false; //has [REDACTED] populated the war chest? bool public redactedClaimed = false; //who gets what address redLizard = 0xfb55e7ECbBA9715A9A9DD31DB3c777D8B98cB4Dc; address blueLizard = 0x87E9Ab2D6f4f744f36aad379f0157da30d3E2670; address greenLizard = 0x86bE508e686AB58ab9442c6A9800B1a941a6D60D; address warChest = 0x30471c24BDb0b9dDb75d9cA5D4E13049fc69FEfD; //some lizard keepers are...more privileged than others mapping (address => bool) public claimWhitelist; mapping (address => uint256) public presaleWhitelist; //there is a lot to unpack here constructor() ERC721("The Lizard Lab", "LIZRD") { } //don't let them all escape!! [REDACTED] needs them function recapture() public onlyOwner { require(bytes(PROOF_OF_ANCESTRY).length > 0, "No distributing Lizards until provenance is established."); require(!redactedClaimed, "Only once, even for you [REDACTED]"); require(totalSupply + FOR_THE_WARCHEST <= MAX_LIZARDS, "You have missed your chance, [REDACTED]."); for (uint256 i = 0; i < FOR_THE_WARCHEST; i++) { _safeMint(warChest, totalSupply + i); } totalSupply += FOR_THE_WARCHEST; redactedClaimed = true; } //a freebie for you, thank you for your support function claim() public { require(presaleActive || saleActive, "A sale period must be active to claim"); require(claimWhitelist[msg.sender], "No claim available for this address"); require(totalSupply + 1 <= MAX_LIZARDS, "Claim would exceed max supply of tokens"); _safeMint( msg.sender, totalSupply); totalSupply += 1; claimWhitelist[msg.sender] = false; } //thanks for hanging out.. function mintPresale(uint256 numberOfMints) public payable { uint256 reserved = presaleWhitelist[msg.sender]; require(presaleActive, "Presale must be active to mint"); require(reserved > 0, "No tokens reserved for this address"); require(numberOfMints <= reserved, "Can't mint more than reserved"); require(totalSupply + numberOfMints <= MAX_LIZARDS, "Purchase would exceed max supply of tokens"); require(PRICE * numberOfMints == msg.value, "Ether value sent is not correct"); presaleWhitelist[msg.sender] = reserved - numberOfMints; for(uint256 i; i < numberOfMints; i++){ _safeMint( msg.sender, totalSupply + i ); } totalSupply += numberOfMints; } //..and now for the rest of you function mint(uint256 numberOfMints) public payable { require(saleActive, "Sale must be active to mint"); require(numberOfMints > 0 && numberOfMints < 6, "Invalid purchase amount"); require(totalSupply + numberOfMints <= MAX_LIZARDS, "Purchase would exceed max supply of tokens"); require(PRICE * numberOfMints == msg.value, "Ether value sent is not correct"); for(uint256 i; i < numberOfMints; i++) { _safeMint(msg.sender, totalSupply + i); } totalSupply += numberOfMints; } //these lizards are free function editClaimList(address[] calldata claimAddresses) public onlyOwner { for(uint256 i; i < claimAddresses.length; i++){ claimWhitelist[claimAddresses[i]] = true; } } //somebody has to keep track of all of this function editPresaleList(address[] calldata presaleAddresses, uint256[] calldata amount) public onlyOwner { for(uint256 i; i < presaleAddresses.length; i++){ presaleWhitelist[presaleAddresses[i]] = amount[i]; } presaleWave = presaleWave + 1; } //[REDACTED] made me put this here..as to not..tinker with anything function setAncestry(string memory provenance) public onlyOwner { require(bytes(PROOF_OF_ANCESTRY).length == 0, "Now now, [REDACTED], do not go and try to play god...twice."); PROOF_OF_ANCESTRY = provenance; } //and a flip of the (small) switch function togglePresale() public onlyOwner { require(bytes(PROOF_OF_ANCESTRY).length > 0, "No distributing Lizards until provenance is established."); presaleActive = !presaleActive; } //the flip of a slightly larger switch function toggleSale() public onlyOwner { require(bytes(PROOF_OF_ANCESTRY).length > 0, "No distributing Lizards until provenance is established."); presaleActive = false; saleActive = !saleActive; } //for the grand reveal and where things are now.. where things will forever be.. lizards willing function setBaseURI(string memory uri) public onlyOwner { baseURI = uri; } //come have a looksy function _baseURI() internal view override returns (string memory) { return baseURI; } //coins for the lizards function withdraw() public { uint256 balance = address(this).balance; payable(redLizard).transfer((balance * 400) / 1000); payable(greenLizard).transfer((balance * 400) / 1000); payable(blueLizard).transfer((balance * 200) / 1000); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/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; /** * @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 Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
[REDACTED] made me put this here..as to not..tinker with anything
function setAncestry(string memory provenance) public onlyOwner { require(bytes(PROOF_OF_ANCESTRY).length == 0, "Now now, [REDACTED], do not go and try to play god...twice."); PROOF_OF_ANCESTRY = provenance; }
13,731,543
[ 1, 63, 5879, 6526, 2056, 65, 7165, 1791, 1378, 333, 2674, 838, 345, 358, 486, 838, 88, 754, 264, 598, 6967, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 979, 27626, 12, 1080, 3778, 24185, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 3890, 12, 3373, 3932, 67, 3932, 67, 4722, 3902, 61, 2934, 2469, 422, 374, 16, 315, 8674, 2037, 16, 306, 5879, 6526, 2056, 6487, 741, 486, 1960, 471, 775, 358, 6599, 314, 369, 2777, 11246, 1812, 1199, 1769, 203, 203, 3639, 4629, 3932, 67, 3932, 67, 4722, 3902, 61, 273, 24185, 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 ]
/* __ __ __ | \ | \ | \ | $$\ | $$ __ __ ______ ____ | $$____ ______ | $$$\| $$| \ | \| \ \ | $$ \ | \ | $$$$\ $$| $$ | $$| $$$$$$\$$$$\| $$$$$$$\ \$$$$$$\ | $$\$$ $$| $$ | $$| $$ | $$ | $$| $$ | $$ / $$ | $$ \$$$$| $$__/ $$| $$ | $$ | $$| $$__/ $$| $$$$$$$ | $$ \$$$ \$$ $$| $$ | $$ | $$| $$ $$ \$$ $$ \$$ \$$ \$$$$$$ \$$ \$$ \$$ \$$$$$$$ \$$$$$$$ go up! https://twitter.com/NumbaNFT http://discord.gg/2hmT32ZHrT https://numbagoup.xyz h/t to Ohm, Looks, Dydx, Luna, Sushi, Reflect, Shib, Safemoon, CRV, ESD, BASED, Effirium, and of course, Bitcoin for the inspiration. s/o to Zeppelin, Larva Labs, Loot, and KaijuKingz (minor) for some aspects of the smart contract. Don't take this too seriously... or who knows, maybe do, as long as you have fun ;) This project is dedicated to all the liquidated boys out there. */ pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; contract Numba is ERC721, ERC721Enumerable, ERC721Burnable, Ownable, ReentrancyGuard { uint256 public constant GENESIS_AMOUNT = 1000; uint256 public numbaMinted = 0; uint256 public price = 0.033 ether; uint256 public priceIncrement = 0.001 ether; uint256 public devFee = 0.011 ether; uint256 public devWithdrawn = 0; mapping(uint256 => uint256) public nextUsable; uint256 internal nonce = 0; uint256[GENESIS_AMOUNT] internal indices; constructor() ERC721("Numba", "#") {} function randomIndex() internal returns (uint256) { uint256 totalSize = GENESIS_AMOUNT - numbaMinted; uint256 index = uint256( keccak256( abi.encodePacked( nonce, msg.sender, block.difficulty, block.timestamp ) ) ) % totalSize; uint256 value = 0; if (indices[index] != 0) { value = indices[index]; } else { value = index; } // Move last value to selected position if (indices[totalSize - 1] == 0) { // Array position not initialized, so use position indices[index] = totalSize - 1; } else { // Array position holds a value so use that indices[index] = indices[totalSize - 1]; } nonce++; // Don't allow a zero index, start counting at 1 return value + 1; } function mintGenesis(uint256 numberOfMints) public payable nonReentrant { require( totalSupply() + numberOfMints <= GENESIS_AMOUNT, "Can't mint that much." ); require( numberOfMints > 0 && numberOfMints < 11, "Too much or too lil." ); require(price * numberOfMints == msg.value, "Hmmm."); for (uint256 i; i < numberOfMints; i++) { _safeMint(msg.sender, randomIndex()); numbaMinted++; } } function mint() public payable nonReentrant { require(numbaMinted > GENESIS_AMOUNT - 1, "Genesis mint is not over."); require(msg.value >= price * 3, "Insufficient funds to purchase."); if (msg.value > price * 3) { // payable(msg.sender).transfer(msg.value - price * 3); (bool success, ) = payable(msg.sender).call{ value: msg.value - price * 3 }(""); require(success, "Transfer failed."); } _safeMint(msg.sender, numbaMinted + 1); numbaMinted++; price += priceIncrement; } function mintByAddition( uint256 x, uint256 y, uint256 z ) public payable nonReentrant { require(numbaMinted > GENESIS_AMOUNT - 1, "Genesis mint is not over."); require(x + y + z == numbaMinted + 1, "Wrong ingredients."); require( ownerOf(x) == msg.sender && ownerOf(y) == msg.sender && ownerOf(z) == msg.sender, "You don't own these." ); require(x != y && y != z && z != x, "Can't be using dupes here."); require( nextUsable[x] < numbaMinted && nextUsable[y] < numbaMinted && nextUsable[z] < numbaMinted, "Cooldown." ); require(price == msg.value, "Hmmmm."); _safeMint(msg.sender, numbaMinted + 1); numbaMinted++; price += priceIncrement; nextUsable[x] = numbaMinted + 20; nextUsable[y] = numbaMinted + 20; nextUsable[z] = numbaMinted + 20; } function mintByMultiplication(uint256 x, uint256 y) public payable nonReentrant { require(numbaMinted > GENESIS_AMOUNT - 1, "Genesis mint is not over."); require(x * y == numbaMinted + 1, "Wrong ingredients."); require( ownerOf(x) == msg.sender && ownerOf(y) == msg.sender, "You don't own these." ); require(price == msg.value, "Hmmmm."); _safeMint(msg.sender, numbaMinted + 1); numbaMinted++; price += priceIncrement; } function mintByExponential(uint256 tokenId, uint256 power) public payable nonReentrant { require(numbaMinted > GENESIS_AMOUNT - 1, "Genesis mint is not over."); require(tokenId**power == numbaMinted + 1, "Wrong ingredients."); require(ownerOf(tokenId) == msg.sender, "You don't own this, fool."); require(price == msg.value, "Hmmmm."); _safeMint(msg.sender, numbaMinted + 1); numbaMinted++; price += priceIncrement; } function claimAndBurn(uint256 tokenId) public nonReentrant { uint256 backing = backingPerToken(); burn(tokenId); (bool success, ) = payable(msg.sender).call{value: backing}(""); require(success, "Transfer failed."); if (price - priceIncrement > 0.033 ether) { price -= priceIncrement; } } function devWithdraw() public onlyOwner nonReentrant { uint256 amount = devWithdrawable(); devWithdrawn += amount; (bool success, ) = payable(msg.sender).call{value: amount}(""); require(success, "Transfer failed."); } function backingPerToken() public view returns (uint256) { uint256 totalWithdrawable = address(this).balance - devWithdrawable(); return totalWithdrawable / totalSupply(); } function reserve() public view returns (uint256) { return address(this).balance - devWithdrawable(); } function holderClaimable(address holder) public view returns (uint256) { return (reserve() * balanceOf(holder)) / totalSupply(); } function numbaBurnt() public view returns (uint256) { return numbaMinted - totalSupply(); } function devWithdrawable() public view returns (uint256) { uint256 totalEarned = devFee * numbaMinted; return totalEarned - devWithdrawn; } function nextNumba() public view returns (uint256) { if (numbaMinted < GENESIS_AMOUNT) { return 0; } return numbaMinted + 1; } function etherBalance() public view returns (uint256) { return address(this).balance; } function message() public view returns (string memory) { return "Numba go up!"; } function tokenURI(uint256 tokenId) public view override returns (string memory) { string[3] memory parts; parts[ 0 ] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: black; font-family: sans-serif; font-size: 33px; }</style><rect width="100%" height="100%" fill="white" /><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" class="base">'; parts[1] = toString(tokenId); parts[2] = "</text></svg>"; string memory output = string( abi.encodePacked(parts[0], parts[1], parts[2]) ); string memory json = Base64.encode( bytes( string( abi.encodePacked( '{"name": "Numba ', toString(tokenId), '", "description": "Numba go up!", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}' ) ) ) ); output = string( abi.encodePacked("data:application/json;base64,", json) ); return output; } function ownedTokenIds(address holder) public view returns (uint256[] memory) { uint256 length = balanceOf(holder); uint256[] memory owned = new uint256[](length); for (uint256 i = 0; i < length; i++) { owned[i] = tokenOfOwnerByIndex(holder, i); } return owned; } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // 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); } // The following functions are overrides required by Solidity. function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } event Received(address, uint256); receive() external payable { emit Received(msg.sender, msg.value); } } library Base64 { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// @notice Encodes some bytes to the base64 representation function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF) ) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF) ) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF) ) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Burnable.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; import "../../../utils/Context.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); }
payable(msg.sender).transfer(msg.value - price * 3);
function mint() public payable nonReentrant { require(numbaMinted > GENESIS_AMOUNT - 1, "Genesis mint is not over."); require(msg.value >= price * 3, "Insufficient funds to purchase."); if (msg.value > price * 3) { (bool success, ) = payable(msg.sender).call{ value: msg.value - price * 3 }(""); require(success, "Transfer failed."); } _safeMint(msg.sender, numbaMinted + 1); numbaMinted++; price += priceIncrement; }
6,029,484
[ 1, 10239, 429, 12, 3576, 18, 15330, 2934, 13866, 12, 3576, 18, 1132, 300, 6205, 225, 890, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 1435, 1071, 8843, 429, 1661, 426, 8230, 970, 288, 203, 3639, 2583, 12, 2107, 12124, 49, 474, 329, 405, 611, 1157, 41, 15664, 67, 2192, 51, 5321, 300, 404, 16, 315, 7642, 16786, 312, 474, 353, 486, 1879, 1199, 1769, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 6205, 380, 890, 16, 315, 5048, 11339, 284, 19156, 358, 23701, 1199, 1769, 203, 3639, 309, 261, 3576, 18, 1132, 405, 6205, 380, 890, 13, 288, 203, 5411, 261, 6430, 2216, 16, 262, 273, 8843, 429, 12, 3576, 18, 15330, 2934, 1991, 95, 203, 7734, 460, 30, 1234, 18, 1132, 300, 6205, 380, 890, 203, 5411, 289, 2932, 8863, 203, 5411, 2583, 12, 4768, 16, 315, 5912, 2535, 1199, 1769, 203, 3639, 289, 203, 203, 3639, 389, 4626, 49, 474, 12, 3576, 18, 15330, 16, 818, 12124, 49, 474, 329, 397, 404, 1769, 203, 3639, 818, 12124, 49, 474, 329, 9904, 31, 203, 3639, 6205, 1011, 6205, 10798, 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 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.4; contract Launcher { enum ContractState { TimeNotExpired, Funded, NotFunded } struct Launch { ContractState contractState; uint launchTime; uint launchGoalInWei; uint totalCommittedWei; address beneficiary; mapping (address => uint) pledges; } mapping(uint => Launch) public launches; // Using a counter is a bad idea in general because it's not a globally guaranteed unique ID // and due to chain issues a counter you think belongs to campaign X could end up belonging // to campaign Y. So one has to always remember to confirm both the counter and the beneficiary. // Ideally we would use the beneficiary as the index but that made testing painful and since // this is really just code to explain solidity I went with something that was easy to test. uint public launchCounter; /// The submitted launch address doesn't match a launch campaign error BadLaunchAddress(); modifier checkLaunchAddress(uint launchID) { if (launches[launchID].launchGoalInWei == 0) revert BadLaunchAddress(); _; } function updateStateIfNeeded(uint launchID) internal checkLaunchAddress(launchID) { Launch storage launch = launches[launchID]; if (launch.contractState != ContractState.TimeNotExpired || block.timestamp < launch.launchTime) { return; } launch.contractState = (launch.totalCommittedWei >= launch.launchGoalInWei) ? ContractState.Funded : ContractState.NotFunded; } /// The state of the contract did not match the state required for this /// function call. error WrongState(ContractState contractState, ContractState expectedState); modifier checkState(uint launchID, ContractState expectedState) { updateStateIfNeeded(launchID); Launch storage launch = launches[launchID]; if (expectedState != launch.contractState) revert WrongState(launch.contractState, expectedState); _; } /// Sender did not pledge money or has already had their pledge refunded error NoPledgeRefundDue(); /// We use this value to detect references to contracts that don't exist and /// besides it's silly to have a launch for 0 Wei error LaunchGoalMustBeGreaterThan0(); /// We really don't need an event but I just wanted to show it's done event LaunchCreated( address beneficiary, uint launchTime, uint launchGoalInWei, uint launchID ); function createLaunch( // This can be 0, in that case the fund raising is quite short :) uint _secondsToLaunchTime, // Any value is accepted since it's met or it isn't, this includes 0 uint _launchGoalInWei) public { if (_launchGoalInWei == 0) revert LaunchGoalMustBeGreaterThan0(); uint launchID = launchCounter++; Launch storage launch = launches[launchID]; launch.contractState = ContractState.TimeNotExpired; launch.launchGoalInWei = _launchGoalInWei; launch.launchTime = block.timestamp + _secondsToLaunchTime; launch.beneficiary = msg.sender; emit LaunchCreated(launch.beneficiary, launch.launchTime, launch.launchGoalInWei, launchID); } function pledge(uint launchID) public payable checkState(launchID, ContractState.TimeNotExpired) { Launch storage launch = launches[launchID]; // Maps treat all unintialized values as starting at 0 so we don't have to check // if the pledge has been set before. launch.pledges[msg.sender] += msg.value; launch.totalCommittedWei += msg.value; } // Strictly speaking the refundPledge and claimPledges functions could // be combined into a single "resolve" function but I like to have small // functions with very limited functionality and lots of testing so I put // the work of combining them together on the client side. // If the project failed to launch, get back pledge function refundPledge(uint launchID) public payable checkState(launchID, ContractState.NotFunded) { Launch storage launch = launches[launchID]; uint refund = launch.pledges[msg.sender]; launch.pledges[msg.sender] = 0; launch.totalCommittedWei -= refund; if (refund == 0) revert NoPledgeRefundDue(); if (!payable(msg.sender).send(refund)) { launch.pledges[msg.sender] = refund; launch.totalCommittedWei += refund; } } function claimPledges(uint launchID) public payable checkState(launchID, ContractState.Funded) { Launch storage launch = launches[launchID]; require(msg.sender == launch.beneficiary, "Only the beneficiary can claim the pledges"); uint totalFunding = launch.totalCommittedWei; launch.totalCommittedWei = 0; if (!payable(launch.beneficiary).send(totalFunding)) { launch.totalCommittedWei = totalFunding; } } function getPledge(uint launchID) public view checkLaunchAddress(launchID) returns(uint) { return launches[launchID].pledges[msg.sender]; } }
This can be 0, in that case the fund raising is quite short :) Any value is accepted since it's met or it isn't, this includes 0
function createLaunch( uint _secondsToLaunchTime, uint _launchGoalInWei) public { if (_launchGoalInWei == 0) revert LaunchGoalMustBeGreaterThan0(); uint launchID = launchCounter++; Launch storage launch = launches[launchID]; launch.contractState = ContractState.TimeNotExpired; launch.launchGoalInWei = _launchGoalInWei; launch.launchTime = block.timestamp + _secondsToLaunchTime; launch.beneficiary = msg.sender; emit LaunchCreated(launch.beneficiary, launch.launchTime, launch.launchGoalInWei, launchID); }
12,552,779
[ 1, 2503, 848, 506, 374, 16, 316, 716, 648, 326, 284, 1074, 28014, 353, 25102, 3025, 294, 13, 5502, 460, 353, 8494, 3241, 518, 1807, 5100, 578, 518, 5177, 1404, 16, 333, 6104, 374, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 752, 9569, 12, 203, 5411, 2254, 389, 7572, 774, 9569, 950, 16, 203, 5411, 2254, 389, 20738, 27716, 382, 3218, 77, 13, 7010, 3639, 1071, 288, 203, 5411, 309, 261, 67, 20738, 27716, 382, 3218, 77, 422, 374, 13, 15226, 14643, 27716, 10136, 1919, 28130, 20, 5621, 203, 5411, 2254, 8037, 734, 273, 8037, 4789, 9904, 31, 203, 5411, 14643, 2502, 8037, 273, 8037, 281, 63, 20738, 734, 15533, 203, 5411, 8037, 18, 16351, 1119, 273, 13456, 1119, 18, 950, 1248, 10556, 31, 203, 5411, 8037, 18, 20738, 27716, 382, 3218, 77, 273, 389, 20738, 27716, 382, 3218, 77, 31, 203, 5411, 8037, 18, 20738, 950, 273, 1203, 18, 5508, 397, 389, 7572, 774, 9569, 950, 31, 203, 5411, 8037, 18, 70, 4009, 74, 14463, 814, 273, 1234, 18, 15330, 31, 203, 5411, 3626, 14643, 6119, 12, 20738, 18, 70, 4009, 74, 14463, 814, 16, 8037, 18, 20738, 950, 16, 8037, 18, 20738, 27716, 382, 3218, 77, 16, 8037, 734, 1769, 203, 3639, 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 ]
// File: @openzeppelin/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `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); /** * @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/IERC20Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) 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/utils/math/Math.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // File: @openzeppelin/contracts/utils/structs/EnumerableSet.sol // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: ERC20I.sol pragma solidity ^0.8.0; /* ERC20I (ERC20 0xInuarashi Edition) Minified and Gas Optimized Contributors: 0xInuarashi (Message to Martians, Anonymice), 0xBasset (Ether Orcs) */ contract ERC20I { // Token Params string public name; string public symbol; constructor(string memory name_, string memory symbol_) { name = name_; symbol = symbol_; } // Decimals uint8 public constant decimals = 18; // Supply uint256 public totalSupply; // Mappings of Balances mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; // Events event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); // Internal Functions function _mint(address to_, uint256 amount_) internal virtual { totalSupply += amount_; balanceOf[to_] += amount_; emit Transfer(address(0x0), to_, amount_); } function _burn(address from_, uint256 amount_) internal virtual { balanceOf[from_] -= amount_; totalSupply -= amount_; emit Transfer(from_, address(0x0), amount_); } function _approve(address owner_, address spender_, uint256 amount_) internal virtual { allowance[owner_][spender_] = amount_; emit Approval(owner_, spender_, amount_); } // Public Functions function approve(address spender_, uint256 amount_) public virtual returns (bool) { _approve(msg.sender, spender_, amount_); return true; } function transfer(address to_, uint256 amount_) public virtual returns (bool) { balanceOf[msg.sender] -= amount_; balanceOf[to_] += amount_; emit Transfer(msg.sender, to_, amount_); return true; } function transferFrom(address from_, address to_, uint256 amount_) public virtual returns (bool) { if (allowance[from_][msg.sender] != type(uint256).max) { allowance[from_][msg.sender] -= amount_; } balanceOf[from_] -= amount_; balanceOf[to_] += amount_; emit Transfer(from_, to_, amount_); return true; } // 0xInuarashi Custom Functions function multiTransfer(address[] memory to_, uint256[] memory amounts_) public virtual { require(to_.length == amounts_.length, "ERC20I: To and Amounts length Mismatch!"); for (uint256 i = 0; i < to_.length; i++) { transfer(to_[i], amounts_[i]); } } function multiTransferFrom(address[] memory from_, address[] memory to_, uint256[] memory amounts_) public virtual { require(from_.length == to_.length && from_.length == amounts_.length, "ERC20I: From, To, and Amounts length Mismatch!"); for (uint256 i = 0; i < from_.length; i++) { transferFrom(from_[i], to_[i], amounts_[i]); } } function burn(uint256 amount_) external virtual { _burn(msg.sender, amount_); } function burnFrom(address from_, uint256 amount_) public virtual { uint256 _currentAllowance = allowance[from_][msg.sender]; require(_currentAllowance >= amount_, "ERC20IBurnable: Burn amount requested exceeds allowance!"); if (allowance[from_][msg.sender] != type(uint256).max) { allowance[from_][msg.sender] -= amount_; } _burn(from_, amount_); } } // File: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, 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}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, 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}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, 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) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][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) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, 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: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, 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 Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - 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: cosmicToken.sol pragma solidity 0.8.7; interface IDuck { function balanceOG(address _user) external view returns(uint256); } contract CosmicToken is ERC20("CosmicUtilityToken", "CUT") { using SafeMath for uint256; uint256 public totalTokensBurned = 0; address[] internal stakeholders; address payable private owner; //token Genesis per day uint256 constant public GENESIS_RATE = 20 ether; //token duck per day uint256 constant public DUCK_RATE = 5 ether; //token for genesis minting uint256 constant public GENESIS_ISSUANCE = 280 ether; //token for duck minting uint256 constant public DUCK_ISSUANCE = 70 ether; // Tue Mar 18 2031 17:46:47 GMT+0000 uint256 constant public END = 1931622407; mapping(address => uint256) public rewards; mapping(address => uint256) public lastUpdate; IDuck public ducksContract; constructor(address initDuckContract) { owner = payable(msg.sender); ducksContract = IDuck(initDuckContract); } function WhoOwns() public view returns (address) { return owner; } modifier Owned { require(msg.sender == owner); _; } function getContractAddress() public view returns (address) { return address(this); } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } modifier contractAddressOnly { require(msg.sender == address(ducksContract)); _; } // called when minting many NFTs function updateRewardOnMint(address _user, uint256 _tokenId) external contractAddressOnly { if(_tokenId <= 1000) { _mint(_user,GENESIS_ISSUANCE); } else if(_tokenId >= 1001) { _mint(_user,DUCK_ISSUANCE); } } function getReward(address _to, uint256 totalPayout) external contractAddressOnly { _mint(_to, (totalPayout * 10 ** 18)); } function burn(address _from, uint256 _amount) external { require(msg.sender == _from, "You do not own these tokens"); _burn(_from, _amount); totalTokensBurned += _amount; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: ERC721A.sol // Creators: locationtba.eth, 2pmflow.eth pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_ ) { require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _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 { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal virtual { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > currentIndex - 1) { endIndex = currentIndex - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: cosmicLabs.sol pragma solidity 0.8.7; contract CosmicLabs is ERC721Enumerable, IERC721Receiver, Ownable { using Strings for uint256; using EnumerableSet for EnumerableSet.UintSet; CosmicToken public cosmictoken; using Counters for Counters.Counter; Counters.Counter private _tokenIdTracker; string public baseURI; string public baseExtension = ".json"; uint public maxGenesisTx = 4; uint public maxDuckTx = 20; uint public maxSupply = 9000; uint public genesisSupply = 1000; uint256 public price = 0.05 ether; bool public GensisSaleOpen = true; bool public GenesisFreeMintOpen = false; bool public DuckMintOpen = false; modifier isSaleOpen { require(GensisSaleOpen == true); _; } modifier isFreeMintOpen { require(GenesisFreeMintOpen == true); _; } modifier isDuckMintOpen { require(DuckMintOpen == true); _; } function switchFromFreeToDuckMint() public onlyOwner { GenesisFreeMintOpen = false; DuckMintOpen = true; } event mint(address to, uint total); event withdraw(uint total); event giveawayNft(address to, uint tokenID); mapping(address => uint256) public balanceOG; mapping(address => uint256) public maxWalletGenesisTX; mapping(address => uint256) public maxWalletDuckTX; mapping(address => EnumerableSet.UintSet) private _deposits; mapping(uint256 => uint256) public _deposit_blocks; mapping(address => bool) public addressStaked; //ID - Days staked; mapping(uint256 => uint256) public IDvsDaysStaked; mapping (address => uint256) public whitelistMintAmount; address internal communityWallet = 0xea25545d846ecF4999C2875bC77dE5B5151Fa633; constructor(string memory _initBaseURI) ERC721("Cosmic Labs", "CLABS") { setBaseURI(_initBaseURI); } function setPrice(uint256 newPrice) external onlyOwner { price = newPrice; } function setYieldToken(address _yield) external onlyOwner { cosmictoken = CosmicToken(_yield); } function totalToken() public view returns (uint256) { return _tokenIdTracker.current(); } modifier communityWalletOnly { require(msg.sender == communityWallet); _; } function communityDuckMint(uint256 amountForAirdrops) public onlyOwner { for(uint256 i; i<amountForAirdrops; i++) { _tokenIdTracker.increment(); _safeMint(communityWallet, totalToken()); } } function GenesisSale(uint8 mintTotal) public payable isSaleOpen { uint256 totalMinted = maxWalletGenesisTX[msg.sender]; totalMinted = totalMinted + mintTotal; require(mintTotal >= 1 && mintTotal <= maxGenesisTx, "Mint Amount Incorrect"); require(totalToken() < genesisSupply, "SOLD OUT!"); require(maxWalletGenesisTX[msg.sender] <= maxGenesisTx, "You've maxed your limit!"); require(msg.value >= price * mintTotal, "Minting a Genesis Costs 0.05 Ether Each!"); require(totalMinted <= maxGenesisTx, "You'll surpass your limit!"); for(uint8 i=0;i<mintTotal;i++) { whitelistMintAmount[msg.sender] += 1; maxWalletGenesisTX[msg.sender] += 1; _tokenIdTracker.increment(); _safeMint(msg.sender, totalToken()); cosmictoken.updateRewardOnMint(msg.sender, totalToken()); emit mint(msg.sender, totalToken()); } if(totalToken() == genesisSupply) { GensisSaleOpen = false; GenesisFreeMintOpen = true; } } function GenesisFreeMint(uint8 mintTotal)public payable isFreeMintOpen { require(whitelistMintAmount[msg.sender] > 0, "You don't have any free mints!"); require(totalToken() < maxSupply, "SOLD OUT!"); require(mintTotal <= whitelistMintAmount[msg.sender], "You are passing your limit!"); for(uint8 i=0;i<mintTotal;i++) { whitelistMintAmount[msg.sender] -= 1; _tokenIdTracker.increment(); _safeMint(msg.sender, totalToken()); cosmictoken.updateRewardOnMint(msg.sender, totalToken()); emit mint(msg.sender, totalToken()); } } function DuckSale(uint8 mintTotal)public payable isDuckMintOpen { uint256 totalMinted = maxWalletDuckTX[msg.sender]; totalMinted = totalMinted + mintTotal; require(mintTotal >= 1 && mintTotal <= maxDuckTx, "Mint Amount Incorrect"); require(msg.value >= price * mintTotal, "Minting a Duck Costs 0.05 Ether Each!"); require(totalToken() < maxSupply, "SOLD OUT!"); require(maxWalletDuckTX[msg.sender] <= maxDuckTx, "You've maxed your limit!"); require(totalMinted <= maxDuckTx, "You'll surpass your limit!"); for(uint8 i=0;i<mintTotal;i++) { maxWalletDuckTX[msg.sender] += 1; _tokenIdTracker.increment(); _safeMint(msg.sender, totalToken()); cosmictoken.updateRewardOnMint(msg.sender, totalToken()); emit mint(msg.sender, totalToken()); } if(totalToken() == maxSupply) { DuckMintOpen = false; } } function airdropNft(address airdropPatricipent, uint16 tokenID) public payable communityWalletOnly { _transfer(msg.sender, airdropPatricipent, tokenID); emit giveawayNft(airdropPatricipent, tokenID); } function airdropMany(address[] memory airdropPatricipents) public payable communityWalletOnly { uint256[] memory tempWalletOfUser = this.walletOfOwner(msg.sender); require(tempWalletOfUser.length >= airdropPatricipents.length, "You dont have enough tokens to airdrop all!"); for(uint256 i=0; i<airdropPatricipents.length; i++) { _transfer(msg.sender, airdropPatricipents[i], tempWalletOfUser[i]); emit giveawayNft(airdropPatricipents[i], tempWalletOfUser[i]); } } function withdrawContractEther(address payable recipient) external onlyOwner { emit withdraw(getBalance()); recipient.transfer(getBalance()); } function getBalance() public view returns(uint) { return address(this).balance; } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } function getReward(uint256 CalculatedPayout) internal { cosmictoken.getReward(msg.sender, CalculatedPayout); } //Staking Functions function depositStake(uint256[] calldata tokenIds) external { require(isApprovedForAll(msg.sender, address(this)), "You are not Approved!"); for (uint256 i; i < tokenIds.length; i++) { safeTransferFrom( msg.sender, address(this), tokenIds[i], '' ); _deposits[msg.sender].add(tokenIds[i]); addressStaked[msg.sender] = true; _deposit_blocks[tokenIds[i]] = block.timestamp; IDvsDaysStaked[tokenIds[i]] = block.timestamp; } } function withdrawStake(uint256[] calldata tokenIds) external { require(isApprovedForAll(msg.sender, address(this)), "You are not Approved!"); for (uint256 i; i < tokenIds.length; i++) { require( _deposits[msg.sender].contains(tokenIds[i]), 'Token not deposited' ); cosmictoken.getReward(msg.sender,totalRewardsToPay(tokenIds[i])); _deposits[msg.sender].remove(tokenIds[i]); _deposit_blocks[tokenIds[i]] = 0; addressStaked[msg.sender] = false; IDvsDaysStaked[tokenIds[i]] = block.timestamp; this.safeTransferFrom( address(this), msg.sender, tokenIds[i], '' ); } } function viewRewards() external view returns (uint256) { uint256 payout = 0; for(uint256 i = 0; i < _deposits[msg.sender].length(); i++) { payout = payout + totalRewardsToPay(_deposits[msg.sender].at(i)); } return payout; } function claimRewards() external { for(uint256 i = 0; i < _deposits[msg.sender].length(); i++) { cosmictoken.getReward(msg.sender, totalRewardsToPay(_deposits[msg.sender].at(i))); IDvsDaysStaked[_deposits[msg.sender].at(i)] = block.timestamp; } } function totalRewardsToPay(uint256 tokenId) internal view returns(uint256) { uint256 payout = 0; if(tokenId > 0 && tokenId <= genesisSupply) { payout = howManyDaysStaked(tokenId) * 20; } else if (tokenId > genesisSupply && tokenId <= maxSupply) { payout = howManyDaysStaked(tokenId) * 5; } return payout; } function howManyDaysStaked(uint256 tokenId) public view returns(uint256) { require( _deposits[msg.sender].contains(tokenId), 'Token not deposited' ); uint256 returndays; uint256 timeCalc = block.timestamp - IDvsDaysStaked[tokenId]; returndays = timeCalc / 86400; return returndays; } function walletOfOwner(address _owner) external view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i = 0; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } function returnStakedTokens() public view returns (uint256[] memory) { return _deposits[msg.sender].values(); } function totalTokensInWallet() public view returns(uint256) { return cosmictoken.balanceOf(msg.sender); } function onERC721Received( address, address, uint256, bytes calldata ) external pure override returns (bytes4) { return IERC721Receiver.onERC721Received.selector; } } // File: cosmicFusion.sol pragma solidity 0.8.7; contract CosmicFusion is ERC721A, Ownable, ReentrancyGuard { using Address for address; using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private _tokenIdTracker; string public baseURI; string public baseExtension = ".json"; mapping (uint256 => address) public fusionIndexToAddress; mapping (uint256 => bool) public hasFused; CosmicLabs public cosmicLabs; constructor() ERC721A("Cosmic Fusion", "CFUSION", 100) { } function setCosmicLabsAddress(address clabsAddress) public onlyOwner { cosmicLabs = CosmicLabs(clabsAddress); } modifier onlySender { require(msg.sender == tx.origin); _; } function teamMint(uint256 amount) public onlyOwner nonReentrant { for(uint i=0;i<amount;i++) { fusionIndexToAddress[_tokenIdTracker.current()] = msg.sender; _tokenIdTracker.increment(); } _safeMint(msg.sender, amount); } function FuseDucks(uint256[] memory tokenIds) public payable nonReentrant { require(tokenIds.length % 2 == 0, "Odd amount of Ducks Selected"); for(uint256 i=0; i<tokenIds.length; i++) { require(tokenIds[i] >= 1001 , "You selected a Genesis"); require(!hasFused[tokenIds[i]], "These ducks have already fused!"); cosmicLabs.transferFrom(msg.sender, 0x000000000000000000000000000000000000dEaD ,tokenIds[i]); hasFused[tokenIds[i]] = true; } uint256 fuseAmount = tokenIds.length / 2; for(uint256 i=0; i<fuseAmount; i++) { fusionIndexToAddress[_tokenIdTracker.current()] = msg.sender; _tokenIdTracker.increment(); } _safeMint(msg.sender, fuseAmount); } function _withdraw(address payable address_, uint256 amount_) internal { (bool success, ) = payable(address_).call{value: amount_}(""); require(success, "Transfer failed"); } function withdrawEther() external onlyOwner { _withdraw(payable(msg.sender), address(this).balance); } function withdrawEtherTo(address payable to_) external onlyOwner { _withdraw(to_, address(this).balance); } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } function walletOfOwner(address address_) public virtual view returns (uint256[] memory) { uint256 _balance = balanceOf(address_); uint256[] memory _tokens = new uint256[] (_balance); uint256 _index; uint256 _loopThrough = totalSupply(); for (uint256 i = 0; i < _loopThrough; i++) { bool _exists = _exists(i); if (_exists) { if (ownerOf(i) == address_) { _tokens[_index] = i; _index++; } } else if (!_exists && _tokens[_balance - 1] == 0) { _loopThrough++; } } return _tokens; } function transferFrom(address from, address to, uint256 tokenId) public override { fusionIndexToAddress[tokenId] = to; ERC721A.transferFrom(from, to, tokenId); } function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public override { fusionIndexToAddress[tokenId] = to; ERC721A.safeTransferFrom(from, to, tokenId, _data); } } // File: cut.sol pragma solidity 0.8.7; contract CosmicUtilityToken is ERC20I, Ownable, ReentrancyGuard { mapping (uint256 => uint256) public tokenIdEarned; mapping (uint256 => uint256) public fusionEarned; uint256 public GENESIS_RATE = 0.02777777777 ether; uint256 public FUSION_RATE = 12 ether; // Sat Feb 22 2022 05:00:00 GMT+0000 uint256 public startTime = 1645506000; // Sat Feb 22 2025 05:00:00 GMT+0000 uint256 public constant endTimeFusion = 1740200400; uint256 public totalTokensBurned = 0; mapping (address => bool) public firstClaim; mapping(uint256 => uint256) public fusionToTimestamp; CosmicLabs public cosmicLabs; CosmicToken public cosmicToken; CosmicFusion public cosmicFusion; constructor(address CLABS, address CUT) ERC20I("Cosmic Utility Token", "CUT") { cosmicLabs = CosmicLabs(CLABS); cosmicToken = CosmicToken(CUT); } function setFusionContract(address fusionContract) public onlyOwner { cosmicFusion = CosmicFusion(fusionContract); } function setCosmicLabsContract(address clabsContract) public onlyOwner { cosmicLabs = CosmicLabs(clabsContract); } function changeGenesis_Rate(uint256 _incoming) public onlyOwner { GENESIS_RATE = _incoming; } function changeFusion_Rate(uint256 _incoming) public onlyOwner { FUSION_RATE = _incoming; } function teamMint(uint256 totalAmount) public onlyOwner stakingEnded { _mint(msg.sender, (totalAmount * 10 ** 18)); _mint(0xcD6a42782d230D7c13A74ddec5dD140e55499Df9, (totalAmount * 10 ** 18)); _mint(0x28dD793B34202eeaEe7D8e1Bb74b812641a503e0, (totalAmount * 10 ** 18)); _mint(0xe7D6f9bE83443BE2527f64bE07639776Fd422e1E, (totalAmount * 10 ** 18)); _mint(0x7b977283DE834A7e82d4f4F81bD8cc9267960459, (totalAmount * 10 ** 18)); _mint(0x5d8026cdC76A5731820B41963059249dfb131C65, (totalAmount * 10 ** 18)); _mint(0xd9bC4a4057eD82f58b0ABECDbe3cCaF8e81aF44A, (totalAmount * 10 ** 18)); _mint(0x83e02c9f0ec019f75d3B7E6Ac193109c9e7224EA, (totalAmount * 10 ** 18)); } //migrate old cut to new cut modifier hasMigrated { require(firstClaim[msg.sender] == false); _; } modifier stakingEnded { require(block.timestamp < endTimeFusion); _; } function migrateCut() public nonReentrant hasMigrated stakingEnded { uint256 howManyTokens = cosmicToken.balanceOf(msg.sender); uint256 extraCommision = (howManyTokens * 10) / 100; cosmicToken.transferFrom(msg.sender, address(this), howManyTokens); firstClaim[msg.sender] = true; _mint(msg.sender, (howManyTokens + extraCommision)); } //Genesis Ducks functions function claimRewards(uint256[] memory nftsToClaim) public nonReentrant stakingEnded { for(uint256 i=0;i<nftsToClaim.length;i++) { require(cosmicLabs.ownerOf(nftsToClaim[i]) == msg.sender, "You are not the owner of these tokens"); } _mint(msg.sender, tokensAccumulated(nftsToClaim)); for(uint256 i=0; i<nftsToClaim.length;i++) { tokenIdEarned[nftsToClaim[i]] = block.timestamp; } } function tokensAccumulated(uint256[] memory nftsToCheck) public view returns(uint256) { uint256 totalTokensEarned; for(uint256 i=0; i<nftsToCheck.length;i++) { if(nftsToCheck[i] <= 1000) { totalTokensEarned += (howManyMinStaked(nftsToCheck[i]) * GENESIS_RATE); } } return totalTokensEarned; } function howManyMinStaked(uint256 tokenId) public view returns(uint256) { uint256 timeCalc; if(tokenIdEarned[tokenId] == 0) { timeCalc = block.timestamp - startTime; } else { timeCalc = block.timestamp - tokenIdEarned[tokenId]; } uint256 returnMins = timeCalc / 60; return returnMins; } //fusion passive staking methods function getPendingTokensFusion(uint256 tokenId_) public view returns (uint256) { uint256 _timestamp = fusionToTimestamp[tokenId_] == 0 ? startTime : fusionToTimestamp[tokenId_] > endTimeFusion ? endTimeFusion : fusionToTimestamp[tokenId_]; uint256 _currentTimeOrEnd = block.timestamp > endTimeFusion ? endTimeFusion : block.timestamp; uint256 _timeElapsed = _currentTimeOrEnd - _timestamp; return (_timeElapsed * FUSION_RATE) / 1 days; } function getPendingTokensManyFusion(uint256[] memory tokenIds_) public view returns (uint256) { uint256 _pendingTokens; for (uint256 i = 0; i < tokenIds_.length; i++) { _pendingTokens += getPendingTokensFusion(tokenIds_[i]); } return _pendingTokens; } function claimFusion(address to_, uint256[] memory tokenIds_) external { require(tokenIds_.length > 0, "You must claim at least 1 Fusion!"); uint256 _pendingTokens = tokenIds_.length > 1 ? getPendingTokensManyFusion(tokenIds_) : getPendingTokensFusion(tokenIds_[0]); // Run loop to update timestamp for each fusion for (uint256 i = 0; i < tokenIds_.length; i++) { require(to_ == cosmicFusion.fusionIndexToAddress(tokenIds_[i]), "claim(): to_ is not owner of Cosmic Fusion!"); fusionToTimestamp[tokenIds_[i]] = block.timestamp; } _mint(to_, _pendingTokens); } function getPendingTokensOfAddress(address address_) public view returns (uint256) { uint256[] memory _tokensOfAddress = cosmicFusion.walletOfOwner(address_); return getPendingTokensManyFusion(_tokensOfAddress); } //deflationary function burn(address _from, uint256 _amount) external { require(msg.sender == _from, "You do not own these tokens"); _burn(_from, _amount); totalTokensBurned += _amount; } function burnFrom(address _from, uint256 _amount) public override { ERC20I.burnFrom(_from, _amount); } } // File: @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** * @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. * * NOTE: 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. * * NOTE: 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); } // File: @openzeppelin/contracts/token/ERC1155/IERC1155.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; /** * @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; } // File: @openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC1155/ERC1155.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; /** * @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 ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address 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}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).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 { _setApprovalForAll(_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 `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, 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 `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, 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 from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); 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: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @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, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @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 IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.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 IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.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; } } // File: @openzeppelin/contracts/token/ERC1155/extensions/ERC1155Burnable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Burnable.sol) pragma solidity ^0.8.0; /** * @dev Extension of {ERC1155} that allows token holders to destroy both their * own tokens and those that they have been approved to use. * * _Available since v3.1._ */ abstract contract ERC1155Burnable is ERC1155 { function burn( address account, uint256 id, uint256 value ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burn(account, id, value); } function burnBatch( address account, uint256[] memory ids, uint256[] memory values ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burnBatch(account, ids, values); } } // File: CosmicLabsCollectables.sol /// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.7; contract CosmicLabsCollectables is ERC1155Burnable, Ownable { using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private _tokenIdTracker; CosmicUtilityToken public cutToken; string public baseURI; string public baseExtension = ".json"; uint256 public cutPrice = 3000 ether; uint256 public collectibleID = 1; uint256 public maxIdsForSale = 10; bool public saleOpen = true; modifier isSaleOpen() { require(saleOpen == true); _; } constructor(string memory _initBaseURI, address _yield) ERC1155(_initBaseURI) { setBaseURI(_initBaseURI); cutToken = CosmicUtilityToken(_yield); for(uint256 i=0; i<1; i++) { _mint(msg.sender, collectibleID, 1, ""); } collectibleID += 1; } function setYieldToken(address _yield) public onlyOwner { cutToken = CosmicUtilityToken(_yield); } function setCutPrice(uint256 newCutPrice) public onlyOwner { cutPrice = (newCutPrice * 10 ** 18); } function setMaxCurrent(uint256 newMax) public onlyOwner { maxIdsForSale = newMax; } function flipSale() public onlyOwner { saleOpen = !saleOpen; } function nextCollectible(uint256 newCutPrice, uint256 maxSupplyOfNew, uint256 teamMint) public onlyOwner { collectibleID += 1; cutPrice = (newCutPrice * 10 ** 18); maxIdsForSale = maxSupplyOfNew; _tokenIdTracker.reset(); if(teamMint > 0) { _mint(msg.sender, collectibleID, teamMint, ""); } } function totalTokens() public view returns (uint256) { return _tokenIdTracker.current(); } function MintCosmicCollectible(uint256 amount) public payable isSaleOpen { require(cutToken.balanceOf(msg.sender) >= (cutPrice * amount), "You Don't Have Enough Cut Tokens!"); require((totalTokens() + amount) <= maxIdsForSale, "Surpassing the max supply!"); cutToken.transferFrom(tx.origin, address(this), (cutPrice * amount)); for(uint256 i=0; i<amount; i++) { _tokenIdTracker.increment(); } _mint(msg.sender, collectibleID, amount, ""); } function burnAllCUT() external onlyOwner { cutToken.burn(address(this), cutToken.balanceOf(address(this))); } function withdrawContractEther(address payable recipient) external onlyOwner { recipient.transfer(getBalance()); } function getBalance() public view returns(uint) { return address(this).balance; } function _baseURI() internal view virtual returns (string memory) { return baseURI; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function uri(uint256 incomingTokenID) public view override virtual returns (string memory) { string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, incomingTokenID.toString(), baseExtension)) : ""; } }
fusion passive staking methods
function getPendingTokensFusion(uint256 tokenId_) public view returns (uint256) { uint256 _timestamp = fusionToTimestamp[tokenId_] == 0 ? startTime : fusionToTimestamp[tokenId_] > endTimeFusion ? endTimeFusion : fusionToTimestamp[tokenId_]; uint256 _currentTimeOrEnd = block.timestamp > endTimeFusion ? endTimeFusion : block.timestamp; uint256 _timeElapsed = _currentTimeOrEnd - _timestamp; return (_timeElapsed * FUSION_RATE) / 1 days; }
10,650,748
[ 1, 74, 7063, 23697, 384, 6159, 2590, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1689, 2846, 5157, 42, 7063, 12, 11890, 5034, 1147, 548, 67, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 389, 5508, 273, 25944, 774, 4921, 63, 2316, 548, 67, 65, 422, 374, 692, 203, 5411, 8657, 294, 25944, 774, 4921, 63, 2316, 548, 67, 65, 405, 13859, 42, 7063, 692, 7010, 5411, 13859, 42, 7063, 294, 25944, 774, 4921, 63, 2316, 548, 67, 15533, 203, 3639, 2254, 5034, 389, 2972, 950, 1162, 1638, 273, 1203, 18, 5508, 405, 13859, 42, 7063, 692, 203, 5411, 13859, 42, 7063, 294, 1203, 18, 5508, 31, 203, 3639, 2254, 5034, 389, 957, 28827, 273, 389, 2972, 950, 1162, 1638, 300, 389, 5508, 31, 203, 203, 3639, 327, 261, 67, 957, 28827, 380, 478, 3378, 1146, 67, 24062, 13, 342, 404, 4681, 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 ]
./full_match/420666/0x36d4Fec597d673a37f26a7346EF3793cfAb95D9f/sources/FrogSwapRouter.sol
given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'FrogSwapLibrary: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'FrogSwapLibrary: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(995); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; }
16,368,695
[ 1, 10822, 392, 810, 3844, 434, 392, 3310, 471, 3082, 400, 264, 3324, 16, 1135, 326, 4207, 876, 3844, 434, 326, 1308, 3310, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 24418, 1182, 12, 11890, 3844, 382, 16, 2254, 20501, 382, 16, 2254, 20501, 1182, 13, 2713, 16618, 1135, 261, 11890, 3844, 1182, 13, 288, 203, 3639, 2583, 12, 8949, 382, 405, 374, 16, 296, 42, 303, 75, 12521, 9313, 30, 2120, 6639, 42, 1653, 7266, 2222, 67, 15934, 67, 2192, 51, 5321, 8284, 203, 3639, 2583, 12, 455, 6527, 382, 405, 374, 597, 20501, 1182, 405, 374, 16, 296, 42, 303, 75, 12521, 9313, 30, 2120, 6639, 42, 1653, 7266, 2222, 67, 2053, 53, 3060, 4107, 8284, 203, 3639, 2254, 3844, 382, 1190, 14667, 273, 3844, 382, 18, 16411, 12, 2733, 25, 1769, 203, 3639, 2254, 16730, 273, 3844, 382, 1190, 14667, 18, 16411, 12, 455, 6527, 1182, 1769, 203, 3639, 2254, 15030, 273, 20501, 382, 18, 16411, 12, 18088, 2934, 1289, 12, 8949, 382, 1190, 14667, 1769, 203, 3639, 3844, 1182, 273, 16730, 342, 15030, 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 ]
./full_match/1/0x563115ac7EdD780f5BFC2E3078Eb97892fE8CfDe/sources/src/SwapFacility.sol
@dev Get prices of underlying and billy tokens @return underlyingTokenPrice Underlying token price @return billyTokenPrice Billy token price
function _getTokenPrices(bool _boundPrices) internal view returns (uint256 underlyingTokenPrice, uint256 billyTokenPrice) { uint256 stablePrice = _readOracle(underlyingTokenOracle); uint256 billyPrice = _readOracle(billyTokenOracle); if (_boundPrices) { if (stablePrice < MIN_STABLE_VALUE) revert ExtremePrice(); if (billyPrice > MAX_BILLY_VALUE) revert ExtremePrice(); } underlyingTokenPrice = STABLE_VALUE * billyScale; billyTokenPrice = billyPrice * underlyingScale; }
4,918,056
[ 1, 967, 19827, 434, 6808, 471, 324, 330, 715, 2430, 327, 6808, 1345, 5147, 21140, 6291, 1147, 6205, 327, 324, 330, 715, 1345, 5147, 605, 330, 715, 1147, 6205, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 588, 1345, 31862, 12, 6430, 389, 3653, 31862, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 6808, 1345, 5147, 16, 2254, 5034, 324, 330, 715, 1345, 5147, 13, 203, 565, 288, 203, 3639, 2254, 5034, 14114, 5147, 273, 389, 896, 23601, 12, 9341, 6291, 1345, 23601, 1769, 7010, 3639, 2254, 5034, 324, 330, 715, 5147, 273, 389, 896, 23601, 12, 70, 330, 715, 1345, 23601, 1769, 203, 3639, 309, 261, 67, 3653, 31862, 13, 288, 203, 5411, 309, 261, 15021, 5147, 411, 6989, 67, 882, 2782, 67, 4051, 13, 15226, 6419, 2764, 73, 5147, 5621, 203, 5411, 309, 261, 70, 330, 715, 5147, 405, 4552, 67, 38, 2627, 7076, 67, 4051, 13, 15226, 6419, 2764, 73, 5147, 5621, 203, 3639, 289, 203, 3639, 6808, 1345, 5147, 273, 2347, 2782, 67, 4051, 380, 324, 330, 715, 5587, 31, 203, 3639, 324, 330, 715, 1345, 5147, 273, 324, 330, 715, 5147, 380, 6808, 5587, 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 ]
// File: @openzeppelin/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 { // 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/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 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 { _owner = _msgSender(); 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; } } // File: contracts/Library/IERC20.sol pragma solidity ^0.5.14; interface IERC20 { event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); function transfer(address _to, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 _value) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); } // File: contracts/Library/SafeMath.sol pragma solidity ^0.5.14; /** * @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: contracts/Library/Freezer.sol pragma solidity ^0.5.14; /** * @title Freezer * @author Yoonsung * @notice This Contracts is an extension of the ERC20. Transfer * of a specific address can be blocked from by the Owner of the * Token Contract. */ contract Freezer is Ownable { event Freezed(address dsc); event Unfreezed(address dsc); mapping (address => bool) public freezing; modifier isFreezed (address src) { require(freezing[src] == false, "Freeze/Fronzen-Account"); _; } /** * @notice The Freeze function sets the transfer limit * for a specific address. * @param _dsc address The specify address want to limit the transfer. */ function freeze(address _dsc) external onlyOwner { require(_dsc != address(0), "Freeze/Zero-Address"); require(freezing[_dsc] == false, "Freeze/Already-Freezed"); freezing[_dsc] = true; emit Freezed(_dsc); } /** * @notice The Freeze function removes the transfer limit * for a specific address. * @param _dsc address The specify address want to remove the transfer. */ function unFreeze(address _dsc) external onlyOwner { require(freezing[_dsc] == true, "Freeze/Already-Unfreezed"); delete freezing[_dsc]; emit Unfreezed(_dsc); } } // File: contracts/Library/SendLimiter.sol pragma solidity ^0.5.14; /** * @title SendLimiter * @author Yoonsung * @notice This contract acts as an ERC20 extension. It must * be called from the creator of the ERC20, and a modifier is * provided that can be used together. This contract is short-lived. * You cannot re-enable it after SendUnlock, to be careful. Provides * a set of functions to manage the addresses that can be sent. */ contract SendLimiter is Ownable { event SendWhitelisted(address dsc); event SendDelisted(address dsc); event SendUnlocked(); bool public sendLimit; mapping (address => bool) public sendWhitelist; /** * @notice In constructor, Set Send Limit exceptionally msg.sender. * constructor is used, the restriction is activated. */ constructor() public { sendLimit = true; sendWhitelist[msg.sender] = true; } modifier isAllowedSend (address dsc) { if (sendLimit) require(sendWhitelist[dsc], "SendLimiter/Not-Allow-Address"); _; } /** * @notice Register the address that you want to allow to be sent. * @param _whiteAddress address The specify what to send target. */ function addAllowSender(address _whiteAddress) public onlyOwner { require(_whiteAddress != address(0), "SendLimiter/Not-Allow-Zero-Address"); sendWhitelist[_whiteAddress] = true; emit SendWhitelisted(_whiteAddress); } /** * @notice Register the addresses that you want to allow to be sent. * @param _whiteAddresses address[] The specify what to send target. */ function addAllowSenders(address[] memory _whiteAddresses) public onlyOwner { for (uint256 i = 0; i < _whiteAddresses.length; i++) { addAllowSender(_whiteAddresses[i]); } } /** * @notice Remove the address that you want to allow to be sent. * @param _whiteAddress address The specify what to send target. */ function removeAllowedSender(address _whiteAddress) public onlyOwner { require(_whiteAddress != address(0), "SendLimiter/Not-Allow-Zero-Address"); delete sendWhitelist[_whiteAddress]; emit SendDelisted(_whiteAddress); } /** * @notice Remove the addresses that you want to allow to be sent. * @param _whiteAddresses address[] The specify what to send target. */ function removeAllowedSenders(address[] memory _whiteAddresses) public onlyOwner { for (uint256 i = 0; i < _whiteAddresses.length; i++) { removeAllowedSender(_whiteAddresses[i]); } } /** * @notice Revoke transfer restrictions. */ function sendUnlock() external onlyOwner { sendLimit = false; emit SendUnlocked(); } } // File: contracts/Library/ReceiveLimiter.sol pragma solidity ^0.5.14; /** * @title ReceiveLimiter * @author Yoonsung * @notice This contract acts as an ERC20 extension. It must * be called from the creator of the ERC20, and a modifier is * provided that can be used together. This contract is short-lived. * You cannot re-enable it after ReceiveUnlock, to be careful. Provides * a set of functions to manage the addresses that can be sent. */ contract ReceiveLimiter is Ownable { event ReceiveWhitelisted(address dsc); event ReceiveDelisted(address dsc); event ReceiveUnlocked(); bool public receiveLimit; mapping (address => bool) public receiveWhitelist; /** * @notice In constructor, Set Receive Limit exceptionally msg.sender. * constructor is used, the restriction is activated. */ constructor() public { receiveLimit = true; receiveWhitelist[msg.sender] = true; } modifier isAllowedReceive (address dsc) { if (receiveLimit) require(receiveWhitelist[dsc], "Limiter/Not-Allow-Address"); _; } /** * @notice Register the address that you want to allow to be receive. * @param _whiteAddress address The specify what to receive target. */ function addAllowReceiver(address _whiteAddress) public onlyOwner { require(_whiteAddress != address(0), "Limiter/Not-Allow-Zero-Address"); receiveWhitelist[_whiteAddress] = true; emit ReceiveWhitelisted(_whiteAddress); } /** * @notice Register the addresses that you want to allow to be receive. * @param _whiteAddresses address[] The specify what to receive target. */ function addAllowReceivers(address[] memory _whiteAddresses) public onlyOwner { for (uint256 i = 0; i < _whiteAddresses.length; i++) { addAllowReceiver(_whiteAddresses[i]); } } /** * @notice Remove the address that you want to allow to be receive. * @param _whiteAddress address The specify what to receive target. */ function removeAllowedReceiver(address _whiteAddress) public onlyOwner { require(_whiteAddress != address(0), "Limiter/Not-Allow-Zero-Address"); delete receiveWhitelist[_whiteAddress]; emit ReceiveDelisted(_whiteAddress); } /** * @notice Remove the addresses that you want to allow to be receive. * @param _whiteAddresses address[] The specify what to receive target. */ function removeAllowedReceivers(address[] memory _whiteAddresses) public onlyOwner { for (uint256 i = 0; i < _whiteAddresses.length; i++) { removeAllowedReceiver(_whiteAddresses[i]); } } /** * @notice Revoke Receive restrictions. */ function receiveUnlock() external onlyOwner { receiveLimit = false; emit ReceiveUnlocked(); } } // File: contracts/TokenAsset.sol pragma solidity ^0.5.14; /** * @title TokenAsset * @author Yoonsung * @notice This Contract is an implementation of TokenAsset's ERC20 * Basic ERC20 functions and "Burn" functions are implemented. For the * Burn function, only the Owner of Contract can be called and used * to incinerate unsold Token. Transfer and reception limits are imposed * after the contract is distributed and can be revoked through SendUnlock * and ReceiveUnlock. Don't do active again after cancellation. The Owner * may also suspend the transfer of a particular account at any time. */ contract TokenAsset is Ownable, IERC20, SendLimiter, ReceiveLimiter, Freezer { using SafeMath for uint256; string public constant name = "tokenAsset"; string public constant symbol = "NTB"; uint8 public constant decimals = 18; uint256 public totalSupply = 200000000e18; mapping (address => uint256) public balanceOf; mapping (address => mapping(address => uint256)) public allowance; /** * @notice In constructor, Set Send Limit and Receive Limits. * Additionally, Contract's publisher is authorized to own all tokens. */ constructor() SendLimiter() ReceiveLimiter() public { balanceOf[msg.sender] = totalSupply; } /** * @notice Transfer function sends Token to the target. However, * caller must have more tokens than or equal to the quantity for send. * @param _to address The specify what to send target. * @param _value uint256 The amount of token to tranfer. * @return True if the withdrawal succeeded, otherwise revert. */ function transfer ( address _to, uint256 _value ) external isAllowedSend(msg.sender) isAllowedReceive(_to) isFreezed(msg.sender) returns (bool) { require(_to != address(0), "TokenAsset/Not-Allow-Zero-Address"); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @notice Transfer function sends Token to the target. * In most cases, the allowed caller uses this function. Send * Token instead of owner. Allowance address must have more * tokens than or equal to the quantity for send. * @param _from address The acoount to sender. * @param _to address The specify what to send target. * @param _value uint256 The amount of token to tranfer. * @return True if the withdrawal succeeded, otherwise revert. */ function transferFrom ( address _from, address _to, uint256 _value ) external isAllowedSend(_from) isAllowedReceive(_to) isFreezed(_from) returns (bool) { require(_from != address(0), "TokenAsset/Not-Allow-Zero-Address"); require(_to != address(0), "TokenAsset/Not-Allow-Zero-Address"); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @notice The Owner of the Contracts incinerate own * Token. burn unsold Token and reduce totalsupply. Caller * must have more tokens than or equal to the quantity for send. * @param _value uint256 The amount of incinerate token. * @return True if the withdrawal succeeded, otherwise revert. */ function burn ( uint256 _value ) external returns (bool) { require(_value <= balanceOf[msg.sender]); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); emit Transfer(msg.sender, address(0), _value); return true; } /** * @notice Allow specific address to send token instead. * @param _spender address The address to send transaction on my behalf * @param _value uint256 The amount on my behalf, Usually 0 or uint256(-1). * @return True if the withdrawal succeeded, otherwise revert. */ function approve ( address _spender, uint256 _value ) external returns (bool) { require(_spender != address(0), "TokenAsset/Not-Allow-Zero-Address"); allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } }
* @notice Register the address that you want to allow to be receive. @param _whiteAddress address The specify what to receive target./
function addAllowReceiver(address _whiteAddress) public onlyOwner { require(_whiteAddress != address(0), "Limiter/Not-Allow-Zero-Address"); receiveWhitelist[_whiteAddress] = true; emit ReceiveWhitelisted(_whiteAddress); }
12,838,341
[ 1, 3996, 326, 1758, 716, 1846, 2545, 358, 1699, 358, 506, 6798, 18, 225, 389, 14739, 1887, 1758, 1021, 4800, 4121, 358, 6798, 1018, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 7009, 12952, 12, 2867, 389, 14739, 1887, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 24899, 14739, 1887, 480, 1758, 12, 20, 3631, 315, 22329, 19, 1248, 17, 7009, 17, 7170, 17, 1887, 8863, 203, 3639, 6798, 18927, 63, 67, 14739, 1887, 65, 273, 638, 31, 203, 3639, 3626, 17046, 18927, 329, 24899, 14739, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.15; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20 { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract BasicToken is ERC20 { using SafeMath for uint256; mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; modifier nonZeroEth(uint _value) { require(_value > 0); _; } modifier onlyPayloadSize() { require(msg.data.length >= 68); _; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) nonZeroEth(_value) onlyPayloadSize returns (bool) { if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]){ balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; }else{ return false; } } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) nonZeroEth(_value) onlyPayloadSize returns (bool) { if(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]){ uint256 _allowance = allowed[_from][msg.sender]; allowed[_from][msg.sender] = _allowance.sub(_value); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); Transfer(_from, _to, _value); return true; }else{ return false; } } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract RPTToken is BasicToken { using SafeMath for uint256; string public name = "RPT Token"; //name of the token string public symbol = "RPT"; // symbol of the token uint8 public decimals = 18; // decimals uint256 public totalSupply = 1000000000 * 10**18; // total supply of RPT Tokens // variables uint256 public keyEmployeeAllocation; // fund allocated to key employee uint256 public totalAllocatedTokens; // variable to regulate the funds allocation uint256 public tokensAllocatedToCrowdFund; // funds allocated to crowdfund // addresses address public founderMultiSigAddress = 0xf96E905091d38ca25e06C014fE67b5CA939eE83D; // multi sign address of founders which hold address public crowdFundAddress; // address of crowdfund contract //events event ChangeFoundersWalletAddress(uint256 _blockTimeStamp, address indexed _foundersWalletAddress); event TransferPreAllocatedFunds(uint256 _blockTimeStamp , address _to , uint256 _value); //modifiers modifier onlyCrowdFundAddress() { require(msg.sender == crowdFundAddress); _; } modifier nonZeroAddress(address _to) { require(_to != 0x0); _; } modifier onlyFounders() { require(msg.sender == founderMultiSigAddress); _; } // creation of the token contract function RPTToken (address _crowdFundAddress) { crowdFundAddress = _crowdFundAddress; // Token Distribution tokensAllocatedToCrowdFund = 70 * 10 ** 25; // 70 % allocation of totalSupply keyEmployeeAllocation = 30 * 10 ** 25; // 30 % allocation of totalSupply // Assigned balances to respective stakeholders balances[founderMultiSigAddress] = keyEmployeeAllocation; balances[crowdFundAddress] = tokensAllocatedToCrowdFund; totalAllocatedTokens = balances[founderMultiSigAddress]; } // function to keep track of the total token allocation function changeTotalSupply(uint256 _amount) onlyCrowdFundAddress { totalAllocatedTokens = totalAllocatedTokens.add(_amount); } // function to change founder multisig wallet address function changeFounderMultiSigAddress(address _newFounderMultiSigAddress) onlyFounders nonZeroAddress(_newFounderMultiSigAddress) { founderMultiSigAddress = _newFounderMultiSigAddress; ChangeFoundersWalletAddress(now, founderMultiSigAddress); } } contract RPTCrowdsale { using SafeMath for uint256; RPTToken public token; // Token variable //variables uint256 public totalWeiRaised; // Flag to track the amount raised uint32 public exchangeRate = 3000; // calculated using priceOfEtherInUSD/priceOfRPTToken uint256 public preDistriToAcquiantancesStartTime = 1510876801; // Friday, 17-Nov-17 00:00:01 UTC uint256 public preDistriToAcquiantancesEndTime = 1511827199; // Monday, 27-Nov-17 23:59:59 UTC uint256 public presaleStartTime = 1511827200; // Tuesday, 28-Nov-17 00:00:00 UTC uint256 public presaleEndTime = 1513036799; // Monday, 11-Dec-17 23:59:59 UTC uint256 public crowdfundStartTime = 1513036800; // Tuesday, 12-Dec-17 00:00:00 UTC uint256 public crowdfundEndTime = 1515628799; // Wednesday, 10-Jan-18 23:59:59 UTC bool internal isTokenDeployed = false; // Flag to track the token deployment // addresses address public founderMultiSigAddress; // Founders multi sign address address public remainingTokenHolder; // Address to hold the remaining tokens after crowdfund end address public beneficiaryAddress; // All funds are transferred to this address enum State { Acquiantances, PreSale, CrowdFund, Closed } //events event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount); event CrowdFundClosed(uint256 _blockTimeStamp); event ChangeFoundersWalletAddress(uint256 _blockTimeStamp, address indexed _foundersWalletAddress); //Modifiers modifier tokenIsDeployed() { require(isTokenDeployed == true); _; } modifier nonZeroEth() { require(msg.value > 0); _; } modifier nonZeroAddress(address _to) { require(_to != 0x0); _; } modifier onlyFounders() { require(msg.sender == founderMultiSigAddress); _; } modifier onlyPublic() { require(msg.sender != founderMultiSigAddress); _; } modifier inState(State state) { require(getState() == state); _; } modifier inBetween() { require(now >= preDistriToAcquiantancesStartTime && now <= crowdfundEndTime); _; } // Constructor to initialize the local variables function RPTCrowdsale (address _founderWalletAddress, address _remainingTokenHolder, address _beneficiaryAddress) { founderMultiSigAddress = _founderWalletAddress; remainingTokenHolder = _remainingTokenHolder; beneficiaryAddress = _beneficiaryAddress; } // Function to change the founders multi sign address function setFounderMultiSigAddress(address _newFounderAddress) onlyFounders nonZeroAddress(_newFounderAddress) { founderMultiSigAddress = _newFounderAddress; ChangeFoundersWalletAddress(now, founderMultiSigAddress); } // Attach the token contract function setTokenAddress(address _tokenAddress) external onlyFounders nonZeroAddress(_tokenAddress) { require(isTokenDeployed == false); token = RPTToken(_tokenAddress); isTokenDeployed = true; } // function call after crowdFundEndTime it transfers the remaining tokens to remainingTokenHolder address function endCrowdfund() onlyFounders returns (bool) { require(now > crowdfundEndTime); uint256 remainingToken = token.balanceOf(this); // remaining tokens if (remainingToken != 0) { token.transfer(remainingTokenHolder, remainingToken); CrowdFundClosed(now); return true; } else { CrowdFundClosed(now); return false; } } // Buy token function call only in duration of crowdfund active function buyTokens(address beneficiary) nonZeroEth tokenIsDeployed onlyPublic nonZeroAddress(beneficiary) inBetween payable public returns(bool) { fundTransfer(msg.value); uint256 amount = getNoOfTokens(exchangeRate, msg.value); if (token.transfer(beneficiary, amount)) { token.changeTotalSupply(amount); totalWeiRaised = totalWeiRaised.add(msg.value); TokenPurchase(beneficiary, msg.value, amount); return true; } return false; } // function to transfer the funds to founders account function fundTransfer(uint256 weiAmount) internal { beneficiaryAddress.transfer(weiAmount); } // Get functions // function to get the current state of the crowdsale function getState() internal constant returns(State) { if (now >= preDistriToAcquiantancesStartTime && now <= preDistriToAcquiantancesEndTime) { return State.Acquiantances; } if (now >= presaleStartTime && now <= presaleEndTime) { return State.PreSale; } if (now >= crowdfundStartTime && now <= crowdfundEndTime) { return State.CrowdFund; } else { return State.Closed; } } // function to calculate the total no of tokens with bonus multiplication function getNoOfTokens(uint32 _exchangeRate, uint256 _amount) internal returns (uint256) { uint256 noOfToken = _amount.mul(uint256(_exchangeRate)); uint256 noOfTokenWithBonus = ((uint256(100 + getCurrentBonusRate())).mul(noOfToken)).div(100); return noOfTokenWithBonus; } // function provide the current bonus rate function getCurrentBonusRate() internal returns (uint8) { if (getState() == State.Acquiantances) { return 40; } if (getState() == State.PreSale) { return 20; } if (getState() == State.CrowdFund) { return 0; } else { return 0; } } // provides the bonus % function getBonus() constant returns (uint8) { return getCurrentBonusRate(); } // send ether to the contract address // With at least 200 000 gas function() public payable { buyTokens(msg.sender); } }
fund allocated to key employee
uint256 public keyEmployeeAllocation;
12,837,409
[ 1, 74, 1074, 11977, 358, 498, 24539, 1340, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 11890, 5034, 1071, 498, 41, 27520, 17353, 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 ]
pragma solidity >=0.8.0; import "./interfaces/IStake.sol"; import "./Stake.sol"; import "./Base.sol"; contract StakeManager is Base { event StakeCreated( address indexed from, address stakeToken, address rewardToken, address stake ); event LibUpdated(address indexed newLib); address[] public stakes; address public lib; constructor(address _config, address _lib) Base(_config) { require(_lib != address(0), "lib address = 0"); lib = _lib; } /** * @dev update stake library */ function updateLib(address _lib) external onlyCEO() { require(_lib != address(0), "lib address = 0"); lib = _lib; emit LibUpdated(_lib); } /** * @dev return number of stake */ function stakeCount() external view returns (uint256) { return stakes.length; } /** * @dev return array of all stake contracts * @return array of stakes */ function allStakes() external view returns (address[] memory) { return stakes; } /** * @dev claim rewards of sepcified address of stakes */ function claims(address[] calldata _stakes) external { for (uint256 i; i < _stakes.length; i++) { IStake(_stakes[i]).claim0(msg.sender); } } /** * @dev create a new stake contract * @param _stakeToken address of stakeable token * @param _startDate epoch seconds of mining start * @param _endDate epoch seconds of mining complete * @param _totalReward reward total */ function createStake( address _stakeToken, uint256 _startDate, uint256 _endDate, uint256 _totalReward ) external onlyCEO() { require(_stakeToken != address(0), "zero address"); require(_endDate > _startDate, "_endDate <= _startDate"); address rewardToken = config.protocolToken(); address stakeAddress = clone(lib); IStake(stakeAddress).initialize( _stakeToken, rewardToken, _startDate, _endDate, _totalReward ); TransferHelper.safeTransferFrom( rewardToken, msg.sender, stakeAddress, _totalReward ); stakes.push(stakeAddress); emit StakeCreated(msg.sender, _stakeToken, rewardToken, stakeAddress); config.notify(IConfig.EventType.STAKE_CREATED, stakeAddress); } function clone(address master) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore( ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(ptr, 0x14), shl(0x60, master)) mstore( add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } } pragma solidity >=0.8.0; interface IStake { function claim0(address _owner) external; function initialize( address stakeToken, address rewardToken, uint256 start, uint256 end, uint256 rewardPerBlock ) external; } pragma solidity >=0.8.0; import "./interfaces/IERC20.sol"; import "./interfaces/IConfig.sol"; import "./interfaces/IStake.sol"; import "./libs/TransferHelper.sol"; interface IConfigable { function getConfig() external returns (IConfig); } contract Stake is IStake { event StakeUpdated( address indexed staker, bool isIncrease, uint256 stakeChanged, uint256 stakeAmount ); event Claimed(address indexed staker, uint256 reward); // stake token address, ERC20 address public stakeToken; bool initialized; bool locker; // reward token address, ERC20 address public rewardToken; // Mining start date(epoch second) uint256 public startDateOfMining; // Mining end date(epoch second) uint256 public endDateOfMining; // controller address address controller; // reward per Second uint256 public rewardPerSecond; // timestamp of last updated uint256 public lastUpdatedTimestamp; uint256 public rewardPerTokenStored; // staked total uint256 private _totalSupply; struct StakerInfo { // exclude reward's amount uint256 rewardDebt; // stake total uint256 amount; // pending reward uint256 reward; } // staker's StakerInfo mapping(address => StakerInfo) public stakers; /* ========== MODIFIER ========== */ modifier stakeable() { require( block.timestamp <= endDateOfMining, "stake not begin or complete" ); _; } modifier enable() { require(initialized, "initialized = false"); _; } modifier onlyController { require(controller == msg.sender, "only controller"); _; } modifier lock() { require(locker == false, "locked"); locker = true; _; locker = false; } modifier updateReward(address _staker) { rewardPerTokenStored = rewardPerToken(); lastUpdatedTimestamp = lastTimeRewardApplicable(); if (_staker != address(0) && stakers[_staker].amount > 0) { stakers[_staker].reward = rewardOf(_staker); stakers[_staker].rewardDebt = rewardPerTokenStored; } _; } constructor() {} /* ========== MUTATIVE FUNCTIONS ========== */ /** * @dev initialize contract * @param _stake address of stake token * @param _reward address of reward token * @param _start epoch seconds of mining starts * @param _end epoch seconds of mining complete * @param _totalReward totalReward */ function initialize( address _stake, address _reward, uint256 _start, uint256 _end, uint256 _totalReward ) external override { require(!initialized, "initialized = true"); // only initialize once initialized = true; controller = msg.sender; stakeToken = _stake; rewardToken = _reward; startDateOfMining = _start; endDateOfMining = _end; rewardPerSecond = _totalReward / (_end - _start + 1); } /** * @dev stake token * @param _amount amount of token to be staked */ function stake(uint256 _amount) external enable() lock() updateReward(msg.sender) { require(_amount > 0, "amount = 0"); require( block.timestamp <= endDateOfMining, "stake not begin or complete" ); _totalSupply += _amount; stakers[msg.sender].amount += _amount; TransferHelper.safeTransferFrom( stakeToken, msg.sender, address(this), _amount ); emit StakeUpdated( msg.sender, true, _amount, stakers[msg.sender].amount ); _notify(); } /** * @dev unstake token * @param _amount amount of token to be unstaked */ function unstake(uint256 _amount) public enable() lock() updateReward(msg.sender) { require(_amount > 0, "amount = 0"); require(stakers[msg.sender].amount >= _amount, "insufficient amount"); _claim(msg.sender); _totalSupply -= _amount; stakers[msg.sender].amount -= _amount; TransferHelper.safeTransfer(stakeToken, msg.sender, _amount); emit StakeUpdated( msg.sender, false, _amount, stakers[msg.sender].amount ); _notify(); } /** * @dev claim rewards */ function claim() external enable() lock() updateReward(msg.sender) { _claim(msg.sender); } /** * @dev quit, claim reward + unstake all */ function quit() external enable() lock() updateReward(msg.sender) { unstake(stakers[msg.sender].amount); _claim(msg.sender); } /** * @dev claim rewards, only owner allowed * @param _staker staker address */ function claim0(address _staker) external override onlyController() enable() updateReward(msg.sender) { _claim(_staker); } /* ========== VIEWs ========== */ function lastTimeRewardApplicable() public view returns (uint256) { if (block.timestamp < startDateOfMining) return startDateOfMining; return block.timestamp > endDateOfMining ? endDateOfMining : block.timestamp; } function rewardPerToken() public view returns (uint256) { if (_totalSupply == 0 || block.timestamp < startDateOfMining) { return rewardPerTokenStored; } return rewardPerTokenStored + (((lastTimeRewardApplicable() - lastUpdatedTimestamp) * rewardPerSecond) * 1e18) / _totalSupply; } /** * @dev amount of stake per address * @param _staker staker address * @return amount of stake */ function stakeOf(address _staker) external view returns (uint256) { return stakers[_staker].amount; } /** * @dev amount of reward per address * @param _staker address * @return value reward amount of _staker */ function rewardOf(address _staker) public view returns (uint256 value) { StakerInfo memory info = stakers[_staker]; return (info.amount * (rewardPerToken() - info.rewardDebt)) / 1e18 + info.reward; } /* ========== INTERNAL FUNCTIONS ========== */ /** * @dev claim reward * @param _staker address */ function _claim(address _staker) private { uint256 reward = stakers[_staker].reward; if (reward > 0) { stakers[_staker].reward = 0; IConfig config = IConfigable(controller).getConfig(); uint256 claimFeeRate = config.claimFeeRate(); uint256 out = (reward * (10000 - claimFeeRate)) / 10000; uint256 fee = reward - out; TransferHelper.safeTransfer(rewardToken, _staker, out); if (fee > 0) { // transfer to feeTo TransferHelper.safeTransfer(rewardToken, config.feeTo(), fee); } emit Claimed(_staker, reward); _notify(); } } function _notify() private { IConfigable(controller).getConfig().notify( IConfig.EventType.STAKE_UPDATED, address(this) ); } } pragma solidity >=0.8.0; import "./interfaces/IConfig.sol"; contract Base { event ConfigUpdated(address indexed owner, address indexed config); IConfig internal config; modifier onlyCEO() { require(msg.sender == config.ceo(), "only CEO"); _; } constructor(address _configAddr) { require(_configAddr != address(0), "config address = 0"); config = IConfig(_configAddr); } function updateConfig(address _config) external onlyCEO() { require(_config != address(0), "config address = 0"); require(address(config) != _config, "address identical"); config = IConfig(_config); emit ConfigUpdated(msg.sender, _config); } function configAddress() external view returns (address) { return address(config); } function getConfig() external view returns (IConfig) { return config; } } pragma solidity >=0.8.0; interface IERC20 { event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (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); } pragma solidity >=0.8.0; interface IConfig { enum EventType {FUND_CREATED, FUND_UPDATED, STAKE_CREATED, STAKE_UPDATED, REG_CREATED, REG_UPDATED, PFUND_CREATED, PFUND_UPDATED} function ceo() external view returns (address); function protocolPool() external view returns (address); function protocolToken() external view returns (address); function feeTo() external view returns (address); function nameRegistry() external view returns (address); // function investTokenWhitelist() external view returns (address[] memory); function tokenMinFundSize(address token) external view returns (uint256); function investFeeRate() external view returns (uint256); function redeemFeeRate() external view returns (uint256); function claimFeeRate() external view returns (uint256); function poolCreationRate() external view returns (uint256); function slot0() external view returns (uint256); function slot1() external view returns (uint256); function slot2() external view returns (uint256); function slot3() external view returns (uint256); function slot4() external view returns (uint256); function notify(EventType _type, address _src) external; } pragma solidity >=0.8.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED' ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } }
bytes4(keccak256(bytes('approve(address,uint256)')));
) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED' ); }
1,534,156
[ 1, 3890, 24, 12, 79, 24410, 581, 5034, 12, 3890, 2668, 12908, 537, 12, 2867, 16, 11890, 5034, 2506, 3719, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 262, 2713, 288, 203, 3639, 261, 6430, 2216, 16, 1731, 3778, 501, 13, 273, 203, 5411, 1147, 18, 1991, 12, 21457, 18, 3015, 1190, 4320, 12, 20, 92, 5908, 25, 24852, 27, 70, 23, 16, 358, 16, 460, 10019, 203, 3639, 2583, 12, 203, 5411, 2216, 597, 261, 892, 18, 2469, 422, 374, 747, 24126, 18, 3922, 12, 892, 16, 261, 6430, 3719, 3631, 203, 5411, 296, 5912, 2276, 30, 14410, 3373, 3412, 67, 11965, 11, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0-or-later /// clip.sol -- Dai auction module 2.0 // Copyright (C) 2020-2021 Maker Ecosystem Growth Holdings, INC. // // 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 // (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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity >=0.6.12; interface VatLike { function move(address,address,uint256) external; function flux(bytes32,address,address,uint256) external; function ilks(bytes32) external returns (uint256, uint256, uint256, uint256, uint256); function suck(address,address,uint256) external; } interface PipLike { function peek() external returns (bytes32, bool); } interface SpotterLike { function par() external returns (uint256); function ilks(bytes32) external returns (PipLike, uint256); } interface DogLike { function chop(bytes32) external returns (uint256); function digs(bytes32, uint256) external; } interface ClipperCallee { function clipperCall(address, uint256, uint256, bytes calldata) external; } interface AbacusLike { function price(uint256, uint256) external view returns (uint256); } contract Clipper { // --- Auth --- mapping (address => uint256) public wards; function rely(address usr) external auth { wards[usr] = 1; emit Rely(usr); } function deny(address usr) external auth { wards[usr] = 0; emit Deny(usr); } modifier auth { require(wards[msg.sender] == 1, "Clipper/not-authorized"); _; } // --- Data --- bytes32 immutable public ilk; // Collateral type of this Clipper VatLike immutable public vat; // Core CDP Engine DogLike public dog; // Liquidation module address public vow; // Recipient of dai raised in auctions SpotterLike public spotter; // Collateral price module AbacusLike public calc; // Current price calculator uint256 public buf; // Multiplicative factor to increase starting price [ray] uint256 public tail; // Time elapsed before auction reset [seconds] uint256 public cusp; // Percentage drop before auction reset [ray] uint64 public chip; // Percentage of tab to suck from vow to incentivize keepers [wad] uint192 public tip; // Flat fee to suck from vow to incentivize keepers [rad] uint256 public chost; // Cache the ilk dust times the ilk chop to prevent excessive SLOADs [rad] uint256 public kicks; // Total auctions uint256[] public active; // Array of active auction ids struct Sale { uint256 pos; // Index in active array uint256 tab; // Dai to raise [rad] uint256 lot; // collateral to sell [wad] address usr; // Liquidated CDP uint96 tic; // Auction start time uint256 top; // Starting price [ray] } mapping(uint256 => Sale) public sales; uint256 internal locked; // Levels for circuit breaker // 0: no breaker // 1: no new kick() // 2: no new kick() or redo() // 3: no new kick(), redo(), or take() uint256 public stopped = 0; // --- Events --- event Rely(address indexed usr); event Deny(address indexed usr); event File(bytes32 indexed what, uint256 data); event File(bytes32 indexed what, address data); event Kick( uint256 indexed id, uint256 top, uint256 tab, uint256 lot, address indexed usr, address indexed kpr, uint256 coin ); event Take( uint256 indexed id, uint256 max, uint256 price, uint256 owe, uint256 tab, uint256 lot, address indexed usr ); event Redo( uint256 indexed id, uint256 top, uint256 tab, uint256 lot, address indexed usr, address indexed kpr, uint256 coin ); event Yank(uint256 id); // --- Init --- constructor(address vat_, address spotter_, address dog_, bytes32 ilk_) public { vat = VatLike(vat_); spotter = SpotterLike(spotter_); dog = DogLike(dog_); ilk = ilk_; buf = RAY; wards[msg.sender] = 1; emit Rely(msg.sender); } // --- Synchronization --- modifier lock { require(locked == 0, "Clipper/system-locked"); locked = 1; _; locked = 0; } modifier isStopped(uint256 level) { require(stopped < level, "Clipper/stopped-incorrect"); _; } // --- Administration --- function file(bytes32 what, uint256 data) external auth lock { if (what == "buf") buf = data; else if (what == "tail") tail = data; // Time elapsed before auction reset else if (what == "cusp") cusp = data; // Percentage drop before auction reset else if (what == "chip") chip = uint64(data); // Percentage of tab to incentivize (max: 2^64 - 1 => 18.xxx WAD = 18xx%) else if (what == "tip") tip = uint192(data); // Flat fee to incentivize keepers (max: 2^192 - 1 => 6.277T RAD) else if (what == "stopped") stopped = data; // Set breaker (0, 1, 2, or 3) else revert("Clipper/file-unrecognized-param"); emit File(what, data); } function file(bytes32 what, address data) external auth lock { if (what == "spotter") spotter = SpotterLike(data); else if (what == "dog") dog = DogLike(data); else if (what == "vow") vow = data; else if (what == "calc") calc = AbacusLike(data); else revert("Clipper/file-unrecognized-param"); emit File(what, data); } // --- Math --- uint256 constant BLN = 10 ** 9; uint256 constant WAD = 10 ** 18; uint256 constant RAY = 10 ** 27; function min(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x <= y ? x : y; } function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x); } function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = mul(x, y) / WAD; } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = mul(x, y) / RAY; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = mul(x, RAY) / y; } // --- Auction --- // get the price directly from the OSM // Could get this from rmul(Vat.ilks(ilk).spot, Spotter.mat()) instead, but // if mat has changed since the last poke, the resulting value will be // incorrect. function getFeedPrice() internal returns (uint256 feedPrice) { (PipLike pip, ) = spotter.ilks(ilk); (bytes32 val, bool has) = pip.peek(); require(has, "Clipper/invalid-price"); feedPrice = rdiv(mul(uint256(val), BLN), spotter.par()); } // start an auction // note: trusts the caller to transfer collateral to the contract // The starting price `top` is obtained as follows: // // top = val * buf / par // // Where `val` is the collateral's unitary value in USD, `buf` is a // multiplicative factor to increase the starting price, and `par` is a // reference per DAI. function kick( uint256 tab, // Debt [rad] uint256 lot, // Collateral [wad] address usr, // Address that will receive any leftover collateral address kpr // Address that will receive incentives ) external auth lock isStopped(1) returns (uint256 id) { // Input validation require(tab > 0, "Clipper/zero-tab"); require(lot > 0, "Clipper/zero-lot"); require(usr != address(0), "Clipper/zero-usr"); id = ++kicks; require(id > 0, "Clipper/overflow"); active.push(id); sales[id].pos = active.length - 1; sales[id].tab = tab; sales[id].lot = lot; sales[id].usr = usr; sales[id].tic = uint96(block.timestamp); uint256 top; top = rmul(getFeedPrice(), buf); require(top > 0, "Clipper/zero-top-price"); sales[id].top = top; // incentive to kick auction uint256 _tip = tip; uint256 _chip = chip; uint256 coin; if (_tip > 0 || _chip > 0) { coin = add(_tip, wmul(tab, _chip)); vat.suck(vow, kpr, coin); } emit Kick(id, top, tab, lot, usr, kpr, coin); } // Reset an auction // See `kick` above for an explanation of the computation of `top`. function redo( uint256 id, // id of the auction to reset address kpr // Address that will receive incentives ) external lock isStopped(2) { // Read auction data address usr = sales[id].usr; uint96 tic = sales[id].tic; uint256 top = sales[id].top; require(usr != address(0), "Clipper/not-running-auction"); // Check that auction needs reset // and compute current price [ray] (bool done,) = status(tic, top); require(done, "Clipper/cannot-reset"); uint256 tab = sales[id].tab; uint256 lot = sales[id].lot; sales[id].tic = uint96(block.timestamp); uint256 feedPrice = getFeedPrice(); top = rmul(feedPrice, buf); require(top > 0, "Clipper/zero-top-price"); sales[id].top = top; // incentive to redo auction uint256 _tip = tip; uint256 _chip = chip; uint256 coin; if (_tip > 0 || _chip > 0) { uint256 _chost = chost; if (tab >= _chost && mul(lot, feedPrice) >= _chost) { coin = add(_tip, wmul(tab, _chip)); vat.suck(vow, kpr, coin); } } emit Redo(id, top, tab, lot, usr, kpr, coin); } // Buy up to `amt` of collateral from the auction indexed by `id`. // // Auctions will not collect more DAI than their assigned DAI target,`tab`; // thus, if `amt` would cost more DAI than `tab` at the current price, the // amount of collateral purchased will instead be just enough to collect `tab` DAI. // // To avoid partial purchases resulting in very small leftover auctions that will // never be cleared, any partial purchase must leave at least `Clipper.chost` // remaining DAI target. `chost` is an asynchronously updated value equal to // (Vat.dust * Dog.chop(ilk) / WAD) where the values are understood to be determined // by whatever they were when Clipper.upchost() was last called. Purchase amounts // will be minimally decreased when necessary to respect this limit; i.e., if the // specified `amt` would leave `tab < chost` but `tab > 0`, the amount actually // purchased will be such that `tab == chost`. // // If `tab <= chost`, partial purchases are no longer possible; that is, the remaining // collateral can only be purchased entirely, or not at all. function take( uint256 id, // Auction id uint256 amt, // Upper limit on amount of collateral to buy [wad] uint256 max, // Maximum acceptable price (DAI / collateral) [ray] address who, // Receiver of collateral and external call address bytes calldata data // Data to pass in external call; if length 0, no call is done ) external lock isStopped(3) { address usr = sales[id].usr; uint96 tic = sales[id].tic; require(usr != address(0), "Clipper/not-running-auction"); uint256 price; { bool done; (done, price) = status(tic, sales[id].top); // Check that auction doesn't need reset require(!done, "Clipper/needs-reset"); } // Ensure price is acceptable to buyer require(max >= price, "Clipper/too-expensive"); uint256 lot = sales[id].lot; uint256 tab = sales[id].tab; uint256 owe; { // Purchase as much as possible, up to amt uint256 slice = min(lot, amt); // slice <= lot // DAI needed to buy a slice of this sale owe = mul(slice, price); // Don't collect more than tab of DAI if (owe > tab) { // Total debt will be paid owe = tab; // owe' <= owe // Adjust slice slice = owe / price; // slice' = owe' / price <= owe / price == slice <= lot } else if (owe < tab && slice < lot) { // If slice == lot => auction completed => dust doesn't matter uint256 _chost = chost; if (tab - owe < _chost) { // safe as owe < tab // If tab <= chost, buyers have to take the entire lot. require(tab > _chost, "Clipper/no-partial-purchase"); // Adjust amount to pay owe = tab - _chost; // owe' <= owe // Adjust slice slice = owe / price; // slice' = owe' / price < owe / price == slice < lot } } // Calculate remaining tab after operation tab = tab - owe; // safe since owe <= tab // Calculate remaining lot after operation lot = lot - slice; // Send collateral to who vat.flux(ilk, address(this), who, slice); // Do external call (if data is defined) but to be // extremely careful we don't allow to do it to the two // contracts which the Clipper needs to be authorized DogLike dog_ = dog; if (data.length > 0 && who != address(vat) && who != address(dog_)) { ClipperCallee(who).clipperCall(msg.sender, owe, slice, data); } // Get DAI from caller vat.move(msg.sender, vow, owe); // Removes Dai out for liquidation from accumulator dog_.digs(ilk, lot == 0 ? tab + owe : owe); } if (lot == 0) { _remove(id); } else if (tab == 0) { vat.flux(ilk, address(this), usr, lot); _remove(id); } else { sales[id].tab = tab; sales[id].lot = lot; } emit Take(id, max, price, owe, tab, lot, usr); } function _remove(uint256 id) internal { uint256 _move = active[active.length - 1]; if (id != _move) { uint256 _index = sales[id].pos; active[_index] = _move; sales[_move].pos = _index; } active.pop(); delete sales[id]; } // The number of active auctions function count() external view returns (uint256) { return active.length; } // Return the entire array of active auctions function list() external view returns (uint256[] memory) { return active; } // Externally returns boolean for if an auction needs a redo and also the current price function getStatus(uint256 id) external view returns (bool needsRedo, uint256 price, uint256 lot, uint256 tab) { // Read auction data address usr = sales[id].usr; uint96 tic = sales[id].tic; bool done; (done, price) = status(tic, sales[id].top); needsRedo = usr != address(0) && done; lot = sales[id].lot; tab = sales[id].tab; } // Internally returns boolean for if an auction needs a redo function status(uint96 tic, uint256 top) internal view returns (bool done, uint256 price) { price = calc.price(top, sub(block.timestamp, tic)); done = (sub(block.timestamp, tic) > tail || rdiv(price, top) < cusp); } // Public function to update the cached dust*chop value. function upchost() external { (,,,, uint256 _dust) = VatLike(vat).ilks(ilk); chost = wmul(_dust, dog.chop(ilk)); } // Cancel an auction during ES or via governance action. function yank(uint256 id) external auth lock { require(sales[id].usr != address(0), "Clipper/not-running-auction"); dog.digs(ilk, sales[id].tab); vat.flux(ilk, address(this), msg.sender, sales[id].lot); _remove(id); emit Yank(id); } }
Collateral type of this Clipper
bytes32 immutable public ilk;
7,614
[ 1, 13535, 2045, 287, 618, 434, 333, 385, 3169, 457, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1731, 1578, 225, 11732, 1071, 14254, 79, 31, 565, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /// @title An optional contract that allows us to associate metadata to our cards. /// @author The CryptoStrikers Team contract StrikersMetadata { /// @dev The base url for the API where we fetch the metadata. /// ex: https://us-central1-cryptostrikers-api.cloudfunctions.net/cards/ string public apiUrl; constructor(string _apiUrl) public { apiUrl = _apiUrl; } /// @dev Returns the API URL for a given token Id. /// ex: https://us-central1-cryptostrikers-api.cloudfunctions.net/cards/22 /// Right now, this endpoint returns a JSON blob conforming to OpenSea's spec. /// see: https://docs.opensea.io/docs/2-adding-metadata function tokenURI(uint256 _tokenId) external view returns (string) { string memory _id = uint2str(_tokenId); return strConcat(apiUrl, _id); } // String helpers below were taken from Oraclize. // https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.4.sol function strConcat(string _a, string _b) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); string memory ab = new string(_ba.length + _bb.length); bytes memory bab = bytes(ab); uint k = 0; for (uint i = 0; i < _ba.length; i++) bab[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) bab[k++] = _bb[i]; return string(bab); } function uint2str(uint i) internal pure returns (string) { if (i == 0) return "0"; uint j = i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0) { bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Metadata is ERC721Basic { function name() public view returns (string _name); function symbol() public view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } /** * @title ERC-721 Non-Fungible Token Standard, full implementation interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. This function MUST use 50,000 gas or less. Return of other * than the magic value MUST result in the transaction being reverted. * Note: the contract address is always the message sender. * @param _from The sending address * @param _tokenId The NFT identifier which is being transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` */ function onERC721Received(address _from, uint256 _tokenId, bytes _data) public returns(bytes4); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. assembly { size := extcodesize(addr) } // solium-disable-line security/no-inline-assembly return size > 0; } } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is ERC721Basic { using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId)); _; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existance of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * @dev The zero address indicates there is no approved address. * @dev There can only be one approved address per token at a given time. * @dev Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); if (getApproved(_tokenId) != address(0) || _to != address(0)) { tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for a the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * @dev An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address _owner, address _operator) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) { address owner = ownerOf(_tokenId); return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender); } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @dev Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); emit Approval(_owner, address(0), _tokenId); } } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * @dev The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received(_from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } /** * @title Full ERC721 Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Token is ERC721, ERC721BasicToken { // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping (address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) internal tokenURIs; /** * @dev Constructor function */ function ERC721Token(string _name, string _symbol) public { name_ = _name; symbol_ = _symbol; } /** * @dev Gets the token name * @return string representing the token name */ function name() public view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() public view returns (string) { return symbol_; } /** * @dev Returns an URI for a given token ID * @dev Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * @dev Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * @dev Reverts if the token ID does not exist * @param _tokenId uint256 ID of the token to set its URI * @param _uri string URI to assign */ function _setTokenURI(uint256 _tokenId, string _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); // Clear metadata (if any) if (bytes(tokenURIs[_tokenId]).length != 0) { delete tokenURIs[_tokenId]; } // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } } /// @title The contract that manages all the players that appear in our game. /// @author The CryptoStrikers Team contract StrikersPlayerList is Ownable { // We only use playerIds in StrikersChecklist.sol (to // indicate which player features on instances of a // given ChecklistItem), and nowhere else in the app. // While it's not explictly necessary for any of our // contracts to know that playerId 0 corresponds to // Lionel Messi, we think that it's nice to have // a canonical source of truth for who the playerIds // actually refer to. Storing strings (player names) // is expensive, so we just use Events to prove that, // at some point, we said a playerId represents a given person. /// @dev The event we fire when we add a player. event PlayerAdded(uint8 indexed id, string name); /// @dev How many players we've added so far /// (max 255, though we don't plan on getting close) uint8 public playerCount; /// @dev Here we add the players we are launching with on Day 1. /// Players are loosely ranked by things like FIFA ratings, /// number of Instagram followers, and opinions of CryptoStrikers /// team members. Feel free to yell at us on Twitter. constructor() public { addPlayer("Lionel Messi"); // 0 addPlayer("Cristiano Ronaldo"); // 1 addPlayer("Neymar"); // 2 addPlayer("Mohamed Salah"); // 3 addPlayer("Robert Lewandowski"); // 4 addPlayer("Kevin De Bruyne"); // 5 addPlayer("Luka Modrić"); // 6 addPlayer("Eden Hazard"); // 7 addPlayer("Sergio Ramos"); // 8 addPlayer("Toni Kroos"); // 9 addPlayer("Luis Suárez"); // 10 addPlayer("Harry Kane"); // 11 addPlayer("Sergio Agüero"); // 12 addPlayer("Kylian Mbappé"); // 13 addPlayer("Gonzalo Higuaín"); // 14 addPlayer("David de Gea"); // 15 addPlayer("Antoine Griezmann"); // 16 addPlayer("N'Golo Kanté"); // 17 addPlayer("Edinson Cavani"); // 18 addPlayer("Paul Pogba"); // 19 addPlayer("Isco"); // 20 addPlayer("Marcelo"); // 21 addPlayer("Manuel Neuer"); // 22 addPlayer("Dries Mertens"); // 23 addPlayer("James Rodríguez"); // 24 addPlayer("Paulo Dybala"); // 25 addPlayer("Christian Eriksen"); // 26 addPlayer("David Silva"); // 27 addPlayer("Gabriel Jesus"); // 28 addPlayer("Thiago"); // 29 addPlayer("Thibaut Courtois"); // 30 addPlayer("Philippe Coutinho"); // 31 addPlayer("Andrés Iniesta"); // 32 addPlayer("Casemiro"); // 33 addPlayer("Romelu Lukaku"); // 34 addPlayer("Gerard Piqué"); // 35 addPlayer("Mats Hummels"); // 36 addPlayer("Diego Godín"); // 37 addPlayer("Mesut Özil"); // 38 addPlayer("Son Heung-min"); // 39 addPlayer("Raheem Sterling"); // 40 addPlayer("Hugo Lloris"); // 41 addPlayer("Radamel Falcao"); // 42 addPlayer("Ivan Rakitić"); // 43 addPlayer("Leroy Sané"); // 44 addPlayer("Roberto Firmino"); // 45 addPlayer("Sadio Mané"); // 46 addPlayer("Thomas Müller"); // 47 addPlayer("Dele Alli"); // 48 addPlayer("Keylor Navas"); // 49 addPlayer("Thiago Silva"); // 50 addPlayer("Raphaël Varane"); // 51 addPlayer("Ángel Di María"); // 52 addPlayer("Jordi Alba"); // 53 addPlayer("Medhi Benatia"); // 54 addPlayer("Timo Werner"); // 55 addPlayer("Gylfi Sigurðsson"); // 56 addPlayer("Nemanja Matić"); // 57 addPlayer("Kalidou Koulibaly"); // 58 addPlayer("Bernardo Silva"); // 59 addPlayer("Vincent Kompany"); // 60 addPlayer("João Moutinho"); // 61 addPlayer("Toby Alderweireld"); // 62 addPlayer("Emil Forsberg"); // 63 addPlayer("Mario Mandžukić"); // 64 addPlayer("Sergej Milinković-Savić"); // 65 addPlayer("Shinji Kagawa"); // 66 addPlayer("Granit Xhaka"); // 67 addPlayer("Andreas Christensen"); // 68 addPlayer("Piotr Zieliński"); // 69 addPlayer("Fyodor Smolov"); // 70 addPlayer("Xherdan Shaqiri"); // 71 addPlayer("Marcus Rashford"); // 72 addPlayer("Javier Hernández"); // 73 addPlayer("Hirving Lozano"); // 74 addPlayer("Hakim Ziyech"); // 75 addPlayer("Victor Moses"); // 76 addPlayer("Jefferson Farfán"); // 77 addPlayer("Mohamed Elneny"); // 78 addPlayer("Marcus Berg"); // 79 addPlayer("Guillermo Ochoa"); // 80 addPlayer("Igor Akinfeev"); // 81 addPlayer("Sardar Azmoun"); // 82 addPlayer("Christian Cueva"); // 83 addPlayer("Wahbi Khazri"); // 84 addPlayer("Keisuke Honda"); // 85 addPlayer("Tim Cahill"); // 86 addPlayer("John Obi Mikel"); // 87 addPlayer("Ki Sung-yueng"); // 88 addPlayer("Bryan Ruiz"); // 89 addPlayer("Maya Yoshida"); // 90 addPlayer("Nawaf Al Abed"); // 91 addPlayer("Lee Chung-yong"); // 92 addPlayer("Gabriel Gómez"); // 93 addPlayer("Naïm Sliti"); // 94 addPlayer("Reza Ghoochannejhad"); // 95 addPlayer("Mile Jedinak"); // 96 addPlayer("Mohammad Al-Sahlawi"); // 97 addPlayer("Aron Gunnarsson"); // 98 addPlayer("Blas Pérez"); // 99 addPlayer("Dani Alves"); // 100 addPlayer("Zlatan Ibrahimović"); // 101 } /// @dev Fires an event, proving that we said a player corresponds to a given ID. /// @param _name The name of the player we are adding. function addPlayer(string _name) public onlyOwner { require(playerCount < 255, "You've already added the maximum amount of players."); emit PlayerAdded(playerCount, _name); playerCount++; } } /// @title The contract that manages checklist items, sets, and rarity tiers. /// @author The CryptoStrikers Team contract StrikersChecklist is StrikersPlayerList { // High level overview of everything going on in this contract: // // ChecklistItem is the parent class to Card and has 3 properties: // - uint8 checklistId (000 to 255) // - uint8 playerId (see StrikersPlayerList.sol) // - RarityTier tier (more info below) // // Two things to note: the checklistId is not explicitly stored // on the checklistItem struct, and it's composed of two parts. // (For the following, assume it is left padded with zeros to reach // three digits, such that checklistId 0 becomes 000) // - the first digit represents the setId // * 0 = Originals Set // * 1 = Iconics Set // * 2 = Unreleased Set // - the last two digits represent its index in the appropriate set arary // // For example, checklist ID 100 would represent fhe first checklist item // in the iconicChecklistItems array (first digit = 1 = Iconics Set, last two // digits = 00 = first index of array) // // Because checklistId is represented as a uint8 throughout the app, the highest // value it can take is 255, which means we can't add more than 56 items to our // Unreleased Set's unreleasedChecklistItems array (setId 2). Also, once we've initialized // this contract, it's impossible for us to add more checklist items to the Originals // and Iconics set -- what you see here is what you get. // // Simple enough right? /// @dev We initialize this contract with so much data that we have /// to stage it in 4 different steps, ~33 checklist items at a time. enum DeployStep { WaitingForStepOne, WaitingForStepTwo, WaitingForStepThree, WaitingForStepFour, DoneInitialDeploy } /// @dev Enum containing all our rarity tiers, just because /// it's cleaner dealing with these values than with uint8s. enum RarityTier { IconicReferral, IconicInsert, Diamond, Gold, Silver, Bronze } /// @dev A lookup table indicating how limited the cards /// in each tier are. If this value is 0, it means /// that cards of this rarity tier are unlimited, /// which is only the case for the 8 Iconics cards /// we give away as part of our referral program. uint16[] public tierLimits = [ 0, // Iconic - Referral Bonus (uncapped) 100, // Iconic Inserts ("Card of the Day") 1000, // Diamond 1664, // Gold 3328, // Silver 4352 // Bronze ]; /// @dev ChecklistItem is essentially the parent class to Card. /// It represents a given superclass of cards (eg Originals Messi), /// and then each Card is an instance of this ChecklistItem, with /// its own serial number, mint date, etc. struct ChecklistItem { uint8 playerId; RarityTier tier; } /// @dev The deploy step we're at. Defaults to WaitingForStepOne. DeployStep public deployStep; /// @dev Array containing all the Originals checklist items (000 - 099) ChecklistItem[] public originalChecklistItems; /// @dev Array containing all the Iconics checklist items (100 - 131) ChecklistItem[] public iconicChecklistItems; /// @dev Array containing all the unreleased checklist items (200 - 255 max) ChecklistItem[] public unreleasedChecklistItems; /// @dev Internal function to add a checklist item to the Originals set. /// @param _playerId The player represented by this checklist item. (see StrikersPlayerList.sol) /// @param _tier This checklist item's rarity tier. (see Rarity Tier enum and corresponding tierLimits) function _addOriginalChecklistItem(uint8 _playerId, RarityTier _tier) internal { originalChecklistItems.push(ChecklistItem({ playerId: _playerId, tier: _tier })); } /// @dev Internal function to add a checklist item to the Iconics set. /// @param _playerId The player represented by this checklist item. (see StrikersPlayerList.sol) /// @param _tier This checklist item's rarity tier. (see Rarity Tier enum and corresponding tierLimits) function _addIconicChecklistItem(uint8 _playerId, RarityTier _tier) internal { iconicChecklistItems.push(ChecklistItem({ playerId: _playerId, tier: _tier })); } /// @dev External function to add a checklist item to our mystery set. /// Must have completed initial deploy, and can't add more than 56 items (because checklistId is a uint8). /// @param _playerId The player represented by this checklist item. (see StrikersPlayerList.sol) /// @param _tier This checklist item's rarity tier. (see Rarity Tier enum and corresponding tierLimits) function addUnreleasedChecklistItem(uint8 _playerId, RarityTier _tier) external onlyOwner { require(deployStep == DeployStep.DoneInitialDeploy, "Finish deploying the Originals and Iconics sets first."); require(unreleasedCount() < 56, "You can't add any more checklist items."); require(_playerId < playerCount, "This player doesn't exist in our player list."); unreleasedChecklistItems.push(ChecklistItem({ playerId: _playerId, tier: _tier })); } /// @dev Returns how many Original checklist items we've added. function originalsCount() external view returns (uint256) { return originalChecklistItems.length; } /// @dev Returns how many Iconic checklist items we've added. function iconicsCount() public view returns (uint256) { return iconicChecklistItems.length; } /// @dev Returns how many Unreleased checklist items we've added. function unreleasedCount() public view returns (uint256) { return unreleasedChecklistItems.length; } // In the next four functions, we initialize this contract with our // 132 initial checklist items (100 Originals, 32 Iconics). Because // of how much data we need to store, it has to be broken up into // four different function calls, which need to be called in sequence. // The ordering of the checklist items we add determines their // checklist ID, which is left-padded in our frontend to be a // 3-digit identifier where the first digit is the setId and the last // 2 digits represents the checklist items index in the appropriate ___ChecklistItems array. // For example, Originals Messi is the first item for set ID 0, and this // is displayed as #000 throughout the app. Our Card struct declare its // checklistId property as uint8, so we have // to be mindful that we can only have 256 total checklist items. /// @dev Deploys Originals #000 through #032. function deployStepOne() external onlyOwner { require(deployStep == DeployStep.WaitingForStepOne, "You're not following the steps in order..."); /* ORIGINALS - DIAMOND */ _addOriginalChecklistItem(0, RarityTier.Diamond); // 000 Messi _addOriginalChecklistItem(1, RarityTier.Diamond); // 001 Ronaldo _addOriginalChecklistItem(2, RarityTier.Diamond); // 002 Neymar _addOriginalChecklistItem(3, RarityTier.Diamond); // 003 Salah /* ORIGINALS - GOLD */ _addOriginalChecklistItem(4, RarityTier.Gold); // 004 Lewandowski _addOriginalChecklistItem(5, RarityTier.Gold); // 005 De Bruyne _addOriginalChecklistItem(6, RarityTier.Gold); // 006 Modrić _addOriginalChecklistItem(7, RarityTier.Gold); // 007 Hazard _addOriginalChecklistItem(8, RarityTier.Gold); // 008 Ramos _addOriginalChecklistItem(9, RarityTier.Gold); // 009 Kroos _addOriginalChecklistItem(10, RarityTier.Gold); // 010 Suárez _addOriginalChecklistItem(11, RarityTier.Gold); // 011 Kane _addOriginalChecklistItem(12, RarityTier.Gold); // 012 Agüero _addOriginalChecklistItem(13, RarityTier.Gold); // 013 Mbappé _addOriginalChecklistItem(14, RarityTier.Gold); // 014 Higuaín _addOriginalChecklistItem(15, RarityTier.Gold); // 015 de Gea _addOriginalChecklistItem(16, RarityTier.Gold); // 016 Griezmann _addOriginalChecklistItem(17, RarityTier.Gold); // 017 Kanté _addOriginalChecklistItem(18, RarityTier.Gold); // 018 Cavani _addOriginalChecklistItem(19, RarityTier.Gold); // 019 Pogba /* ORIGINALS - SILVER (020 to 032) */ _addOriginalChecklistItem(20, RarityTier.Silver); // 020 Isco _addOriginalChecklistItem(21, RarityTier.Silver); // 021 Marcelo _addOriginalChecklistItem(22, RarityTier.Silver); // 022 Neuer _addOriginalChecklistItem(23, RarityTier.Silver); // 023 Mertens _addOriginalChecklistItem(24, RarityTier.Silver); // 024 James _addOriginalChecklistItem(25, RarityTier.Silver); // 025 Dybala _addOriginalChecklistItem(26, RarityTier.Silver); // 026 Eriksen _addOriginalChecklistItem(27, RarityTier.Silver); // 027 David Silva _addOriginalChecklistItem(28, RarityTier.Silver); // 028 Gabriel Jesus _addOriginalChecklistItem(29, RarityTier.Silver); // 029 Thiago _addOriginalChecklistItem(30, RarityTier.Silver); // 030 Courtois _addOriginalChecklistItem(31, RarityTier.Silver); // 031 Coutinho _addOriginalChecklistItem(32, RarityTier.Silver); // 032 Iniesta // Move to the next deploy step. deployStep = DeployStep.WaitingForStepTwo; } /// @dev Deploys Originals #033 through #065. function deployStepTwo() external onlyOwner { require(deployStep == DeployStep.WaitingForStepTwo, "You're not following the steps in order..."); /* ORIGINALS - SILVER (033 to 049) */ _addOriginalChecklistItem(33, RarityTier.Silver); // 033 Casemiro _addOriginalChecklistItem(34, RarityTier.Silver); // 034 Lukaku _addOriginalChecklistItem(35, RarityTier.Silver); // 035 Piqué _addOriginalChecklistItem(36, RarityTier.Silver); // 036 Hummels _addOriginalChecklistItem(37, RarityTier.Silver); // 037 Godín _addOriginalChecklistItem(38, RarityTier.Silver); // 038 Özil _addOriginalChecklistItem(39, RarityTier.Silver); // 039 Son _addOriginalChecklistItem(40, RarityTier.Silver); // 040 Sterling _addOriginalChecklistItem(41, RarityTier.Silver); // 041 Lloris _addOriginalChecklistItem(42, RarityTier.Silver); // 042 Falcao _addOriginalChecklistItem(43, RarityTier.Silver); // 043 Rakitić _addOriginalChecklistItem(44, RarityTier.Silver); // 044 Sané _addOriginalChecklistItem(45, RarityTier.Silver); // 045 Firmino _addOriginalChecklistItem(46, RarityTier.Silver); // 046 Mané _addOriginalChecklistItem(47, RarityTier.Silver); // 047 Müller _addOriginalChecklistItem(48, RarityTier.Silver); // 048 Alli _addOriginalChecklistItem(49, RarityTier.Silver); // 049 Navas /* ORIGINALS - BRONZE (050 to 065) */ _addOriginalChecklistItem(50, RarityTier.Bronze); // 050 Thiago Silva _addOriginalChecklistItem(51, RarityTier.Bronze); // 051 Varane _addOriginalChecklistItem(52, RarityTier.Bronze); // 052 Di María _addOriginalChecklistItem(53, RarityTier.Bronze); // 053 Alba _addOriginalChecklistItem(54, RarityTier.Bronze); // 054 Benatia _addOriginalChecklistItem(55, RarityTier.Bronze); // 055 Werner _addOriginalChecklistItem(56, RarityTier.Bronze); // 056 Sigurðsson _addOriginalChecklistItem(57, RarityTier.Bronze); // 057 Matić _addOriginalChecklistItem(58, RarityTier.Bronze); // 058 Koulibaly _addOriginalChecklistItem(59, RarityTier.Bronze); // 059 Bernardo Silva _addOriginalChecklistItem(60, RarityTier.Bronze); // 060 Kompany _addOriginalChecklistItem(61, RarityTier.Bronze); // 061 Moutinho _addOriginalChecklistItem(62, RarityTier.Bronze); // 062 Alderweireld _addOriginalChecklistItem(63, RarityTier.Bronze); // 063 Forsberg _addOriginalChecklistItem(64, RarityTier.Bronze); // 064 Mandžukić _addOriginalChecklistItem(65, RarityTier.Bronze); // 065 Milinković-Savić // Move to the next deploy step. deployStep = DeployStep.WaitingForStepThree; } /// @dev Deploys Originals #066 through #099. function deployStepThree() external onlyOwner { require(deployStep == DeployStep.WaitingForStepThree, "You're not following the steps in order..."); /* ORIGINALS - BRONZE (066 to 099) */ _addOriginalChecklistItem(66, RarityTier.Bronze); // 066 Kagawa _addOriginalChecklistItem(67, RarityTier.Bronze); // 067 Xhaka _addOriginalChecklistItem(68, RarityTier.Bronze); // 068 Christensen _addOriginalChecklistItem(69, RarityTier.Bronze); // 069 Zieliński _addOriginalChecklistItem(70, RarityTier.Bronze); // 070 Smolov _addOriginalChecklistItem(71, RarityTier.Bronze); // 071 Shaqiri _addOriginalChecklistItem(72, RarityTier.Bronze); // 072 Rashford _addOriginalChecklistItem(73, RarityTier.Bronze); // 073 Hernández _addOriginalChecklistItem(74, RarityTier.Bronze); // 074 Lozano _addOriginalChecklistItem(75, RarityTier.Bronze); // 075 Ziyech _addOriginalChecklistItem(76, RarityTier.Bronze); // 076 Moses _addOriginalChecklistItem(77, RarityTier.Bronze); // 077 Farfán _addOriginalChecklistItem(78, RarityTier.Bronze); // 078 Elneny _addOriginalChecklistItem(79, RarityTier.Bronze); // 079 Berg _addOriginalChecklistItem(80, RarityTier.Bronze); // 080 Ochoa _addOriginalChecklistItem(81, RarityTier.Bronze); // 081 Akinfeev _addOriginalChecklistItem(82, RarityTier.Bronze); // 082 Azmoun _addOriginalChecklistItem(83, RarityTier.Bronze); // 083 Cueva _addOriginalChecklistItem(84, RarityTier.Bronze); // 084 Khazri _addOriginalChecklistItem(85, RarityTier.Bronze); // 085 Honda _addOriginalChecklistItem(86, RarityTier.Bronze); // 086 Cahill _addOriginalChecklistItem(87, RarityTier.Bronze); // 087 Mikel _addOriginalChecklistItem(88, RarityTier.Bronze); // 088 Sung-yueng _addOriginalChecklistItem(89, RarityTier.Bronze); // 089 Ruiz _addOriginalChecklistItem(90, RarityTier.Bronze); // 090 Yoshida _addOriginalChecklistItem(91, RarityTier.Bronze); // 091 Al Abed _addOriginalChecklistItem(92, RarityTier.Bronze); // 092 Chung-yong _addOriginalChecklistItem(93, RarityTier.Bronze); // 093 Gómez _addOriginalChecklistItem(94, RarityTier.Bronze); // 094 Sliti _addOriginalChecklistItem(95, RarityTier.Bronze); // 095 Ghoochannejhad _addOriginalChecklistItem(96, RarityTier.Bronze); // 096 Jedinak _addOriginalChecklistItem(97, RarityTier.Bronze); // 097 Al-Sahlawi _addOriginalChecklistItem(98, RarityTier.Bronze); // 098 Gunnarsson _addOriginalChecklistItem(99, RarityTier.Bronze); // 099 Pérez // Move to the next deploy step. deployStep = DeployStep.WaitingForStepFour; } /// @dev Deploys all Iconics and marks the deploy as complete! function deployStepFour() external onlyOwner { require(deployStep == DeployStep.WaitingForStepFour, "You're not following the steps in order..."); /* ICONICS */ _addIconicChecklistItem(0, RarityTier.IconicInsert); // 100 Messi _addIconicChecklistItem(1, RarityTier.IconicInsert); // 101 Ronaldo _addIconicChecklistItem(2, RarityTier.IconicInsert); // 102 Neymar _addIconicChecklistItem(3, RarityTier.IconicInsert); // 103 Salah _addIconicChecklistItem(4, RarityTier.IconicInsert); // 104 Lewandowski _addIconicChecklistItem(5, RarityTier.IconicInsert); // 105 De Bruyne _addIconicChecklistItem(6, RarityTier.IconicInsert); // 106 Modrić _addIconicChecklistItem(7, RarityTier.IconicInsert); // 107 Hazard _addIconicChecklistItem(8, RarityTier.IconicInsert); // 108 Ramos _addIconicChecklistItem(9, RarityTier.IconicInsert); // 109 Kroos _addIconicChecklistItem(10, RarityTier.IconicInsert); // 110 Suárez _addIconicChecklistItem(11, RarityTier.IconicInsert); // 111 Kane _addIconicChecklistItem(12, RarityTier.IconicInsert); // 112 Agüero _addIconicChecklistItem(15, RarityTier.IconicInsert); // 113 de Gea _addIconicChecklistItem(16, RarityTier.IconicInsert); // 114 Griezmann _addIconicChecklistItem(17, RarityTier.IconicReferral); // 115 Kanté _addIconicChecklistItem(18, RarityTier.IconicReferral); // 116 Cavani _addIconicChecklistItem(19, RarityTier.IconicInsert); // 117 Pogba _addIconicChecklistItem(21, RarityTier.IconicInsert); // 118 Marcelo _addIconicChecklistItem(24, RarityTier.IconicInsert); // 119 James _addIconicChecklistItem(26, RarityTier.IconicInsert); // 120 Eriksen _addIconicChecklistItem(29, RarityTier.IconicReferral); // 121 Thiago _addIconicChecklistItem(36, RarityTier.IconicReferral); // 122 Hummels _addIconicChecklistItem(38, RarityTier.IconicReferral); // 123 Özil _addIconicChecklistItem(39, RarityTier.IconicInsert); // 124 Son _addIconicChecklistItem(46, RarityTier.IconicInsert); // 125 Mané _addIconicChecklistItem(48, RarityTier.IconicInsert); // 126 Alli _addIconicChecklistItem(49, RarityTier.IconicReferral); // 127 Navas _addIconicChecklistItem(73, RarityTier.IconicInsert); // 128 Hernández _addIconicChecklistItem(85, RarityTier.IconicInsert); // 129 Honda _addIconicChecklistItem(100, RarityTier.IconicReferral); // 130 Alves _addIconicChecklistItem(101, RarityTier.IconicReferral); // 131 Zlatan // Mark the initial deploy as complete. deployStep = DeployStep.DoneInitialDeploy; } /// @dev Returns the mint limit for a given checklist item, based on its tier. /// @param _checklistId Which checklist item we need to get the limit for. /// @return How much of this checklist item we are allowed to mint. function limitForChecklistId(uint8 _checklistId) external view returns (uint16) { RarityTier rarityTier; uint8 index; if (_checklistId < 100) { // Originals = #000 to #099 rarityTier = originalChecklistItems[_checklistId].tier; } else if (_checklistId < 200) { // Iconics = #100 to #131 index = _checklistId - 100; require(index < iconicsCount(), "This Iconics checklist item doesn't exist."); rarityTier = iconicChecklistItems[index].tier; } else { // Unreleased = #200 to max #255 index = _checklistId - 200; require(index < unreleasedCount(), "This Unreleased checklist item doesn't exist."); rarityTier = unreleasedChecklistItems[index].tier; } return tierLimits[uint8(rarityTier)]; } } /// @title Base contract for CryptoStrikers. Defines what a card is and how to mint one. /// @author The CryptoStrikers Team contract StrikersBase is ERC721Token("CryptoStrikers", "STRK") { /// @dev Emit this event whenever we mint a new card (see _mintCard below) event CardMinted(uint256 cardId); /// @dev The struct representing the game's main object, a sports trading card. struct Card { // The timestamp at which this card was minted. // With uint32 we are good until 2106, by which point we will have not minted // a card in like, 88 years. uint32 mintTime; // The checklist item represented by this card. See StrikersChecklist.sol for more info. uint8 checklistId; // Cards for a given player have a serial number, which gets // incremented in sequence. For example, if we mint 1000 of a card, // the third one to be minted has serialNumber = 3 (out of 1000). uint16 serialNumber; } /*** STORAGE ***/ /// @dev All the cards that have been minted, indexed by cardId. Card[] public cards; /// @dev Keeps track of how many cards we have minted for a given checklist item /// to make sure we don't go over the limit for it. /// NB: uint16 has a capacity of 65,535, but we are not minting more than /// 4,352 of any given checklist item. mapping (uint8 => uint16) public mintedCountForChecklistId; /// @dev A reference to our checklist contract, which contains all the minting limits. StrikersChecklist public strikersChecklist; /*** FUNCTIONS ***/ /// @dev For a given owner, returns two arrays. The first contains the IDs of every card owned /// by this address. The second returns the corresponding checklist ID for each of these cards. /// There are a few places we need this info in the web app and short of being able to return an /// actual array of Cards, this is the best solution we could come up with... function cardAndChecklistIdsForOwner(address _owner) external view returns (uint256[], uint8[]) { uint256[] memory cardIds = ownedTokens[_owner]; uint256 cardCount = cardIds.length; uint8[] memory checklistIds = new uint8[](cardCount); for (uint256 i = 0; i < cardCount; i++) { uint256 cardId = cardIds[i]; checklistIds[i] = cards[cardId].checklistId; } return (cardIds, checklistIds); } /// @dev An internal method that creates a new card and stores it. /// Emits both a CardMinted and a Transfer event. /// @param _checklistId The ID of the checklistItem represented by the card (see Checklist.sol) /// @param _owner The card's first owner! function _mintCard( uint8 _checklistId, address _owner ) internal returns (uint256) { uint16 mintLimit = strikersChecklist.limitForChecklistId(_checklistId); require(mintLimit == 0 || mintedCountForChecklistId[_checklistId] < mintLimit, "Can't mint any more of this card!"); uint16 serialNumber = ++mintedCountForChecklistId[_checklistId]; Card memory newCard = Card({ mintTime: uint32(now), checklistId: _checklistId, serialNumber: serialNumber }); uint256 newCardId = cards.push(newCard) - 1; emit CardMinted(newCardId); _mint(_owner, newCardId); return newCardId; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /// @title The contract that exposes minting functions to the outside world and limits who can call them. /// @author The CryptoStrikers Team contract StrikersMinting is StrikersBase, Pausable { /// @dev Emit this when we decide to no longer mint a given checklist ID. event PulledFromCirculation(uint8 checklistId); /// @dev If the value for a checklistId is true, we can no longer mint it. mapping (uint8 => bool) public outOfCirculation; /// @dev The address of the contract that manages the pack sale. address public packSaleAddress; /// @dev Only the owner can update the address of the pack sale contract. /// @param _address The address of the new StrikersPackSale contract. function setPackSaleAddress(address _address) external onlyOwner { packSaleAddress = _address; } /// @dev Allows the contract at packSaleAddress to mint cards. /// @param _checklistId The checklist item represented by this new card. /// @param _owner The card's first owner! /// @return The new card's ID. function mintPackSaleCard(uint8 _checklistId, address _owner) external returns (uint256) { require(msg.sender == packSaleAddress, "Only the pack sale contract can mint here."); require(!outOfCirculation[_checklistId], "Can't mint any more of this checklist item..."); return _mintCard(_checklistId, _owner); } /// @dev Allows the owner to mint cards from our Unreleased Set. /// @param _checklistId The checklist item represented by this new card. Must be >= 200. /// @param _owner The card's first owner! function mintUnreleasedCard(uint8 _checklistId, address _owner) external onlyOwner { require(_checklistId >= 200, "You can only use this to mint unreleased cards."); require(!outOfCirculation[_checklistId], "Can't mint any more of this checklist item..."); _mintCard(_checklistId, _owner); } /// @dev Allows the owner or the pack sale contract to prevent an Iconic or Unreleased card from ever being minted again. /// @param _checklistId The Iconic or Unreleased card we want to remove from circulation. function pullFromCirculation(uint8 _checklistId) external { bool ownerOrPackSale = (msg.sender == owner) || (msg.sender == packSaleAddress); require(ownerOrPackSale, "Only the owner or pack sale can take checklist items out of circulation."); require(_checklistId >= 100, "This function is reserved for Iconics and Unreleased sets."); outOfCirculation[_checklistId] = true; emit PulledFromCirculation(_checklistId); } } /// @title StrikersTrading - Allows users to trustlessly trade cards. /// @author The CryptoStrikers Team contract StrikersTrading is StrikersMinting { /// @dev Emitting this allows us to look up if a trade has been /// successfully filled, by who, and which cards were involved. event TradeFilled( bytes32 indexed tradeHash, address indexed maker, uint256 makerCardId, address indexed taker, uint256 takerCardId ); /// @dev Emitting this allows us to look up if a trade has been cancelled. event TradeCancelled(bytes32 indexed tradeHash, address indexed maker); /// @dev All the possible states for a trade. enum TradeState { Valid, Filled, Cancelled } /// @dev Mapping of tradeHash => TradeState. Defaults to Valid. mapping (bytes32 => TradeState) public tradeStates; /// @dev A taker (someone who has received a signed trade hash) /// submits a cardId to this function and, if it satisfies /// the given criteria, the trade is executed. /// @param _maker Address of the maker (i.e. trade creator). /// @param _makerCardId ID of the card the maker has agreed to give up. /// @param _taker The counterparty the maker wishes to trade with (if it's address(0), anybody can fill the trade!) /// @param _takerCardOrChecklistId If taker is the 0-address, then this is a checklist ID (e.g. "any Originals John Smith"). /// If not, then it's a card ID (e.g. "Originals John Smith #8/100"). /// @param _salt A uint256 timestamp to differentiate trades that have otherwise identical params (prevents replay attacks). /// @param _submittedCardId The card the taker is using to fill the trade. Must satisfy either the card or checklist ID /// specified in _takerCardOrChecklistId. /// @param _v ECDSA signature parameter v from the tradeHash signed by the maker. /// @param _r ECDSA signature parameters r from the tradeHash signed by the maker. /// @param _s ECDSA signature parameters s from the tradeHash signed by the maker. function fillTrade( address _maker, uint256 _makerCardId, address _taker, uint256 _takerCardOrChecklistId, uint256 _salt, uint256 _submittedCardId, uint8 _v, bytes32 _r, bytes32 _s) external whenNotPaused { require(_maker != msg.sender, "You can't fill your own trade."); require(_taker == address(0) || _taker == msg.sender, "You are not authorized to fill this trade."); if (_taker == address(0)) { // This trade is open to the public so we are requesting a checklistItem, rather than a specific card. require(cards[_submittedCardId].checklistId == _takerCardOrChecklistId, "The card you submitted is not valid for this trade."); } else { // We are trading directly with another user and are requesting a specific card. require(_submittedCardId == _takerCardOrChecklistId, "The card you submitted is not valid for this trade."); } bytes32 tradeHash = getTradeHash( _maker, _makerCardId, _taker, _takerCardOrChecklistId, _salt ); require(tradeStates[tradeHash] == TradeState.Valid, "This trade is no longer valid."); require(isValidSignature(_maker, tradeHash, _v, _r, _s), "Invalid signature."); tradeStates[tradeHash] = TradeState.Filled; // For better UX, we assume that by signing the trade, the maker has given // implicit approval for this token to be transferred. This saves us from an // extra approval transaction... tokenApprovals[_makerCardId] = msg.sender; safeTransferFrom(_maker, msg.sender, _makerCardId); safeTransferFrom(msg.sender, _maker, _submittedCardId); emit TradeFilled(tradeHash, _maker, _makerCardId, msg.sender, _submittedCardId); } /// @dev Allows the maker to cancel a trade that hasn't been filled yet. /// @param _maker Address of the maker (i.e. trade creator). /// @param _makerCardId ID of the card the maker has agreed to give up. /// @param _taker The counterparty the maker wishes to trade with (if it's address(0), anybody can fill the trade!) /// @param _takerCardOrChecklistId If taker is the 0-address, then this is a checklist ID (e.g. "any Lionel Messi"). /// If not, then it's a card ID (e.g. "Lionel Messi #8/100"). /// @param _salt A uint256 timestamp to differentiate trades that have otherwise identical params (prevents replay attacks). function cancelTrade( address _maker, uint256 _makerCardId, address _taker, uint256 _takerCardOrChecklistId, uint256 _salt) external { require(_maker == msg.sender, "Only the trade creator can cancel this trade."); bytes32 tradeHash = getTradeHash( _maker, _makerCardId, _taker, _takerCardOrChecklistId, _salt ); require(tradeStates[tradeHash] == TradeState.Valid, "This trade has already been cancelled or filled."); tradeStates[tradeHash] = TradeState.Cancelled; emit TradeCancelled(tradeHash, _maker); } /// @dev Calculates Keccak-256 hash of a trade with specified parameters. /// @param _maker Address of the maker (i.e. trade creator). /// @param _makerCardId ID of the card the maker has agreed to give up. /// @param _taker The counterparty the maker wishes to trade with (if it's address(0), anybody can fill the trade!) /// @param _takerCardOrChecklistId If taker is the 0-address, then this is a checklist ID (e.g. "any Lionel Messi"). /// If not, then it's a card ID (e.g. "Lionel Messi #8/100"). /// @param _salt A uint256 timestamp to differentiate trades that have otherwise identical params (prevents replay attacks). /// @return Keccak-256 hash of trade. function getTradeHash( address _maker, uint256 _makerCardId, address _taker, uint256 _takerCardOrChecklistId, uint256 _salt) public view returns (bytes32) { // Hashing the contract address prevents a trade from being replayed on any new trade contract we deploy. bytes memory packed = abi.encodePacked(this, _maker, _makerCardId, _taker, _takerCardOrChecklistId, _salt); return keccak256(packed); } /// @dev Verifies that a signed trade is valid. /// @param _signer Address of signer. /// @param _tradeHash Signed Keccak-256 hash. /// @param _v ECDSA signature parameter v. /// @param _r ECDSA signature parameters r. /// @param _s ECDSA signature parameters s. /// @return Validity of signature. function isValidSignature( address _signer, bytes32 _tradeHash, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (bool) { bytes memory packed = abi.encodePacked("\x19Ethereum Signed Message:\n32", _tradeHash); return _signer == ecrecover(keccak256(packed), _v, _r, _s); } } /// @title The main, ERC721-compliant CryptoStrikers contract. /// @author The CryptoStrikers Team contract StrikersCore is StrikersTrading { /// @dev An external metadata contract that the owner can upgrade. StrikersMetadata public strikersMetadata; /// @dev We initialize the CryptoStrikers game with an immutable checklist that oversees card rarity. constructor(address _checklistAddress) public { strikersChecklist = StrikersChecklist(_checklistAddress); } /// @dev Allows the contract owner to update the metadata contract. function setMetadataAddress(address _contractAddress) external onlyOwner { strikersMetadata = StrikersMetadata(_contractAddress); } /// @dev If we've set an external metadata contract, use that. function tokenURI(uint256 _tokenId) public view returns (string) { if (strikersMetadata == address(0)) { return super.tokenURI(_tokenId); } require(exists(_tokenId), "Card does not exist."); return strikersMetadata.tokenURI(_tokenId); } }
@dev A taker (someone who has received a signed trade hash) submits a cardId to this function and, if it satisfies the given criteria, the trade is executed. @param _maker Address of the maker (i.e. trade creator). @param _makerCardId ID of the card the maker has agreed to give up. @param _taker The counterparty the maker wishes to trade with (if it's address(0), anybody can fill the trade!) @param _takerCardOrChecklistId If taker is the 0-address, then this is a checklist ID (e.g. "any Originals John Smith"). If not, then it's a card ID (e.g. "Originals John Smith #8/100"). @param _salt A uint256 timestamp to differentiate trades that have otherwise identical params (prevents replay attacks). @param _submittedCardId The card the taker is using to fill the trade. Must satisfy either the card or checklist ID specified in _takerCardOrChecklistId. @param _v ECDSA signature parameter v from the tradeHash signed by the maker. @param _r ECDSA signature parameters r from the tradeHash signed by the maker. @param _s ECDSA signature parameters s from the tradeHash signed by the maker. This trade is open to the public so we are requesting a checklistItem, rather than a specific card. We are trading directly with another user and are requesting a specific card.
function fillTrade( address _maker, uint256 _makerCardId, address _taker, uint256 _takerCardOrChecklistId, uint256 _salt, uint256 _submittedCardId, uint8 _v, bytes32 _r, bytes32 _s) external whenNotPaused { require(_maker != msg.sender, "You can't fill your own trade."); require(_taker == address(0) || _taker == msg.sender, "You are not authorized to fill this trade."); if (_taker == address(0)) { require(cards[_submittedCardId].checklistId == _takerCardOrChecklistId, "The card you submitted is not valid for this trade."); require(_submittedCardId == _takerCardOrChecklistId, "The card you submitted is not valid for this trade."); } bytes32 tradeHash = getTradeHash( _maker, _makerCardId, _taker, _takerCardOrChecklistId, _salt ); require(tradeStates[tradeHash] == TradeState.Valid, "This trade is no longer valid."); require(isValidSignature(_maker, tradeHash, _v, _r, _s), "Invalid signature."); tradeStates[tradeHash] = TradeState.Filled; safeTransferFrom(_maker, msg.sender, _makerCardId); safeTransferFrom(msg.sender, _maker, _submittedCardId); emit TradeFilled(tradeHash, _maker, _makerCardId, msg.sender, _submittedCardId); }
5,349,960
[ 1, 37, 268, 6388, 261, 19068, 476, 10354, 711, 5079, 279, 6726, 18542, 1651, 13, 282, 720, 22679, 279, 5270, 548, 358, 333, 445, 471, 16, 309, 518, 17917, 282, 326, 864, 3582, 16, 326, 18542, 353, 7120, 18, 225, 389, 29261, 5267, 434, 326, 312, 6388, 261, 77, 18, 73, 18, 18542, 11784, 2934, 225, 389, 29261, 6415, 548, 1599, 434, 326, 5270, 326, 312, 6388, 711, 1737, 15656, 358, 8492, 731, 18, 225, 389, 88, 6388, 1021, 3895, 21214, 326, 312, 6388, 14302, 281, 358, 18542, 598, 261, 430, 518, 1807, 1758, 12, 20, 3631, 1281, 3432, 848, 3636, 326, 18542, 24949, 225, 389, 88, 6388, 6415, 1162, 1564, 1098, 548, 971, 268, 6388, 353, 326, 374, 17, 2867, 16, 1508, 333, 353, 279, 866, 1098, 1599, 261, 73, 18, 75, 18, 315, 2273, 18040, 1031, 804, 22223, 9425, 483, 20387, 27573, 971, 486, 16, 1508, 518, 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, 3636, 22583, 12, 203, 565, 1758, 389, 29261, 16, 203, 565, 2254, 5034, 389, 29261, 6415, 548, 16, 203, 565, 1758, 389, 88, 6388, 16, 203, 565, 2254, 5034, 389, 88, 6388, 6415, 1162, 1564, 1098, 548, 16, 203, 565, 2254, 5034, 389, 5759, 16, 203, 565, 2254, 5034, 389, 31575, 6415, 548, 16, 203, 565, 2254, 28, 389, 90, 16, 203, 565, 1731, 1578, 389, 86, 16, 203, 565, 1731, 1578, 389, 87, 13, 203, 565, 3903, 203, 565, 1347, 1248, 28590, 203, 225, 288, 203, 565, 2583, 24899, 29261, 480, 1234, 18, 15330, 16, 315, 6225, 848, 1404, 3636, 3433, 4953, 18542, 1199, 1769, 203, 565, 2583, 24899, 88, 6388, 422, 1758, 12, 20, 13, 747, 389, 88, 6388, 422, 1234, 18, 15330, 16, 315, 6225, 854, 486, 10799, 358, 3636, 333, 18542, 1199, 1769, 203, 203, 565, 309, 261, 67, 88, 6388, 422, 1758, 12, 20, 3719, 288, 203, 1377, 2583, 12, 3327, 87, 63, 67, 31575, 6415, 548, 8009, 1893, 1098, 548, 422, 389, 88, 6388, 6415, 1162, 1564, 1098, 548, 16, 315, 1986, 5270, 1846, 9638, 353, 486, 923, 364, 333, 18542, 1199, 1769, 203, 1377, 2583, 24899, 31575, 6415, 548, 422, 389, 88, 6388, 6415, 1162, 1564, 1098, 548, 16, 315, 1986, 5270, 1846, 9638, 353, 486, 923, 364, 333, 18542, 1199, 1769, 203, 565, 289, 203, 203, 565, 1731, 1578, 18542, 2310, 273, 336, 22583, 2310, 12, 203, 1377, 389, 29261, 16, 203, 1377, 389, 29261, 6415, 548, 16, 203, 1377, 389, 88, 6388, 16, 2 ]
./full_match/4/0x381ec53f4e74DA2E090d042368060376463592AE/sources/contracts/nftFolder.sol
USING DIRECTIVES DATA STRUCTURES
contract NftFolder is AccessControl, ERC721Burnable { using Counters for Counters.Counter; using SafeMath for uint; pragma solidity >=0.4.22 <0.9.0; struct TokenData { uint256 nftFileHash; address certificationChip; uint8 retributionRate; string name; string description; } enum FolderActivation { } address[2] private _parents; uint8 public constant _folderType = 13; uint8 public constant _customerId = 14; string public constant _version = "1.00"; uint256 private _maxToken; Counters.Counter private _nextToken; FolderActivation private _folderActivation; string private _logoURI; string private _dataURI; mapping(uint256 => TokenData) _tokenData; function parents() external view returns (address[2] memory) { return _parents; } function maxToken() external view returns (uint256) { return _maxToken; } function nextToken() external view returns (uint256) { return _nextToken.current(); } function folderActivation() external view returns (FolderActivation) { return _folderActivation; } function logoURI() external view returns (string memory) { return _logoURI; } function dataURI() external view returns (string memory) { return _dataURI; } function tokenData_nftFileHash(uint256 tokenId) external view returns (uint256) { return _tokenData[tokenId].nftFileHash; } function tokenData_certificationChip(uint256 tokenId) external view returns (address) { return _tokenData[tokenId].certificationChip; } function tokenData_retributionRate(uint256 tokenId) external view returns (uint8) { return _tokenData[tokenId].retributionRate; } function tokenData_name(uint256 tokenId) external view returns (string memory) { return _tokenData[tokenId].name; } function tokenData_description(uint256 tokenId) external view returns (string memory) { return _tokenData[tokenId].description; } string memory _name, string memory _symbol, address parent1, address parent2, uint256 max_token, string memory logo_URI, string memory base_URI) constructor( ERC721(_name, _symbol) { _parents[0] = parent1; _parents[1] = parent2; _setupRole(DEFAULT_ADMIN_ROLE, _parents[0]); _setupRole(DEFAULT_ADMIN_ROLE, _parents[1]); _maxToken = max_token; _folderActivation = FolderActivation.not_set; _logoURI = logo_URI; _dataURI = base_URI; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal folderActivated override(ERC721) { super._beforeTokenTransfer(from, to, tokenId); } modifier checkTokenCount() { require(_nextToken._value != _maxToken, "number of tokens above the prescribed maximum"); _; } modifier onlyParents() { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "only Parent accounts may call this function"); _; } modifier folderActivated() { require(_folderActivation == FolderActivation.active, "Folder is not active"); _; } function mint( address _to, address certificationChip, uint8 retributionRate, string memory name, string memory description) checkTokenCount folderActivated public { uint256 newTokenId = _nextToken.current(); _safeMint(_to, newTokenId); _tokenData[newTokenId].certificationChip = certificationChip; _tokenData[newTokenId].retributionRate = retributionRate; _tokenData[newTokenId].name = name; _tokenData[newTokenId].description = description; _nextToken.increment(); } function setFolderActivation(FolderActivation code) public onlyParents { require(_folderActivation == FolderActivation.not_set && code != FolderActivation.not_set, "folderActivation cannot be unset and cannot be modifier once set"); _folderActivation = code; } }
752,029
[ 1, 3378, 1360, 29100, 5354, 55, 8730, 7128, 9749, 4830, 55, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 16351, 423, 1222, 3899, 353, 24349, 16, 4232, 39, 27, 5340, 38, 321, 429, 288, 203, 203, 202, 9940, 9354, 87, 364, 9354, 87, 18, 4789, 31, 203, 202, 9940, 14060, 10477, 364, 2254, 31, 203, 203, 683, 9454, 18035, 560, 1545, 20, 18, 24, 18, 3787, 411, 20, 18, 29, 18, 20, 31, 203, 202, 1697, 3155, 751, 288, 203, 202, 202, 11890, 5034, 202, 82, 1222, 812, 2310, 31, 203, 202, 202, 2867, 202, 7593, 1480, 782, 625, 31, 203, 202, 202, 11890, 28, 202, 266, 4027, 4727, 31, 203, 202, 202, 1080, 225, 202, 529, 31, 203, 202, 202, 1080, 202, 3384, 31, 203, 202, 97, 203, 203, 202, 7924, 12623, 14857, 288, 203, 202, 97, 203, 203, 202, 2867, 63, 22, 65, 3238, 1082, 202, 67, 12606, 31, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 202, 11890, 28, 1071, 5381, 3196, 202, 67, 5609, 559, 273, 5958, 31, 203, 202, 11890, 28, 1071, 5381, 3196, 202, 67, 10061, 548, 273, 5045, 31, 203, 202, 1080, 1071, 5381, 3196, 202, 67, 1589, 273, 315, 21, 18, 713, 14432, 203, 202, 11890, 5034, 3238, 7734, 389, 1896, 1345, 31, 203, 202, 18037, 18, 4789, 3238, 202, 67, 4285, 1345, 31, 203, 202, 3899, 14857, 3238, 202, 67, 5609, 14857, 31, 203, 202, 1080, 3238, 9506, 202, 67, 19882, 3098, 31, 203, 202, 1080, 3238, 9506, 202, 67, 892, 3098, 31, 203, 202, 6770, 12, 11890, 5034, 516, 3155, 751, 13, 389, 2316, 751, 31, 203, 203, 2 ]
./full_match/80001/0x5226665a3E3c086A3840880713541F2AD9A8699a/sources/project_/contracts/proxy/authority/TREXImplementationAuthority.sol
* @dev See {ITREXImplementationAuthority-getTokenImplementation}./
function getTokenImplementation() external view override returns (address) { return _contracts[_versionToBytes(_currentVersion)].tokenImplementation; }
5,562,757
[ 1, 9704, 288, 1285, 862, 60, 13621, 10962, 17, 588, 1345, 13621, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 9162, 13621, 1435, 3903, 1476, 3849, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 16351, 87, 63, 67, 1589, 21033, 24899, 2972, 1444, 13, 8009, 2316, 13621, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Utilities for manipulating memory arrays * * Unlike storage arrays, memory arrays can't be resized to we use these * utility functions to generate copies. */ library ArrayLibUtils { /** * @dev Append value to copy of the array, increasing its length. * @param array of uint256 * @param val value * @return newArray */ function push(uint256[] memory array, uint256 val) internal pure returns (uint256[] memory) { uint256 arrayLength = array.length; uint256[] memory newArray = new uint256[](arrayLength + 1); for (uint256 i = 0; i < arrayLength; i++) { newArray[i] = array[i]; } newArray[arrayLength] = val; return newArray; } /** * @dev Delete last value from copy of the array, decreasing its length. * @param array of uint256 * @return newArray */ function pop(uint256[] memory array) internal pure returns (uint256[] memory) { uint256 arrayLength = array.length; uint256[] memory newArray = new uint256[](arrayLength - 1); for (uint256 i = 0; i < arrayLength - 1; i++) { newArray[i] = array[i]; } return newArray; } /** * @dev keccak256 hash the encoded array elements * @param array of uint256 * @return hash */ function hash(uint256[] memory array) internal pure returns (bytes32) { return keccak256(abi.encode(array)); } /** * @dev Sum the array elements * @param array of uint256 * @return sum */ function sum(uint256[] memory array) internal pure returns (uint256) { uint256 total; for (uint256 i = 0; i < array.length; i++) { total += array[i]; } return total; } /** * @dev Concatenate byte arrays * @param arrayOfArrays of bytes * @return concatenated * * This function is especially useful when looking to concatenate a * dynamic array of strings. */ function concat(bytes[] memory arrayOfArrays) internal pure returns (bytes memory) { uint256 arrayCount = arrayOfArrays.length; uint256 totalLength = 0; for (uint256 i = 0; i < arrayCount; i++) { totalLength += arrayOfArrays[i].length; } bytes memory newArray = new bytes(totalLength); uint256 k = 0; for (uint256 i = 0; i < arrayCount; i++) { for (uint256 j = 0; j < arrayOfArrays[i].length; j++) { newArray[k] = arrayOfArrays[i][j]; k++; } } return newArray; } /** * @dev Concatenate byte arrays * @param arrayOfArrays of uint256 * @return concatenated */ function concat(uint256[][] memory arrayOfArrays) internal pure returns (uint256[] memory) { uint256 arrayCount = arrayOfArrays.length; uint256 totalLength = 0; for (uint256 i = 0; i < arrayCount; i++) { totalLength += arrayOfArrays[i].length; } uint256[] memory newArray = new uint256[](totalLength); uint256 k = 0; for (uint256 i = 0; i < arrayCount; i++) { for (uint256 j = 0; j < arrayOfArrays[i].length; j++) { newArray[k] = arrayOfArrays[i][j]; k++; } } return newArray; } /** * @dev Return range array * @param from start index * @param to end index, exclusive * @return rangeArray * */ function range(uint256 from, uint256 to) internal pure returns (uint256[] memory rangeArray) { require(from < to, 'from >= to'); rangeArray = new uint256[](to - from); for (uint256 i = 0; i < rangeArray.length; i++) { rangeArray[i] = from + i; } } }
* @dev Utilities for manipulating memory arrays Unlike storage arrays, memory arrays can't be resized to we use these utility functions to generate copies./
library ArrayLibUtils { pragma solidity ^0.6.0; function push(uint256[] memory array, uint256 val) internal pure returns (uint256[] memory) { uint256 arrayLength = array.length; uint256[] memory newArray = new uint256[](arrayLength + 1); for (uint256 i = 0; i < arrayLength; i++) { newArray[i] = array[i]; } newArray[arrayLength] = val; return newArray; } function push(uint256[] memory array, uint256 val) internal pure returns (uint256[] memory) { uint256 arrayLength = array.length; uint256[] memory newArray = new uint256[](arrayLength + 1); for (uint256 i = 0; i < arrayLength; i++) { newArray[i] = array[i]; } newArray[arrayLength] = val; return newArray; } function pop(uint256[] memory array) internal pure returns (uint256[] memory) { uint256 arrayLength = array.length; uint256[] memory newArray = new uint256[](arrayLength - 1); for (uint256 i = 0; i < arrayLength - 1; i++) { newArray[i] = array[i]; } return newArray; } function pop(uint256[] memory array) internal pure returns (uint256[] memory) { uint256 arrayLength = array.length; uint256[] memory newArray = new uint256[](arrayLength - 1); for (uint256 i = 0; i < arrayLength - 1; i++) { newArray[i] = array[i]; } return newArray; } function hash(uint256[] memory array) internal pure returns (bytes32) { return keccak256(abi.encode(array)); } function sum(uint256[] memory array) internal pure returns (uint256) { uint256 total; for (uint256 i = 0; i < array.length; i++) { total += array[i]; } return total; } function sum(uint256[] memory array) internal pure returns (uint256) { uint256 total; for (uint256 i = 0; i < array.length; i++) { total += array[i]; } return total; } function concat(bytes[] memory arrayOfArrays) internal pure returns (bytes memory) { uint256 arrayCount = arrayOfArrays.length; uint256 totalLength = 0; for (uint256 i = 0; i < arrayCount; i++) { totalLength += arrayOfArrays[i].length; } bytes memory newArray = new bytes(totalLength); uint256 k = 0; for (uint256 i = 0; i < arrayCount; i++) { for (uint256 j = 0; j < arrayOfArrays[i].length; j++) { newArray[k] = arrayOfArrays[i][j]; k++; } } return newArray; } function concat(bytes[] memory arrayOfArrays) internal pure returns (bytes memory) { uint256 arrayCount = arrayOfArrays.length; uint256 totalLength = 0; for (uint256 i = 0; i < arrayCount; i++) { totalLength += arrayOfArrays[i].length; } bytes memory newArray = new bytes(totalLength); uint256 k = 0; for (uint256 i = 0; i < arrayCount; i++) { for (uint256 j = 0; j < arrayOfArrays[i].length; j++) { newArray[k] = arrayOfArrays[i][j]; k++; } } return newArray; } function concat(bytes[] memory arrayOfArrays) internal pure returns (bytes memory) { uint256 arrayCount = arrayOfArrays.length; uint256 totalLength = 0; for (uint256 i = 0; i < arrayCount; i++) { totalLength += arrayOfArrays[i].length; } bytes memory newArray = new bytes(totalLength); uint256 k = 0; for (uint256 i = 0; i < arrayCount; i++) { for (uint256 j = 0; j < arrayOfArrays[i].length; j++) { newArray[k] = arrayOfArrays[i][j]; k++; } } return newArray; } function concat(bytes[] memory arrayOfArrays) internal pure returns (bytes memory) { uint256 arrayCount = arrayOfArrays.length; uint256 totalLength = 0; for (uint256 i = 0; i < arrayCount; i++) { totalLength += arrayOfArrays[i].length; } bytes memory newArray = new bytes(totalLength); uint256 k = 0; for (uint256 i = 0; i < arrayCount; i++) { for (uint256 j = 0; j < arrayOfArrays[i].length; j++) { newArray[k] = arrayOfArrays[i][j]; k++; } } return newArray; } function concat(uint256[][] memory arrayOfArrays) internal pure returns (uint256[] memory) { uint256 arrayCount = arrayOfArrays.length; uint256 totalLength = 0; for (uint256 i = 0; i < arrayCount; i++) { totalLength += arrayOfArrays[i].length; } uint256[] memory newArray = new uint256[](totalLength); uint256 k = 0; for (uint256 i = 0; i < arrayCount; i++) { for (uint256 j = 0; j < arrayOfArrays[i].length; j++) { newArray[k] = arrayOfArrays[i][j]; k++; } } return newArray; } function concat(uint256[][] memory arrayOfArrays) internal pure returns (uint256[] memory) { uint256 arrayCount = arrayOfArrays.length; uint256 totalLength = 0; for (uint256 i = 0; i < arrayCount; i++) { totalLength += arrayOfArrays[i].length; } uint256[] memory newArray = new uint256[](totalLength); uint256 k = 0; for (uint256 i = 0; i < arrayCount; i++) { for (uint256 j = 0; j < arrayOfArrays[i].length; j++) { newArray[k] = arrayOfArrays[i][j]; k++; } } return newArray; } function concat(uint256[][] memory arrayOfArrays) internal pure returns (uint256[] memory) { uint256 arrayCount = arrayOfArrays.length; uint256 totalLength = 0; for (uint256 i = 0; i < arrayCount; i++) { totalLength += arrayOfArrays[i].length; } uint256[] memory newArray = new uint256[](totalLength); uint256 k = 0; for (uint256 i = 0; i < arrayCount; i++) { for (uint256 j = 0; j < arrayOfArrays[i].length; j++) { newArray[k] = arrayOfArrays[i][j]; k++; } } return newArray; } function concat(uint256[][] memory arrayOfArrays) internal pure returns (uint256[] memory) { uint256 arrayCount = arrayOfArrays.length; uint256 totalLength = 0; for (uint256 i = 0; i < arrayCount; i++) { totalLength += arrayOfArrays[i].length; } uint256[] memory newArray = new uint256[](totalLength); uint256 k = 0; for (uint256 i = 0; i < arrayCount; i++) { for (uint256 j = 0; j < arrayOfArrays[i].length; j++) { newArray[k] = arrayOfArrays[i][j]; k++; } } return newArray; } function range(uint256 from, uint256 to) internal pure returns (uint256[] memory rangeArray) { require(from < to, 'from >= to'); rangeArray = new uint256[](to - from); for (uint256 i = 0; i < rangeArray.length; i++) { rangeArray[i] = from + i; } } function range(uint256 from, uint256 to) internal pure returns (uint256[] memory rangeArray) { require(from < to, 'from >= to'); rangeArray = new uint256[](to - from); for (uint256 i = 0; i < rangeArray.length; i++) { rangeArray[i] = from + i; } } }
12,604,998
[ 1, 11864, 364, 13441, 27967, 3778, 5352, 25448, 2502, 5352, 16, 3778, 5352, 848, 1404, 506, 21615, 358, 732, 999, 4259, 12788, 4186, 358, 2103, 13200, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 1510, 5664, 1989, 288, 203, 683, 9454, 18035, 560, 3602, 20, 18, 26, 18, 20, 31, 203, 565, 445, 1817, 12, 11890, 5034, 8526, 3778, 526, 16, 2254, 5034, 1244, 13, 2713, 16618, 1135, 261, 11890, 5034, 8526, 3778, 13, 288, 203, 3639, 2254, 5034, 526, 1782, 273, 526, 18, 2469, 31, 203, 3639, 2254, 5034, 8526, 3778, 11653, 273, 394, 2254, 5034, 8526, 12, 1126, 1782, 397, 404, 1769, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 526, 1782, 31, 277, 27245, 288, 203, 5411, 11653, 63, 77, 65, 273, 526, 63, 77, 15533, 203, 3639, 289, 203, 3639, 11653, 63, 1126, 1782, 65, 273, 1244, 31, 203, 3639, 327, 11653, 31, 203, 565, 289, 203, 203, 565, 445, 1817, 12, 11890, 5034, 8526, 3778, 526, 16, 2254, 5034, 1244, 13, 2713, 16618, 1135, 261, 11890, 5034, 8526, 3778, 13, 288, 203, 3639, 2254, 5034, 526, 1782, 273, 526, 18, 2469, 31, 203, 3639, 2254, 5034, 8526, 3778, 11653, 273, 394, 2254, 5034, 8526, 12, 1126, 1782, 397, 404, 1769, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 526, 1782, 31, 277, 27245, 288, 203, 5411, 11653, 63, 77, 65, 273, 526, 63, 77, 15533, 203, 3639, 289, 203, 3639, 11653, 63, 1126, 1782, 65, 273, 1244, 31, 203, 3639, 327, 11653, 31, 203, 565, 289, 203, 203, 565, 445, 1843, 12, 11890, 5034, 8526, 3778, 526, 13, 2713, 16618, 1135, 261, 11890, 5034, 8526, 3778, 13, 288, 203, 3639, 2254, 5034, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; // Openzeppelin. import "../openzeppelin-solidity/contracts/SafeMath.sol"; // Internal references. import '../interfaces/external/ICandlestickDataFeedRegistry.sol'; // Inheritance. import '../interfaces/IIndicator.sol'; contract EMA is IIndicator { using SafeMath for uint256; // Maximum number of elements to use for the history. // This prevents 'for' loops with too many iterations, which may exceed the block gas limit. uint256 public constant MAX_HISTORY_LENGTH = 20; // Maximum number of seconds between indicator updates before the indicator is considered inactive. uint256 public constant MAX_TIME_BETWEEN_UPDATES = 180; address public immutable componentRegistry; address public immutable keeperRegistry; ICandlestickDataFeedRegistry public immutable candlestickDataFeedRegistry; uint256 public constant multiplierNumerator = 2; // Keep track of total number of instances. // This ensures instance IDs are unique. uint256 numberOfInstances; // (instance number => instance state). mapping (uint256 => State) public instances; // (instance number => timestamp at which the instance was last updated). // Prevents keepers from updating instances too frequently. mapping (uint256 => uint256) public lastUpdated; // (instance number => timeframe, in minutes). // The indicator instance's timeframe can be different from the asset's timeframe. mapping (uint256 => uint256) public override indicatorTimeframe; // (instance number => address of the instance's dedicated keeper). mapping (uint256 => address) public override keepers; constructor(address _componentRegistry, address _candlestickDataFeedRegistry, address _keeperRegistry) { require(_componentRegistry != address(0), "Indicator: Invalid address for _componentRegistry."); require(_candlestickDataFeedRegistry != address(0), "Indicator: Invalid address for _candlestickDataFeedRegistry."); require(_keeperRegistry != address(0), "Indicator: Invalid address for _keeperRegistry."); componentRegistry = _componentRegistry; keeperRegistry = _keeperRegistry; candlestickDataFeedRegistry = ICandlestickDataFeedRegistry(_candlestickDataFeedRegistry); } /* ========== VIEWS ========== */ /** * @notice Returns the name of this indicator. */ function getName() external pure override returns (string memory) { return "EMA"; } /** * @notice Returns the value of this indicator for the given instance. * @dev Returns an empty array if the instance number is out of bounds. * @param _instance Instance number of this indicator. * @return (uint256[] memory) Indicator value for the given instance. */ function getValue(uint256 _instance) external view override returns (uint256[] memory) { uint256[] memory result = new uint256[](1); result[0] = instances[_instance].value; return result; } /** * @notice Returns the history of this indicator for the given instance. * @dev Returns an empty array if the instance number is out of bounds. * @param _instance Instance number of this indicator. * @return (uint256[] memory) Indicator value history for the given instance. */ function getHistory(uint256 _instance) external view override returns (uint256[] memory) { uint256 historyLength = instances[_instance].history.length; uint256 length = historyLength >= MAX_HISTORY_LENGTH ? MAX_HISTORY_LENGTH : historyLength; uint256[] memory history = new uint256[](length); for (uint256 i = 0; i < length; i++) { history[i] = instances[_instance].history[historyLength.sub(length).add(i)]; } return history; } /** * @notice Returns whether the indicator instance can be updated. * @param _instance Instance number of this indicator. * @return bool Whether the indicator instance can be updated. */ function canUpdate(uint256 _instance) public view override returns (bool) { return block.timestamp >= lastUpdated[_instance].add(indicatorTimeframe[_instance].mul(60)).sub(2); } /** * @notice Returns the status of the given instance of this indicator. * @param _instance Instance number of this indicator. * @return bool Whether the indicator instance is active. */ function isActive(uint256 _instance) external view override returns (bool) { if (block.timestamp > lastUpdated[_instance].add(indicatorTimeframe[_instance].mul(60)).add(MAX_TIME_BETWEEN_UPDATES)) { return false; } return true; } /** * @notice Returns the state of the given indicator instance. * @dev Returns 0 for each value if the instance is out of bounds. * @param _instance Instance number of this indicator. * @return (string, address, uint256, uint256, uint256[]) Asset symbol, * timeframe of the asset (in minutes), * the current value of the given instance, * an array of params for the given instance, * an array of variables for the given instance, * the history of the given instance. */ function getState(uint256 _instance) external view override returns (string memory, uint256, uint256, uint256[] memory, uint256[] memory, uint256[] memory) { // Gas savings. State memory state = instances[_instance]; uint256[] memory params = new uint256[](state.params.length); uint256[] memory variables = new uint256[](state.variables.length); uint256[] memory history = new uint256[](state.history.length >= MAX_HISTORY_LENGTH ? MAX_HISTORY_LENGTH : state.history.length); for (uint256 i = 0; i < params.length; i++) { params[i] = instances[_instance].params[i]; } for (uint256 i = 0; i < variables.length; i++) { variables[i] = instances[_instance].variables[i]; } for (uint256 i = 0; i < history.length; i++) { history[i] = instances[_instance].history[i]; } return (state.asset, state.assetTimeframe, state.value, params, variables, history); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Creates an instance of this indicator. * @dev This function can only be called by the ComponentRegistry contract. * @param _asset Symbol of the asset. * @param _assetTimeframe Timeframe (in minutes) of the asset's data feed. * @param _indicatorTimeframe Timeframe (in minutes) of the indicator instance. * @param _params An array of parameters. * @return (uint256) Instance number of the indicator. */ function createInstance(string memory _asset, uint256 _assetTimeframe, uint256 _indicatorTimeframe, uint256[] memory _params) external override onlyComponentRegistry returns (uint256) { require(_params.length >= 1, "Indicator: Not enough params."); require(_params[0] > 1 && _params[0] <= 200, "Indicator: Param out of bounds."); // Gas savings. uint256 instanceNumber = numberOfInstances.add(1); indicatorTimeframe[instanceNumber] = _indicatorTimeframe; numberOfInstances = instanceNumber; instances[instanceNumber] = State({ asset: _asset, assetTimeframe: _assetTimeframe, value: 0, params: _params, variables: new uint256[](2), history: new uint256[](0) }); instances[instanceNumber].variables[1] = _params[0].add(1); emit CreatedInstance(instanceNumber, _asset, _assetTimeframe, _indicatorTimeframe, _params); return instanceNumber; } /** * @notice Updates the indicator's state for the given instance, based on the latest price feed update. * @dev This function can only be called by the dedicated keeper of this instance. * @param _instance Instance number of this indicator. * @return bool Whether the indicator was updated successfully. */ function update(uint256 _instance) external override onlyDedicatedKeeper(_instance) returns (bool) { require(canUpdate(_instance), "Indicator: Cannot update yet."); State memory data = instances[_instance]; uint256 latestPrice = candlestickDataFeedRegistry.getCurrentPrice(data.asset, data.assetTimeframe); // Return early if there was an error getting the latest price. if (latestPrice == 0) { return false; } uint256 currentValue = data.value; uint256 newValue = (currentValue == 0) ? latestPrice : (latestPrice >= data.variables[0]) ? (multiplierNumerator.mul(latestPrice.sub(data.variables[0])).div(data.variables[1])).add(data.variables[0]) : data.variables[0].sub(multiplierNumerator.mul(data.variables[0].sub(latestPrice)).div(data.variables[1])); instances[_instance].value = newValue; instances[_instance].variables[0] = (currentValue == 0) ? latestPrice : currentValue; instances[_instance].history.push(newValue); lastUpdated[_instance] = block.timestamp; emit Updated(_instance, latestPrice, newValue); return true; } /** * @notice Updates the dedicated keeper for the given instance of this indicator. * @dev This function can only be called by the KeeperRegistry contract. * @param _instance Instance number of this indicator. * @param _newKeeper Address of the new keeper contract. */ function setKeeper(uint256 _instance, address _newKeeper) external override onlyKeeperRegistry { require((_newKeeper == address(0) && keepers[_instance] != address(0)) || (_newKeeper != address(0) && keepers[_instance] == address(0)), "Indicator: Invalid keeper."); keepers[_instance] = _newKeeper; emit UpdatedKeeper(_instance, _newKeeper); } /* ========== MODIFIERS ========== */ modifier onlyDedicatedKeeper(uint256 _instance) { require(keepers[_instance] == msg.sender, "Indicator: Only the dedicated keeper for this instance can call the function."); _; } modifier onlyComponentRegistry() { require(msg.sender == componentRegistry, "Indicator: Only the ComponentRegistry contract can call this function."); _; } modifier onlyKeeperRegistry() { require(msg.sender == keeperRegistry, "Indicator: Only the KeeperRegistry contract can call this function."); _; } }
* @notice Updates the indicator's state for the given instance, based on the latest price feed update. @dev This function can only be called by the dedicated keeper of this instance. @param _instance Instance number of this indicator. @return bool Whether the indicator was updated successfully./ Return early if there was an error getting the latest price.
function update(uint256 _instance) external override onlyDedicatedKeeper(_instance) returns (bool) { require(canUpdate(_instance), "Indicator: Cannot update yet."); State memory data = instances[_instance]; uint256 latestPrice = candlestickDataFeedRegistry.getCurrentPrice(data.asset, data.assetTimeframe); if (latestPrice == 0) { return false; } uint256 currentValue = data.value; uint256 newValue = (currentValue == 0) ? latestPrice : (latestPrice >= data.variables[0]) ? (multiplierNumerator.mul(latestPrice.sub(data.variables[0])).div(data.variables[1])).add(data.variables[0]) : data.variables[0].sub(multiplierNumerator.mul(data.variables[0].sub(latestPrice)).div(data.variables[1])); instances[_instance].value = newValue; instances[_instance].variables[0] = (currentValue == 0) ? latestPrice : currentValue; instances[_instance].history.push(newValue); lastUpdated[_instance] = block.timestamp; emit Updated(_instance, latestPrice, newValue); return true; }
15,807,218
[ 1, 5121, 326, 10664, 1807, 919, 364, 326, 864, 791, 16, 2511, 603, 326, 4891, 6205, 4746, 1089, 18, 225, 1220, 445, 848, 1338, 506, 2566, 635, 326, 24328, 417, 9868, 434, 333, 791, 18, 225, 389, 1336, 5180, 1300, 434, 333, 10664, 18, 327, 1426, 17403, 326, 10664, 1703, 3526, 4985, 18, 19, 2000, 11646, 309, 1915, 1703, 392, 555, 8742, 326, 4891, 6205, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 12, 11890, 5034, 389, 1336, 13, 3903, 3849, 1338, 26892, 17891, 24899, 1336, 13, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 12, 4169, 1891, 24899, 1336, 3631, 315, 13140, 30, 14143, 1089, 4671, 1199, 1769, 203, 203, 3639, 3287, 3778, 501, 273, 3884, 63, 67, 1336, 15533, 203, 3639, 2254, 5034, 4891, 5147, 273, 15350, 80, 395, 1200, 751, 8141, 4243, 18, 588, 3935, 5147, 12, 892, 18, 9406, 16, 501, 18, 9406, 950, 3789, 1769, 203, 203, 3639, 309, 261, 13550, 5147, 422, 374, 13, 288, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 14794, 273, 501, 18, 1132, 31, 203, 3639, 2254, 5034, 6129, 273, 261, 2972, 620, 422, 374, 13, 692, 4891, 5147, 294, 203, 4766, 565, 261, 13550, 5147, 1545, 501, 18, 7528, 63, 20, 5717, 692, 203, 4766, 565, 261, 20538, 2578, 7385, 18, 16411, 12, 13550, 5147, 18, 1717, 12, 892, 18, 7528, 63, 20, 5717, 2934, 2892, 12, 892, 18, 7528, 63, 21, 5717, 2934, 1289, 12, 892, 18, 7528, 63, 20, 5717, 294, 203, 4766, 565, 501, 18, 7528, 63, 20, 8009, 1717, 12, 20538, 2578, 7385, 18, 16411, 12, 892, 18, 7528, 63, 20, 8009, 1717, 12, 13550, 5147, 13, 2934, 2892, 12, 892, 18, 7528, 63, 21, 5717, 1769, 203, 203, 3639, 3884, 63, 67, 1336, 8009, 1132, 273, 6129, 31, 203, 3639, 3884, 63, 67, 1336, 8009, 7528, 63, 20, 65, 273, 261, 2972, 620, 422, 374, 13, 692, 4891, 5147, 294, 14794, 31, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-06-07 */ /** *Submitted for verification at BscScan.com on 2021-05-09 */ /** *Submitted for verification at BscScan.com on 2021-05-01 */ /** *Submitted for verification at BscScan.com on 2021-05-01 */ /** */ pragma solidity ^0.6.12; // SPDX-License-Identifier: Unlicensed interface IERC20 { function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } 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; } } /** * @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); } } } } /** * @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; address private _previousOwner; uint256 private _lockTime; 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; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = now + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(now > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } // pragma solidity >=0.5.0; 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; } // pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // pragma solidity >=0.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.2; 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 JollyRoger is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; address public charityaddress = 0x7aA09A068CE457a5b477d155824DB74a9542Ffb5; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 100000000 * 10**18; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _tBurnTotal; string private _name = "JollyRoger"; string private _symbol = "$LOOT"; uint8 private _decimals = 18; uint256 public _taxFee = 0; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee = 0; uint256 private _previousLiquidityFee = _liquidityFee; uint256 public _burnFee = 0; uint256 private _previousburnFee = _burnFee; uint256 public _charityFee = 7; uint256 private _previouscharityFee = _charityFee; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 public _maxTxAmount = 1000000 * 10**18; uint256 private numTokensSellToAddToLiquidity = 100000 * 10**18; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () public { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; // exclude charity from fee _isExcludedFromFee[charityaddress] = true; // exclude charity from standard 4% reflection distribution reward _isExcluded[charityaddress] = true; _excluded.push(charityaddress); emit Transfer(address(0), _msgSender(), _tTotal); } 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 _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function totalBurn() public view returns (uint256) { return _tBurnTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); uint256 tburnFee = calculateBurnFee(tAmount); uint256 rburnfee = tburnFee.mul(_getRate()); // _tOwned[burnaddress] = _tOwned[burnaddress].add(tburnFee); // _rOwned[burnaddress] = _rOwned[burnaddress].add(rburnfee); uint256 tcharityFee = calculateCharityFee(tAmount); uint256 rcharityfee = tcharityFee.mul(_getRate()); _tOwned[charityaddress] = _tOwned[charityaddress].add(tcharityFee); _rOwned[charityaddress] = _rOwned[charityaddress].add(rcharityfee); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee, rburnfee,tburnFee ); emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { _taxFee = taxFee; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { _liquidityFee = liquidityFee; } function setBurnFeePercent(uint256 burnfee) external onlyOwner() { _burnFee = burnfee; } function setCharityFeePercent(uint256 charityfee) external onlyOwner() { _charityFee = charityfee; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { _maxTxAmount = _tTotal.mul(maxTxPercent).div( 10**2 ); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee, uint256 rBurn, uint256 tBurn ) private { _rTotal = _rTotal.sub(rFee).sub(rBurn); _tFeeTotal = _tFeeTotal.add(tFee); _tBurnTotal = _tBurnTotal.add(tBurn); _tTotal = _tTotal.sub(tBurn); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tburnFee = calculateBurnFee(tAmount); uint256 tcharityFee = calculateCharityFee(tAmount); uint256 extrafee = tburnFee + tcharityFee; uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity).sub(extrafee); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private view returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 tburnFee = calculateBurnFee(tAmount); uint256 rburnfee = tburnFee.mul(currentRate); uint256 tcharityFee = calculateCharityFee(tAmount); uint256 rcharityfee = tcharityFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity).sub(rburnfee).sub(rcharityfee); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**2 ); } function calculateBurnFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_burnFee).div( 10**2 ); } function calculateCharityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_charityFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0 && _burnFee == 0 && _charityFee == 0 ) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _previousburnFee = _burnFee; _previouscharityFee = _charityFee; _taxFee = 0; _liquidityFee = 0; _burnFee = 0; _charityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; _burnFee = _previousburnFee; _charityFee = _previouscharityFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; //add liquidity swapAndLiquify(contractTokenBalance); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // split the contract balance into halves // 100 uint256 half = contractTokenBalance.div(2); // 50 uint256 otherHalf = contractTokenBalance.sub(half); // 50 // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // bnb // swap tokens for ETH swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } 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 owner(), block.timestamp ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); uint256 tburnFee = calculateBurnFee(tAmount); uint256 rburnfee = tburnFee.mul(_getRate()); // _tOwned[burnaddress] = _tOwned[burnaddress].add(tburnFee); // _rOwned[burnaddress] = _rOwned[burnaddress].add(rburnfee); uint256 tcharityFee = calculateCharityFee(tAmount); uint256 rcharityfee = tcharityFee.mul(_getRate()); _tOwned[charityaddress] = _tOwned[charityaddress].add(tcharityFee); _rOwned[charityaddress] = _rOwned[charityaddress].add(rcharityfee); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee, rburnfee,tburnFee ); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); uint256 tburnFee = calculateBurnFee(tAmount); uint256 rburnfee = tburnFee.mul(_getRate()); // _tOwned[burnaddress] = _tOwned[burnaddress].add(tburnFee); // _rOwned[burnaddress] = _rOwned[burnaddress].add(rburnfee); uint256 tcharityFee = calculateCharityFee(tAmount); uint256 rcharityfee = tcharityFee.mul(_getRate()); _tOwned[charityaddress] = _tOwned[charityaddress].add(tcharityFee); _rOwned[charityaddress] = _rOwned[charityaddress].add(rcharityfee); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee, rburnfee,tburnFee ); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); uint256 tburnFee = calculateBurnFee(tAmount); uint256 rburnfee = tburnFee.mul(_getRate()); // _tOwned[burnaddress] = _tOwned[burnaddress].add(tburnFee); // _rOwned[burnaddress] = _rOwned[burnaddress].add(rburnfee); uint256 tcharityFee = calculateCharityFee(tAmount); uint256 rcharityfee = tcharityFee.mul(_getRate()); _tOwned[charityaddress] = _tOwned[charityaddress].add(tcharityFee); _rOwned[charityaddress] = _rOwned[charityaddress].add(rcharityfee); // _tTotal = _tTotal.sub(tburnFee); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee, rburnfee,tburnFee ); emit Transfer(sender, recipient, tTransferAmount); } }
SPDX-License-Identifier: Unlicensed
interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); }
12,004,959
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 1351, 80, 335, 28003, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5831, 467, 654, 39, 3462, 288, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 7412, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 7412, 1265, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 460, 1769, 203, 203, 203, 203, 203, 21281, 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 ]
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(addr) } return size > 0; } } /** * Strings Library * * In summary this is a simple library of string functions which make simple * string operations less tedious in solidity. * * Please be aware these functions can be quite gas heavy so use them only when * necessary not to clog the blockchain with expensive transactions. * * @author James Lockhart <[email protected]> */ library Strings { /** * Concat (High gas cost) * * Appends two strings together and returns a new value * * @param _base When being used for a data type this is the extended object * otherwise this is the string which will be the concatenated * prefix * @param _value The value to be the concatenated suffix * @return string The resulting string from combinging the base and value */ function concat(string _base, string _value) internal returns (string) { bytes memory _baseBytes = bytes(_base); bytes memory _valueBytes = bytes(_value); assert(_valueBytes.length > 0); string memory _tmpValue = new string(_baseBytes.length + _valueBytes.length); bytes memory _newValue = bytes(_tmpValue); uint i; uint j; for(i = 0; i < _baseBytes.length; i++) { _newValue[j++] = _baseBytes[i]; } for(i = 0; i<_valueBytes.length; i++) { _newValue[j++] = _valueBytes[i]; } return string(_newValue); } /** * Index Of * * Locates and returns the position of a character within a string * * @param _base When being used for a data type this is the extended object * otherwise this is the string acting as the haystack to be * searched * @param _value The needle to search for, at present this is currently * limited to one character * @return int The position of the needle starting from 0 and returning -1 * in the case of no matches found */ function indexOf(string _base, string _value) internal returns (int) { return _indexOf(_base, _value, 0); } /** * Index Of * * Locates and returns the position of a character within a string starting * from a defined offset * * @param _base When being used for a data type this is the extended object * otherwise this is the string acting as the haystack to be * searched * @param _value The needle to search for, at present this is currently * limited to one character * @param _offset The starting point to start searching from which can start * from 0, but must not exceed the length of the string * @return int The position of the needle starting from 0 and returning -1 * in the case of no matches found */ function _indexOf(string _base, string _value, uint _offset) internal returns (int) { bytes memory _baseBytes = bytes(_base); bytes memory _valueBytes = bytes(_value); assert(_valueBytes.length == 1); for(uint i = _offset; i < _baseBytes.length; i++) { if (_baseBytes[i] == _valueBytes[0]) { return int(i); } } return -1; } /** * Length * * Returns the length of the specified string * * @param _base When being used for a data type this is the extended object * otherwise this is the string to be measured * @return uint The length of the passed string */ function length(string _base) internal returns (uint) { bytes memory _baseBytes = bytes(_base); return _baseBytes.length; } /** * Sub String * * Extracts the beginning part of a string based on the desired length * * @param _base When being used for a data type this is the extended object * otherwise this is the string that will be used for * extracting the sub string from * @param _length The length of the sub string to be extracted from the base * @return string The extracted sub string */ function substring(string _base, int _length) internal returns (string) { return _substring(_base, _length, 0); } /** * Sub String * * Extracts the part of a string based on the desired length and offset. The * offset and length must not exceed the lenth of the base string. * * @param _base When being used for a data type this is the extended object * otherwise this is the string that will be used for * extracting the sub string from * @param _length The length of the sub string to be extracted from the base * @param _offset The starting point to extract the sub string from * @return string The extracted sub string */ function _substring(string _base, int _length, int _offset) internal returns (string) { bytes memory _baseBytes = bytes(_base); assert(uint(_offset+_length) <= _baseBytes.length); string memory _tmp = new string(uint(_length)); bytes memory _tmpBytes = bytes(_tmp); uint j = 0; for(uint i = uint(_offset); i < uint(_offset+_length); i++) { _tmpBytes[j++] = _baseBytes[i]; } return string(_tmpBytes); } /** * String Split (Very high gas cost) * * Splits a string into an array of strings based off the delimiter value. * Please note this can be quite a gas expensive function due to the use of * storage so only use if really required. * * @param _base When being used for a data type this is the extended object * otherwise this is the string value to be split. * @param _value The delimiter to split the string on which must be a single * character * @return string[] An array of values split based off the delimiter, but * do not container the delimiter. */ function split(string _base, string _value) internal returns (string[] storage splitArr) { bytes memory _baseBytes = bytes(_base); uint _offset = 0; while(_offset < _baseBytes.length-1) { int _limit = _indexOf(_base, _value, _offset); if (_limit == -1) { _limit = int(_baseBytes.length); } string memory _tmp = new string(uint(_limit)-_offset); bytes memory _tmpBytes = bytes(_tmp); uint j = 0; for(uint i = _offset; i < uint(_limit); i++) { _tmpBytes[j++] = _baseBytes[i]; } _offset = uint(_limit) + 1; splitArr.push(string(_tmpBytes)); } return splitArr; } /** * Compare To * * Compares the characters of two strings, to ensure that they have an * identical footprint * * @param _base When being used for a data type this is the extended object * otherwise this is the string base to compare against * @param _value The string the base is being compared to * @return bool Simply notates if the two string have an equivalent */ function compareTo(string _base, string _value) internal returns (bool) { bytes memory _baseBytes = bytes(_base); bytes memory _valueBytes = bytes(_value); if (_baseBytes.length != _valueBytes.length) { return false; } for(uint i = 0; i < _baseBytes.length; i++) { if (_baseBytes[i] != _valueBytes[i]) { return false; } } return true; } /** * Compare To Ignore Case (High gas cost) * * Compares the characters of two strings, converting them to the same case * where applicable to alphabetic characters to distinguish if the values * match. * * @param _base When being used for a data type this is the extended object * otherwise this is the string base to compare against * @param _value The string the base is being compared to * @return bool Simply notates if the two string have an equivalent value * discarding case */ function compareToIgnoreCase(string _base, string _value) internal returns (bool) { bytes memory _baseBytes = bytes(_base); bytes memory _valueBytes = bytes(_value); if (_baseBytes.length != _valueBytes.length) { return false; } for(uint i = 0; i < _baseBytes.length; i++) { if (_baseBytes[i] != _valueBytes[i] && _upper(_baseBytes[i]) != _upper(_valueBytes[i])) { return false; } } return true; } /** * Upper * * Converts all the values of a string to their corresponding upper case * value. * * @param _base When being used for a data type this is the extended object * otherwise this is the string base to convert to upper case * @return string */ function upper(string _base) internal returns (string) { bytes memory _baseBytes = bytes(_base); for (uint i = 0; i < _baseBytes.length; i++) { _baseBytes[i] = _upper(_baseBytes[i]); } return string(_baseBytes); } /** * Lower * * Converts all the values of a string to their corresponding lower case * value. * * @param _base When being used for a data type this is the extended object * otherwise this is the string base to convert to lower case * @return string */ function lower(string _base) internal returns (string) { bytes memory _baseBytes = bytes(_base); for (uint i = 0; i < _baseBytes.length; i++) { _baseBytes[i] = _lower(_baseBytes[i]); } return string(_baseBytes); } /** * Upper * * Convert an alphabetic character to upper case and return the original * value when not alphabetic * * @param _b1 The byte to be converted to upper case * @return bytes1 The converted value if the passed value was alphabetic * and in a lower case otherwise returns the original value */ function _upper(bytes1 _b1) private constant returns (bytes1) { if (_b1 >= 0x61 && _b1 <= 0x7A) { return bytes1(uint8(_b1)-32); } return _b1; } /** * Lower * * Convert an alphabetic character to lower case and return the original * value when not alphabetic * * @param _b1 The byte to be converted to lower case * @return bytes1 The converted value if the passed value was alphabetic * and in a upper case otherwise returns the original value */ function _lower(bytes1 _b1) private constant returns (bytes1) { if (_b1 >= 0x41 && _b1 <= 0x5A) { return bytes1(uint8(_b1)+32); } return _b1; } } /** * Integers Library * * In summary this is a simple library of integer functions which allow a simple * conversion to and from strings * * @author James Lockhart <[email protected]> */ library Integers { /** * Parse Int * * Converts an ASCII string value into an uint as long as the string * its self is a valid unsigned integer * * @param _value The ASCII string to be converted to an unsigned integer * @return uint The unsigned value of the ASCII string */ function parseInt(string _value) public pure returns (uint _ret) { bytes memory _bytesValue = bytes(_value); uint j = 1; for(uint i = _bytesValue.length-1; i >= 0 && i < _bytesValue.length; i--) { assert(_bytesValue[i] >= 48 && _bytesValue[i] <= 57); _ret += (uint(_bytesValue[i]) - 48)*j; j*=10; } } /** * To String * * Converts an unsigned integer to the ASCII string equivalent value * * @param _base The unsigned integer to be converted to a string * @return string The resulting ASCII string value */ function toString(uint _base) internal pure returns (string) { bytes memory _tmp = new bytes(32); uint i; for(i = 0;_base > 0;i++) { _tmp[i] = byte((_base % 10) + 48); _base /= 10; } bytes memory _real = new bytes(i--); for(uint j = 0; j < _real.length; j++) { _real[j] = _tmp[i--]; } return string(_real); } /** * To Byte * * Convert an 8 bit unsigned integer to a byte * * @param _base The 8 bit unsigned integer * @return byte The byte equivalent */ function toByte(uint8 _base) public pure returns (byte _ret) { assembly { let m_alloc := add(msize(),0x1) mstore8(m_alloc, _base) _ret := mload(m_alloc) } } /** * To Bytes * * Converts an unsigned integer to bytes * * @param _base The integer to be converted to bytes * @return bytes The bytes equivalent */ function toBytes(uint _base) internal pure returns (bytes _ret) { assembly { let m_alloc := add(msize(),0x1) _ret := mload(m_alloc) mstore(_ret, 0x20) mstore(add(_ret, 0x20), _base) } } } contract HEROES { using SafeMath for uint256; using AddressUtils for address; using Strings for string; using Integers for uint; event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); event Lock(uint256 lockedTo, uint16 lockId); event LevelUp(uint32 level); struct Character { uint256 genes; uint256 mintedAt; uint256 godfather; uint256 mentor; uint32 wins; uint32 losses; uint32 level; uint256 lockedTo; uint16 lockId; } string internal constant name_ = "⚔ CRYPTOHEROES GAME ⚔"; string internal constant symbol_ = "CRYPTOHEROES"; string internal baseURI_; address internal admin; mapping(address => bool) internal agents; bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; mapping(uint256 => address) internal tokenOwner; mapping(address => uint256[]) internal ownedTokens; mapping(uint256 => uint256) internal ownedTokensIndex; mapping(address => uint256) internal ownedTokensCount; mapping(uint256 => address) internal tokenApprovals; mapping(address => mapping(address => bool)) internal operatorApprovals; uint256[] internal allTokens; mapping(uint256 => uint256) internal allTokensIndex; Character[] characters; mapping(uint256 => uint256) tokenCharacters; // tokenId => characterId modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender || (ownerOf(_tokenId) == tx.origin && isAgent(msg.sender)) || msg.sender == admin); _; } modifier canTransfer(uint256 _tokenId) { require(isLocked(_tokenId) && (isApprovedOrOwned(msg.sender, _tokenId) || (isApprovedOrOwned(tx.origin, _tokenId) && isAgent(msg.sender)) || msg.sender == admin)); _; } modifier onlyAdmin() { require(msg.sender == admin); _; } modifier onlyAgent() { require(isAgent(msg.sender)); _; } /* CONTRACT METHODS */ constructor(string _baseURI) public { baseURI_ = _baseURI; admin = msg.sender; addAgent(msg.sender); } function name() external pure returns (string) { return name_; } function symbol() external pure returns (string) { return symbol_; } /* METADATA METHODS */ function setBaseURI(string _baseURI) external onlyAdmin { baseURI_ = _baseURI; } function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return baseURI_.concat(_tokenId.toString()); } function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } function totalSupply() public view returns (uint256) { return allTokens.length; } /* TOKEN METHODS */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); if (getApproved(_tokenId) != address(0) || _to != address(0)) { tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } } function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } function isApprovedForAll(address _owner, address _operator) public view returns (bool) { return operatorApprovals[_owner][_operator]; } function transferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } function safeTransferFrom(address _from, address _to, uint256 _tokenId) public { safeTransferFrom(_from, _to, _tokenId, ""); } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } function isApprovedOrOwned(address _spender, uint256 _tokenId) internal view returns (bool) { address owner = ownerOf(_tokenId); return (_spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender)); } function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); emit Approval(_owner, address(0), _tokenId); } } function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } function addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } function removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } function checkAndCallSafeTransfer(address _from, address _to, uint256 _tokenId, bytes _data) internal returns(bool) { return true; } /* AGENT ROLE */ function addAgent(address _agent) public onlyAdmin { agents[_agent] = true; } function removeAgent(address _agent) external onlyAdmin { agents[_agent] = false; } function isAgent(address _agent) public view returns (bool) { return agents[_agent]; } /* CHARACTER LOGIC */ function getCharacter(uint256 _tokenId) external view returns (uint256 genes, uint256 mintedAt, uint256 godfather, uint256 mentor, uint32 wins, uint32 losses, uint32 level, uint256 lockedTo, uint16 lockId) { require(exists(_tokenId)); Character memory c = characters[tokenCharacters[_tokenId]]; genes = c.genes; mintedAt = c.mintedAt; godfather = c.godfather; mentor = c.mentor; wins = c.wins; losses = c.losses; level = c.level; lockedTo = c.lockedTo; lockId = c.lockId; } function addWin(uint256 _tokenId) external onlyAgent { require(exists(_tokenId)); Character storage character = characters[tokenCharacters[_tokenId]]; character.wins++; character.level++; emit LevelUp(character.level); } function addLoss(uint256 _tokenId) external onlyAgent { require(exists(_tokenId)); Character storage character = characters[tokenCharacters[_tokenId]]; character.losses++; if (character.level > 1) { character.level--; emit LevelUp(character.level); } } /* MINTING */ function mintTo(address _to, uint256 _genes, uint256 _godfather, uint256 _mentor, uint32 _level) external onlyAgent returns (uint256) { uint256 newTokenId = totalSupply().add(1); _mint(_to, newTokenId); _mintCharacter(newTokenId, _genes, _godfather, _mentor, _level); return newTokenId; } function _mintCharacter(uint256 _tokenId, uint256 _genes, uint256 _godfather, uint256 _mentor, uint32 _level) internal { require(exists(_tokenId)); Character memory character = Character({ genes: _genes, mintedAt: now, mentor: _mentor, godfather: _godfather, wins: 0, losses: 0, level: _level, lockedTo: 0, lockId: 0 }); uint256 characterId = characters.push(character) - 1; tokenCharacters[_tokenId] = characterId; } /* LOCKS */ function lock(uint256 _tokenId, uint256 _lockedTo, uint16 _lockId) external onlyAgent returns (bool) { require(exists(_tokenId)); Character storage character = characters[tokenCharacters[_tokenId]]; if (character.lockId == 0) { character.lockedTo = _lockedTo; character.lockId = _lockId; emit Lock(character.lockedTo, character.lockId); return true; } return false; } function unlock(uint256 _tokenId, uint16 _lockId) external onlyAgent returns (bool) { require(exists(_tokenId)); Character storage character = characters[tokenCharacters[_tokenId]]; if (character.lockId == _lockId) { character.lockedTo = 0; character.lockId = 0; emit Lock(character.lockedTo, character.lockId); return true; } return false; } function getLock(uint256 _tokenId) external view returns (uint256 lockedTo, uint16 lockId) { require(exists(_tokenId)); lockedTo = characters[tokenCharacters[_tokenId]].lockedTo; lockId = characters[tokenCharacters[_tokenId]].lockId; } function isLocked(uint _tokenId) public view returns (bool) { require(exists(_tokenId)); //isLocked workaround: lockedTo должен быть =1 для блокировки трансфер return ((characters[tokenCharacters[_tokenId]].lockedTo == 0 && characters[tokenCharacters[_tokenId]].lockId != 0) || now <= characters[tokenCharacters[_tokenId]].lockedTo); } function test(uint256 _x) returns (bool) { return now <= _x; } }
tokenId => characterId
mapping(uint256 => uint256) tokenCharacters;
5,501,199
[ 1, 2316, 548, 516, 26235, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 1147, 11600, 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 ]
// ______ __ __ // / ____/___ ___ / /_ / /__ ____ ___ // / __/ / __ `__ \/ __ \/ / _ \/ __ `__ \ // / /___/ / / / / / /_/ / / __/ / / / / / // /_____/_/ /_/ /_/_.___/_/\___/_/ /_/ /_/ // | | / /___ ___ __/ / /_ // | | / / __ `/ / / / / __/ // | |/ / /_/ / /_/ / / /_ // |___/\__,_/\__,_/_/\__/ // __ __ ____ ______ // / / / /___ _____ ____/ / /__ _____ _ __/ ____/ // / /_/ / __ `/ __ \/ __ / / _ \/ ___/ | | / /___ \ // / __ / /_/ / / / / /_/ / / __/ / | |/ /___/ / // /_/ /_/\__,_/_/ /_/\__,_/_/\___/_/ |___/_____/ // File: browser/ReentrancyGuard.sol // 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; } } // File: browser/IERC20Token.sol pragma solidity ^0.6.11; interface IERC20Token { 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); } // File: browser/SafeMath.sol pragma solidity ^0.6.11; /** * @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: browser/VaultHandler_v4.sol pragma experimental ABIEncoderV2; pragma solidity ^0.6.11; interface IERC721 { function burn(uint256 tokenId) external; function transferFrom(address from, address to, uint256 tokenId) external; function mint( address _to, uint256 _tokenId, string calldata _uri, string calldata _payload) external; function changeName(string calldata name, string calldata symbol) external; function updateTokenUri(uint256 _tokenId,string memory _uri) external; function tokenPayload(uint256 _tokenId) external view returns (string memory); function ownerOf(uint256 _tokenId) external returns (address _owner); function getApproved(uint256 _tokenId) external returns (address); function safeTransferFrom(address _from, address _to, uint256 _tokenId) external; } interface Ownable { function transferOwnership(address newOwner) external; } interface BasicERC20 { function burn(uint256 value) external; function decimals() external view returns (uint8); } contract VaultHandlerV5 is ReentrancyGuard { using SafeMath for uint256; using SafeMath for uint8; address payable private owner; string public metadataBaseUri; bool public initialized; address public nftAddress; address public paymentAddress; address public recipientAddress; address public couponAddress; uint256 public price; uint256 public offerPrice = 0; bool public payToAcceptOffer = false; bool public payToMakeOffer = false; bool public shouldBurn = false; struct PreMint { string payload; bytes32 preImage; } struct PreTransfer { string payload; bytes32 preImage; address _from; } struct Offer { uint tokenId; address _from; } // mapping(uint => PreMint) public tokenIdToPreMint; mapping(address => mapping(uint => PreMint)) preMints; mapping(address => mapping(uint => PreMint)) preMintsByIndex; mapping(address => uint) preMintCounts; mapping(uint => PreTransfer) preTransfers; mapping(uint => mapping(uint => PreTransfer)) preTransfersByIndex; mapping(uint => uint) preTransferCounts; mapping(uint => Offer[]) offers; mapping(uint => Offer[]) rejected; mapping(address => mapping(uint => Offer)) offered; mapping(address => bool) public witnesses; mapping(uint256 => bool) usedNonces; // event for EVM logging event OwnerSet(address indexed oldOwner, address indexed newOwner); // modifier to check if caller is owner modifier isOwner() { // If the first argument of 'require' evaluates to 'false', execution terminates and all // changes to the state and to Ether balances are reverted. // This used to consume all gas in old EVM versions, but not anymore. // It is often a good idea to use 'require' to check if functions are called correctly. // As a second argument, you can also provide an explanation about what went wrong. require(msg.sender == owner, "Caller is not owner"); _; } /** * @dev Change owner * @param newOwner address of new owner */ function transferOwnership(address payable newOwner) public isOwner { emit OwnerSet(owner, newOwner); owner = newOwner; } /** * @dev Return owner address * @return address of owner */ function getOwner() external view returns (address) { return owner; } constructor(address _nftAddress, address _paymentAddress, address _recipientAddress, uint256 _price) public { owner = msg.sender; // 'msg.sender' is sender of current call, contract deployer for a constructor emit OwnerSet(address(0), owner); addWitness(owner); metadataBaseUri = "http://104.154.252.216/meta/"; nftAddress = _nftAddress; paymentAddress = _paymentAddress; recipientAddress = _recipientAddress; initialized = true; uint decimals = BasicERC20(paymentAddress).decimals(); price = _price * 10 ** decimals; } function claim(uint256 tokenId) public isOwner { IERC721 token = IERC721(nftAddress); token.burn(tokenId); } function buyWithPaymentOnly(address _to, uint256 _tokenId, string calldata image) public payable { IERC20Token paymentToken = IERC20Token(paymentAddress); IERC721 nftToken = IERC721(nftAddress); PreMint memory preMint = preMints[msg.sender][_tokenId]; require(preMint.preImage == sha256(abi.encodePacked(image)), 'Payload does not match'); // Payload should match if (shouldBurn) { require(paymentToken.transferFrom(msg.sender, address(this), price), 'Transfer ERROR'); // Payment sent to recipient BasicERC20(paymentAddress).burn(price); } else { require(paymentToken.transferFrom(msg.sender, address(recipientAddress), price), 'Transfer ERROR'); // Payment sent to recipient } string memory _uri = concat(metadataBaseUri, uintToStr(_tokenId)); nftToken.mint(_to, _tokenId, _uri, preMint.payload); delete preMintsByIndex[msg.sender][preMintCounts[msg.sender]]; delete preMints[msg.sender][_tokenId]; preMintCounts[msg.sender] = preMintCounts[msg.sender].sub(1); } function addPreMint(address _for, string calldata _payload, uint256 _tokenId, bytes32 preImage) public isOwner { try IERC721(nftAddress).tokenPayload(_tokenId) returns (string memory) { revert('NFT Exists with this ID'); } catch { require(!_duplicatePremint(_for, _tokenId), 'Duplicate PreMint'); preMintCounts[_for] = preMintCounts[_for].add(1); preMints[_for][_tokenId] = PreMint(_payload, preImage); preMintsByIndex[_for][preMintCounts[_for]] = preMints[_for][_tokenId]; } } function _duplicatePremint(address _for, uint256 _tokenId) internal view returns (bool) { string memory data = preMints[_for][_tokenId].payload; bytes32 NULL = keccak256(bytes('')); return keccak256(bytes(data)) != NULL; } function deletePreMint(address _for, uint256 _tokenId) public isOwner { delete preMintsByIndex[_for][preMintCounts[_for]]; preMintCounts[_for] = preMintCounts[_for].sub(1); delete preMints[_for][_tokenId]; } function getPreMint(address _for, uint256 _tokenId) public view returns (PreMint memory) { return preMints[_for][_tokenId]; } function checkPreMintImage(string memory image, bytes32 preImage) public pure returns (bytes32, bytes32, bool) { bytes32 calculated = sha256(abi.encodePacked(image)); bytes32 preBytes = preImage; return (calculated, preBytes, calculated == preBytes); } function getPreMintCount(address _for) public view returns (uint length) { return preMintCounts[_for]; } function getPreMintByIndex(address _for, uint index) public view returns (PreMint memory) { return preMintsByIndex[_for][index]; } function toggleShouldBurn() public { shouldBurn = !shouldBurn; } /* Transfer with code */ function addWitness(address _witness) public isOwner { witnesses[_witness] = true; } function removeWitness(address _witness) public isOwner { witnesses[_witness] = false; } function getAddressFromSignature(uint256 _tokenId, uint256 _nonce, bytes memory signature) public view returns (address) { require(!usedNonces[_nonce]); bytes32 hash = keccak256(abi.encodePacked(concat(uintToStr(_tokenId), uintToStr(_nonce)))); address addressFromSig = recoverSigner(hash, signature); return addressFromSig; } function transferWithCode(uint256 _tokenId, string calldata code, address _to, uint256 _nonce, bytes memory signature) public payable { require(witnesses[getAddressFromSignature(_tokenId, _nonce, signature)], 'Not Witnessed'); IERC721 nftToken = IERC721(nftAddress); PreTransfer memory preTransfer = preTransfers[_tokenId]; require(preTransfer.preImage == sha256(abi.encodePacked(code)), 'Code does not match'); // Payload should match nftToken.transferFrom(preTransfer._from, _to, _tokenId); delete preTransfers[_tokenId]; delete preTransfersByIndex[_tokenId][preTransferCounts[_tokenId]]; preTransferCounts[_tokenId] = preTransferCounts[_tokenId].sub(1); usedNonces[_nonce] = true; } function addPreTransfer(uint256 _tokenId, bytes32 preImage) public { require(!_duplicatePretransfer(_tokenId), 'Duplicate PreTransfer'); preTransferCounts[_tokenId] = preTransferCounts[_tokenId].add(1); preTransfers[_tokenId] = PreTransfer("payload", preImage, msg.sender); preTransfersByIndex[_tokenId][preTransferCounts[_tokenId]] = preTransfers[_tokenId]; } function _duplicatePretransfer(uint256 _tokenId) internal view returns (bool) { string memory data = preTransfers[_tokenId].payload; bytes32 NULL = keccak256(bytes('')); return keccak256(bytes(data)) != NULL; } function deletePreTransfer(uint256 _tokenId) public { require(preTransfers[_tokenId]._from == msg.sender, 'PreTransfer does not belong to sender'); delete preTransfersByIndex[_tokenId][preTransferCounts[_tokenId]]; preTransferCounts[_tokenId] = preTransferCounts[_tokenId].sub(1); delete preTransfers[_tokenId]; } function getPreTransfer(uint256 _tokenId) public view returns (PreTransfer memory) { return preTransfers[_tokenId]; } function checkPreTransferImage(string memory image, bytes32 preImage) public pure returns (bytes32, bytes32, bool) { bytes32 calculated = sha256(abi.encodePacked(image)); bytes32 preBytes = preImage; return (calculated, preBytes, calculated == preBytes); } function getPreTransferCount(uint256 _tokenId) public view returns (uint length) { return preTransferCounts[_tokenId]; } function getPreTransferByIndex(uint256 _tokenId, uint index) public view returns (PreTransfer memory) { return preTransfersByIndex[_tokenId][index]; } /* Swap */ function acceptOffer(uint _tokenId, uint index) public { Offer memory _offer = offers[_tokenId][index]; IERC721 nftToken = IERC721(nftAddress); IERC20Token couponToken = IERC20Token(couponAddress); require(nftToken.ownerOf(_tokenId) == msg.sender,'Sender is not owner of NFT'); require(nftToken.ownerOf(_offer.tokenId) == _offer._from, 'NFT not owned by offerer'); require(nftToken.getApproved(_offer.tokenId) == address(this), 'Handler unable to transfer offer NFT'); require(nftToken.getApproved(_tokenId) == address(this), 'Handler unable to transfer NFT'); if (offerPrice > 0 && payToAcceptOffer) { require(couponToken.allowance(msg.sender, address(this)) >= offerPrice, 'Handler unable take payment for offer'); require(couponToken.balanceOf(msg.sender) >= offerPrice, 'Insufficient Balance for payment'); require(couponToken.transferFrom(msg.sender, paymentAddress, offerPrice), 'Payment error'); } nftToken.safeTransferFrom(_offer._from, msg.sender, _offer.tokenId); nftToken.safeTransferFrom(msg.sender, _offer._from, _tokenId); delete offers[_tokenId][index]; delete offered[_offer._from][_tokenId]; } function addOffer(uint256 _tokenId, uint256 _for) public { IERC721 nftToken = IERC721(nftAddress); IERC20Token couponToken = IERC20Token(couponAddress); require(nftToken.ownerOf(_tokenId) == msg.sender, 'Sender not owner of NFT'); require(nftToken.getApproved(_tokenId) == address(this), 'Handler unable to transfer NFT'); if (offerPrice > 0 && payToMakeOffer) { require(couponToken.allowance(msg.sender, address(this)) >= offerPrice, 'Handler unable take payment for offer'); require(couponToken.balanceOf(msg.sender) >= offerPrice, 'Insufficient Balance for payment'); require(couponToken.transferFrom(msg.sender, paymentAddress, offerPrice), 'Payment error'); } offers[_for].push(Offer(_tokenId, msg.sender)); offered[msg.sender][_tokenId] = Offer(_tokenId, msg.sender); } function rejectOffer(uint256 _tokenId, uint index) public { Offer memory _offer = offers[_tokenId][index]; IERC721 nftToken = IERC721(nftAddress); require(nftToken.ownerOf(_tokenId) == msg.sender,'Sender is not owner of NFT'); rejected[_tokenId].push(_offer); delete offers[_tokenId][index]; delete offered[_offer._from][_tokenId]; } function withdrawOffer(uint256 _tokenId, uint index) public { Offer memory _offer = offers[_tokenId][index]; IERC721 nftToken = IERC721(nftAddress); require(nftToken.ownerOf(_offer.tokenId) == msg.sender,'Sender is not owner of offer NFT'); delete offers[_tokenId][index]; delete offered[_offer._from][_tokenId]; } function togglePayToMakeOffer() public isOwner { payToMakeOffer = !payToMakeOffer; } function togglePayToAcceptOffer() public isOwner { payToAcceptOffer = !payToAcceptOffer; } function getOffer(uint256 _tokenId, uint index) public view returns (Offer memory) { return offers[_tokenId][index]; } function getOfferCount(uint256 _tokenId) public view returns (uint) { return offers[_tokenId].length; } function changeMetadataBaseUri(string calldata _uri) public isOwner { metadataBaseUri = _uri; } function transferPaymentOwnership(address newOwner) external isOwner { Ownable paymentToken = Ownable(paymentAddress); paymentToken.transferOwnership(newOwner); } function transferNftOwnership(address newOwner) external isOwner { Ownable nftToken = Ownable(nftAddress); nftToken.transferOwnership(newOwner); } function mint( address _to, uint256 _tokenId, string calldata _uri, string calldata _payload) external isOwner { IERC721 nftToken = IERC721(nftAddress); nftToken.mint(_to, _tokenId, _uri, _payload); } function changeName(string calldata name, string calldata symbol) external isOwner { IERC721 nftToken = IERC721(nftAddress); nftToken.changeName(name, symbol); } function updateTokenUri(uint256 _tokenId,string memory _uri) external isOwner { IERC721 nftToken = IERC721(nftAddress); nftToken.updateTokenUri(_tokenId, _uri); } function getPaymentDecimals() public view returns (uint8){ BasicERC20 token = BasicERC20(paymentAddress); return token.decimals(); } function changePayment(address payment) public isOwner { paymentAddress = payment; } function changeCoupon(address coupon) public isOwner { couponAddress = coupon; } function changeRecipient(address _recipient) public isOwner { recipientAddress = _recipient; } function changeNft(address token) public isOwner { nftAddress = token; } function changePrice(uint256 _price) public isOwner { uint decimals = BasicERC20(paymentAddress).decimals(); price = _price * 10 ** decimals; } function changeOfferPrice(uint256 _price) public isOwner { uint decimals = BasicERC20(couponAddress).decimals(); offerPrice = _price * 10 ** decimals; } function concat(string memory a, string memory b) internal pure returns (string memory) { return string(abi.encodePacked(a, b)); } /** * @dev Recover signer address from a message by using their signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param sig bytes signature, the signature is generated using web3.eth.sign(). Inclusive "0x..." */ function recoverSigner(bytes32 hash, bytes memory sig) public pure returns (address) { require(sig.length == 65, "Require correct length"); bytes32 r; bytes32 s; uint8 v; // Divide the signature in r, s and v variables assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } require(v == 27 || v == 28, "Signature version not match"); return recoverSigner2(hash, v, r, s); } function recoverSigner2(bytes32 h, uint8 v, bytes32 r, bytes32 s) public pure returns (address) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, h)); address addr = ecrecover(prefixedHash, v, r, s); return addr; } /// @notice converts number to string /// @dev source: https://github.com/provable-things/ethereum-api/blob/master/oraclizeAPI_0.5.sol#L1045 /// @param _i integer to convert /// @return _uintAsString function uintToStr(uint _i) internal pure returns (string memory _uintAsString) { uint number = _i; if (number == 0) { return "0"; } uint j = number; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (number != 0) { bstr[k--] = byte(uint8(48 + number % 10)); number /= 10; } return string(bstr); } 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 bytes32ToStr(bytes32 _bytes32) public pure returns (string memory) { // string memory str = string(_bytes32); // TypeError: Explicit type conversion not allowed from "bytes32" to "string storage pointer" // thus we should fist convert bytes32 to bytes (to dynamically-sized byte array) bytes memory bytesArray = new bytes(32); for (uint256 i; i < 32; i++) { bytesArray[i] = _bytes32[i]; } return string(bytesArray); } }
Payload should match
require(preTransfer.preImage == sha256(abi.encodePacked(code)), 'Code does not match');
1,970,056
[ 1, 6110, 1410, 845, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 12, 1484, 5912, 18, 1484, 2040, 422, 6056, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 710, 13, 3631, 296, 1085, 1552, 486, 845, 8284, 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 ]
//Address: 0x44eaac6d56b347f58e56927005339a22af4ec4b5 //Contract name: DTCC_ILOW_4 //Balance: 0 Ether //Verification Date: 4/24/2018 //Transacion Count: 11 // CODE STARTS HERE pragma solidity ^0.4.21 ; interface IERC20Token { function totalSupply() public constant returns (uint); function balanceOf(address tokenlender) public constant returns (uint balance); function allowance(address tokenlender, 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 tokenlender, address indexed spender, uint tokens); } contract DTCC_ILOW_4 { address owner ; function DTCC_ILOW_4 () public { owner = msg.sender; } modifier onlyOwner () { require(msg.sender == owner ); _; } // IN DATA / SET DATA / GET DATA / UINT 256 / PUBLIC / ONLY OWNER / CONSTANT uint256 inData_1 = 1000 ; function setData_1 ( uint256 newData_1 ) public onlyOwner { inData_1 = newData_1 ; } function getData_1 () public constant returns ( uint256 ) { return inData_1 ; } // IN DATA / SET DATA / GET DATA / UINT 256 / PUBLIC / ONLY OWNER / CONSTANT uint256 inData_2 = 1000 ; function setData_2 ( uint256 newData_2 ) public onlyOwner { inData_2 = newData_2 ; } function getData_2 () public constant returns ( uint256 ) { return inData_2 ; } // IN DATA / SET DATA / GET DATA / UINT 256 / PUBLIC / ONLY OWNER / CONSTANT uint256 inData_3 = 1000 ; function setData_3 ( uint256 newData_3 ) public onlyOwner { inData_3 = newData_3 ; } function getData_3 () public constant returns ( uint256 ) { return inData_3 ; } // IN DATA / SET DATA / GET DATA / UINT 256 / PUBLIC / ONLY OWNER / CONSTANT uint256 inData_4 = 1000 ; function setData_4 ( uint256 newData_4 ) public onlyOwner { inData_4 = newData_4 ; } function getData_4 () public constant returns ( uint256 ) { return inData_4 ; } // IN DATA / SET DATA / GET DATA / UINT 256 / PUBLIC / ONLY OWNER / CONSTANT uint256 inData_5 = 1000 ; function setData_5 ( uint256 newData_5 ) public onlyOwner { inData_5 = newData_5 ; } function getData_5 () public constant returns ( uint256 ) { return inData_5 ; } // IN DATA / SET DATA / GET DATA / UINT 256 / PUBLIC / ONLY OWNER / CONSTANT uint256 inData_6 = 1000 ; function setData_6 ( uint256 newData_6 ) public onlyOwner { inData_6 = newData_6 ; } function getData_6 () public constant returns ( uint256 ) { return inData_6 ; } address public User_1 = msg.sender ; address public User_2 ;// _User_2 ; address public User_3 ;// _User_3 ; address public User_4 ;// _User_4 ; address public User_5 ;// _User_5 ; IERC20Token public Token_1 ;// _Token_1 ; IERC20Token public Token_2 ;// _Token_2 ; IERC20Token public Token_3 ;// _Token_3 ; IERC20Token public Token_4 ;// _Token_4 ; IERC20Token public Token_5 ;// _Token_5 ; uint256 public retraitStandard_1 ;// _retraitStandard_1 ; uint256 public retraitStandard_2 ;// _retraitStandard_2 ; uint256 public retraitStandard_3 ;// _retraitStandard_3 ; uint256 public retraitStandard_4 ;// _retraitStandard_4 ; uint256 public retraitStandard_5 ;// _retraitStandard_5 ; function admiss_1 ( address _User_1 , IERC20Token _Token_1 , uint256 _retraitStandard_1 ) public onlyOwner { User_1 = _User_1 ; Token_1 = _Token_1 ; retraitStandard_1 = _retraitStandard_1 ; } function admiss_2 ( address _User_2 , IERC20Token _Token_2 , uint256 _retraitStandard_2 ) public onlyOwner { User_2 = _User_2 ; Token_2 = _Token_2 ; retraitStandard_2 = _retraitStandard_2 ; } function admiss_3 ( address _User_3 , IERC20Token _Token_3 , uint256 _retraitStandard_3 ) public onlyOwner { User_3 = _User_3 ; Token_3 = _Token_3 ; retraitStandard_3 = _retraitStandard_3 ; } function admiss_4 ( address _User_4 , IERC20Token _Token_4 , uint256 _retraitStandard_4 ) public onlyOwner { User_4 = _User_4 ; Token_4 = _Token_4 ; retraitStandard_4 = _retraitStandard_4 ; } function admiss_5 ( address _User_5 , IERC20Token _Token_5 , uint256 _retraitStandard_5 ) public onlyOwner { User_5 = _User_5 ; Token_5 = _Token_5 ; retraitStandard_5 = _retraitStandard_5 ; } // // function retrait_1 () public { require( msg.sender == User_1 ); require( Token_1.transfer(User_1, retraitStandard_1) ); require( inData_1 == inData_2 ); require( inData_3 == inData_4 ); require( inData_5 == inData_6 ); } function retrait_2 () public { require( msg.sender == User_2 ); require( Token_2.transfer(User_2, retraitStandard_2) ); require( inData_1 == inData_2 ); require( inData_3 == inData_4 ); require( inData_5 == inData_6 ); } function retrait_3 () public { require( msg.sender == User_3 ); require( Token_3.transfer(User_3, retraitStandard_3) ); require( inData_1 == inData_2 ); require( inData_3 == inData_4 ); require( inData_5 == inData_6 ); } function retrait_4 () public { require( msg.sender == User_4 ); require( Token_4.transfer(User_4, retraitStandard_4) ); require( inData_1 == inData_2 ); require( inData_3 == inData_4 ); require( inData_5 == inData_6 ); } function retrait_5 () public { require( msg.sender == User_5 ); require( Token_5.transfer(User_5, retraitStandard_5) ); require( inData_1 == inData_2 ); require( inData_3 == inData_4 ); require( inData_5 == inData_6 ); } }
_retraitStandard_2 ;
uint256 public retraitStandard_2 ;
1,038,407
[ 1, 67, 266, 22513, 8336, 67, 22, 9506, 202, 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 ]
[ 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, 202, 11890, 5034, 202, 482, 202, 266, 22513, 8336, 67, 22, 202, 202, 31, 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 ]
./partial_match/1/0x25eC2A8cD2C5E4a7Db2BB978da33B163eBDD4709/sources/DogeInu.sol
disable Transfer delay - cannot be reenabled
function dogeDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; }
2,739,689
[ 1, 8394, 12279, 4624, 300, 2780, 506, 283, 5745, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 302, 717, 73, 6763, 1435, 3903, 1338, 5541, 1135, 261, 6430, 13, 288, 203, 3639, 7412, 6763, 1526, 273, 629, 31, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.4.0 <0.6.0; contract Poll{ //model class for contestant// struct Contestant { uint id; string name; string genre; uint votes; } //mapping to fetch contestant details// mapping(uint => Contestant) public contestants; //list to hold a list of voters// mapping(address => bool) public votersList; //varialble to keep track of number of contestants - because of the way solidity work// uint public contestantsCount; //contructor for a Poll with contestants// constructor () public { addNewContestant('FRIENDS', 'Comedy'); addNewContestant('HIMYM', 'Comedy'); } //function to add a contestant// function addNewContestant (string memory _name, string memory _genre) private { //increament the value of contestantCount// contestantsCount ++; contestants[contestantsCount] = Contestant(contestantsCount, _name, _genre, 0); } //function to cast vote to a contestant and follow up with voetrs data// function castVote(uint _contestantId) public { // filter to block single user for multiple times // //user is not present in votersList require(!votersList[msg.sender], 'User has already voted'); //check id it's a valid contestant// require(_contestantId > 0 && _contestantId <= contestantsCount, 'Not a valid contestant'); //add vote count for the contestant// contestants[_contestantId].votes ++; //adding user to votersList// votersList[msg.sender] = true; } }
function to cast vote to a contestant and follow up with voetrs data filter to block single user for multiple times user is not present in votersListcheck id it's a valid contestantadd vote count for the contestantadding user to votersList
function castVote(uint _contestantId) public { require(!votersList[msg.sender], 'User has already voted'); require(_contestantId > 0 && _contestantId <= contestantsCount, 'Not a valid contestant'); contestants[_contestantId].votes ++; votersList[msg.sender] = true; }
2,536,999
[ 1, 915, 358, 4812, 12501, 358, 279, 466, 395, 970, 471, 2805, 731, 598, 19993, 278, 5453, 501, 1034, 358, 1203, 2202, 729, 364, 3229, 4124, 729, 353, 486, 3430, 316, 331, 352, 414, 682, 1893, 612, 518, 1807, 279, 923, 466, 395, 970, 1289, 12501, 1056, 364, 326, 466, 395, 970, 3439, 729, 358, 331, 352, 414, 682, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4812, 19338, 12, 11890, 389, 1213, 395, 970, 548, 13, 1071, 288, 203, 3639, 2583, 12, 5, 90, 352, 414, 682, 63, 3576, 18, 15330, 6487, 296, 1299, 711, 1818, 331, 16474, 8284, 203, 3639, 2583, 24899, 1213, 395, 970, 548, 405, 374, 597, 389, 1213, 395, 970, 548, 1648, 466, 395, 4388, 1380, 16, 296, 1248, 279, 923, 466, 395, 970, 8284, 203, 3639, 466, 395, 4388, 63, 67, 1213, 395, 970, 548, 8009, 27800, 965, 31, 203, 3639, 331, 352, 414, 682, 63, 3576, 18, 15330, 65, 273, 638, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xAC63f537964B0C98141BdD676c7AE12D5dE7788b/sources/contracts/token/TokenERC1155_OSRoyaltyFilter.sol
Token name Token symbol
{ using ECDSAUpgradeable for bytes32; using StringsUpgradeable for uint256; bytes32 private constant MODULE_TYPE = bytes32("TokenERC1155"); uint256 private constant VERSION = 1; string public name; string public symbol; bytes32 private constant TYPEHASH = keccak256( "MintRequest(address to,address royaltyRecipient,uint256 royaltyBps,address primarySaleRecipient,uint256 tokenId,string uri,uint256 quantity,uint256 pricePerToken,address currency,uint128 validityStartTimestamp,uint128 validityEndTimestamp,bytes32 uid)" ); bytes32 private constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE"); bytes32 private constant MINTER_ROLE = keccak256("MINTER_ROLE"); uint256 private constant MAX_BPS = 10_000; address private _owner; uint256 public nextTokenIdToMint; address public primarySaleRecipient; address public platformFeeRecipient; address private royaltyRecipient; uint128 private royaltyBps; uint128 private platformFeeBps; string public contractURI; mapping(bytes32 => bool) private minted; mapping(uint256 => string) private _tokenURI; mapping(uint256 => uint256) public totalSupply; mapping(uint256 => address) public saleRecipientForToken; mapping(uint256 => RoyaltyInfo) private royaltyInfoForToken; function initialize( address _defaultAdmin, string memory _name, string memory _symbol, string memory _contractURI, address[] memory _trustedForwarders, address _primarySaleRecipient, address _royaltyRecipient, uint128 _royaltyBps, uint128 _platformFeeBps, address _platformFeeRecipient pragma solidity ^0.8.11; import { ITokenERC1155 } from "@thirdweb-dev/contracts/interfaces/token/ITokenERC1155.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol"; import "operator-filter-registry/src/upgradeable/DefaultOperatorFiltererUpgradeable.sol"; constructor() initializer {} ) external initializer { __ReentrancyGuard_init(); __EIP712_init("TokenERC1155", "1"); __ERC2771Context_init(_trustedForwarders); __ERC1155_init(""); __DefaultOperatorFilterer_init(); name = _name; symbol = _symbol; royaltyRecipient = _royaltyRecipient; royaltyBps = _royaltyBps; platformFeeRecipient = _platformFeeRecipient; primarySaleRecipient = _primarySaleRecipient; contractURI = _contractURI; require(_platformFeeBps <= MAX_BPS, "exceeds MAX_BPS"); platformFeeBps = _platformFeeBps; _owner = _defaultAdmin; _setupRole(DEFAULT_ADMIN_ROLE, _defaultAdmin); _setupRole(MINTER_ROLE, _defaultAdmin); _setupRole(TRANSFER_ROLE, _defaultAdmin); _setupRole(TRANSFER_ROLE, address(0)); } function contractType() external pure returns (bytes32) { return MODULE_TYPE; } function contractVersion() external pure returns (uint8) { return uint8(VERSION); } function owner() public view returns (address) { return hasRole(DEFAULT_ADMIN_ROLE, _owner) ? _owner : address(0); } function verify(MintRequest calldata _req, bytes calldata _signature) public view returns (bool, address) { address signer = recoverAddress(_req, _signature); return (!minted[_req.uid] && hasRole(MINTER_ROLE, signer), signer); } function uri(uint256 _tokenId) public view override returns (string memory) { return _tokenURI[_tokenId]; } function mintTo( address _to, uint256 _tokenId, string calldata _uri, uint256 _amount ) external onlyRole(MINTER_ROLE) { uint256 tokenIdToMint; if (_tokenId == type(uint256).max) { tokenIdToMint = nextTokenIdToMint; nextTokenIdToMint += 1; require(_tokenId < nextTokenIdToMint, "invalid id"); tokenIdToMint = _tokenId; } } function mintTo( address _to, uint256 _tokenId, string calldata _uri, uint256 _amount ) external onlyRole(MINTER_ROLE) { uint256 tokenIdToMint; if (_tokenId == type(uint256).max) { tokenIdToMint = nextTokenIdToMint; nextTokenIdToMint += 1; require(_tokenId < nextTokenIdToMint, "invalid id"); tokenIdToMint = _tokenId; } } } else { _mintTo(_to, _uri, tokenIdToMint, _amount); function royaltyInfo( uint256 tokenId, uint256 salePrice ) external view virtual returns (address receiver, uint256 royaltyAmount) { (address recipient, uint256 bps) = getRoyaltyInfoForToken(tokenId); receiver = recipient; royaltyAmount = (salePrice * bps) / MAX_BPS; } function mintWithSignature(MintRequest calldata _req, bytes calldata _signature) external payable nonReentrant { address signer = verifyRequest(_req, _signature); address receiver = _req.to; uint256 tokenIdToMint; if (_req.tokenId == type(uint256).max) { tokenIdToMint = nextTokenIdToMint; nextTokenIdToMint += 1; require(_req.tokenId < nextTokenIdToMint, "invalid id"); tokenIdToMint = _req.tokenId; } if (_req.royaltyRecipient != address(0)) { royaltyInfoForToken[tokenIdToMint] = RoyaltyInfo({ recipient: _req.royaltyRecipient, bps: _req.royaltyBps }); } _mintTo(receiver, _req.uri, tokenIdToMint, _req.quantity); collectPrice(_req); emit TokensMintedWithSignature(signer, receiver, tokenIdToMint, _req); } function mintWithSignature(MintRequest calldata _req, bytes calldata _signature) external payable nonReentrant { address signer = verifyRequest(_req, _signature); address receiver = _req.to; uint256 tokenIdToMint; if (_req.tokenId == type(uint256).max) { tokenIdToMint = nextTokenIdToMint; nextTokenIdToMint += 1; require(_req.tokenId < nextTokenIdToMint, "invalid id"); tokenIdToMint = _req.tokenId; } if (_req.royaltyRecipient != address(0)) { royaltyInfoForToken[tokenIdToMint] = RoyaltyInfo({ recipient: _req.royaltyRecipient, bps: _req.royaltyBps }); } _mintTo(receiver, _req.uri, tokenIdToMint, _req.quantity); collectPrice(_req); emit TokensMintedWithSignature(signer, receiver, tokenIdToMint, _req); } } else { function mintWithSignature(MintRequest calldata _req, bytes calldata _signature) external payable nonReentrant { address signer = verifyRequest(_req, _signature); address receiver = _req.to; uint256 tokenIdToMint; if (_req.tokenId == type(uint256).max) { tokenIdToMint = nextTokenIdToMint; nextTokenIdToMint += 1; require(_req.tokenId < nextTokenIdToMint, "invalid id"); tokenIdToMint = _req.tokenId; } if (_req.royaltyRecipient != address(0)) { royaltyInfoForToken[tokenIdToMint] = RoyaltyInfo({ recipient: _req.royaltyRecipient, bps: _req.royaltyBps }); } _mintTo(receiver, _req.uri, tokenIdToMint, _req.quantity); collectPrice(_req); emit TokensMintedWithSignature(signer, receiver, tokenIdToMint, _req); } function mintWithSignature(MintRequest calldata _req, bytes calldata _signature) external payable nonReentrant { address signer = verifyRequest(_req, _signature); address receiver = _req.to; uint256 tokenIdToMint; if (_req.tokenId == type(uint256).max) { tokenIdToMint = nextTokenIdToMint; nextTokenIdToMint += 1; require(_req.tokenId < nextTokenIdToMint, "invalid id"); tokenIdToMint = _req.tokenId; } if (_req.royaltyRecipient != address(0)) { royaltyInfoForToken[tokenIdToMint] = RoyaltyInfo({ recipient: _req.royaltyRecipient, bps: _req.royaltyBps }); } _mintTo(receiver, _req.uri, tokenIdToMint, _req.quantity); collectPrice(_req); emit TokensMintedWithSignature(signer, receiver, tokenIdToMint, _req); } function setPrimarySaleRecipient(address _saleRecipient) external onlyRole(DEFAULT_ADMIN_ROLE) { primarySaleRecipient = _saleRecipient; emit PrimarySaleRecipientUpdated(_saleRecipient); } function setDefaultRoyaltyInfo( address _royaltyRecipient, uint256 _royaltyBps ) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_royaltyBps <= MAX_BPS, "exceed royalty bps"); royaltyRecipient = _royaltyRecipient; royaltyBps = uint128(_royaltyBps); emit DefaultRoyalty(_royaltyRecipient, _royaltyBps); } function setRoyaltyInfoForToken( uint256 _tokenId, address _recipient, uint256 _bps ) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_bps <= MAX_BPS, "exceed royalty bps"); emit RoyaltyForToken(_tokenId, _recipient, _bps); } royaltyInfoForToken[_tokenId] = RoyaltyInfo({ recipient: _recipient, bps: _bps }); function setPlatformFeeInfo( address _platformFeeRecipient, uint256 _platformFeeBps ) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_platformFeeBps <= MAX_BPS, "exceeds MAX_BPS"); platformFeeBps = uint64(_platformFeeBps); platformFeeRecipient = _platformFeeRecipient; emit PlatformFeeInfoUpdated(_platformFeeRecipient, _platformFeeBps); } function setOwner(address _newOwner) external onlyRole(DEFAULT_ADMIN_ROLE) { require(hasRole(DEFAULT_ADMIN_ROLE, _newOwner), "new owner not module admin."); address _prevOwner = _owner; _owner = _newOwner; emit OwnerUpdated(_prevOwner, _newOwner); } function setContractURI(string calldata _uri) external onlyRole(DEFAULT_ADMIN_ROLE) { contractURI = _uri; } function getPlatformFeeInfo() external view returns (address, uint16) { return (platformFeeRecipient, uint16(platformFeeBps)); } function getDefaultRoyaltyInfo() external view returns (address, uint16) { return (royaltyRecipient, uint16(royaltyBps)); } function getRoyaltyInfoForToken(uint256 _tokenId) public view returns (address, uint16) { RoyaltyInfo memory royaltyForToken = royaltyInfoForToken[_tokenId]; return royaltyForToken.recipient == address(0) ? (royaltyRecipient, uint16(royaltyBps)) : (royaltyForToken.recipient, uint16(royaltyForToken.bps)); } function _mintTo(address _to, string calldata _uri, uint256 _tokenId, uint256 _amount) internal { if (bytes(_tokenURI[_tokenId]).length == 0) { require(bytes(_uri).length > 0, "empty uri."); _tokenURI[_tokenId] = _uri; } _mint(_to, _tokenId, _amount, ""); emit TokensMinted(_to, _tokenId, _tokenURI[_tokenId], _amount); } function _mintTo(address _to, string calldata _uri, uint256 _tokenId, uint256 _amount) internal { if (bytes(_tokenURI[_tokenId]).length == 0) { require(bytes(_uri).length > 0, "empty uri."); _tokenURI[_tokenId] = _uri; } _mint(_to, _tokenId, _amount, ""); emit TokensMinted(_to, _tokenId, _tokenURI[_tokenId], _amount); } function recoverAddress(MintRequest calldata _req, bytes calldata _signature) internal view returns (address) { return _hashTypedDataV4(keccak256(_encodeRequest(_req))).recover(_signature); } function _encodeRequest(MintRequest calldata _req) internal pure returns (bytes memory) { return abi.encode( TYPEHASH, _req.to, _req.royaltyRecipient, _req.royaltyBps, _req.primarySaleRecipient, _req.tokenId, keccak256(bytes(_req.uri)), _req.quantity, _req.pricePerToken, _req.currency, _req.validityStartTimestamp, _req.validityEndTimestamp, _req.uid ); } function verifyRequest(MintRequest calldata _req, bytes calldata _signature) internal returns (address) { (bool success, address signer) = verify(_req, _signature); require(success, "invalid signature"); require( _req.validityStartTimestamp <= block.timestamp && _req.validityEndTimestamp >= block.timestamp, "request expired" ); require(_req.to != address(0), "recipient undefined"); require(_req.quantity > 0, "zero quantity"); minted[_req.uid] = true; return signer; } function collectPrice(MintRequest calldata _req) internal { if (_req.pricePerToken == 0) { return; } uint256 totalPrice = _req.pricePerToken * _req.quantity; uint256 platformFees = (totalPrice * platformFeeBps) / MAX_BPS; if (_req.currency == CurrencyTransferLib.NATIVE_TOKEN) { require(msg.value == totalPrice, "must send total price."); require(msg.value == 0, "msg value not zero"); } address saleRecipient = _req.primarySaleRecipient == address(0) ? primarySaleRecipient : _req.primarySaleRecipient; CurrencyTransferLib.transferCurrency(_req.currency, _msgSender(), platformFeeRecipient, platformFees); CurrencyTransferLib.transferCurrency(_req.currency, _msgSender(), saleRecipient, totalPrice - platformFees); } function collectPrice(MintRequest calldata _req) internal { if (_req.pricePerToken == 0) { return; } uint256 totalPrice = _req.pricePerToken * _req.quantity; uint256 platformFees = (totalPrice * platformFeeBps) / MAX_BPS; if (_req.currency == CurrencyTransferLib.NATIVE_TOKEN) { require(msg.value == totalPrice, "must send total price."); require(msg.value == 0, "msg value not zero"); } address saleRecipient = _req.primarySaleRecipient == address(0) ? primarySaleRecipient : _req.primarySaleRecipient; CurrencyTransferLib.transferCurrency(_req.currency, _msgSender(), platformFeeRecipient, platformFees); CurrencyTransferLib.transferCurrency(_req.currency, _msgSender(), saleRecipient, totalPrice - platformFees); } function collectPrice(MintRequest calldata _req) internal { if (_req.pricePerToken == 0) { return; } uint256 totalPrice = _req.pricePerToken * _req.quantity; uint256 platformFees = (totalPrice * platformFeeBps) / MAX_BPS; if (_req.currency == CurrencyTransferLib.NATIVE_TOKEN) { require(msg.value == totalPrice, "must send total price."); require(msg.value == 0, "msg value not zero"); } address saleRecipient = _req.primarySaleRecipient == address(0) ? primarySaleRecipient : _req.primarySaleRecipient; CurrencyTransferLib.transferCurrency(_req.currency, _msgSender(), platformFeeRecipient, platformFees); CurrencyTransferLib.transferCurrency(_req.currency, _msgSender(), saleRecipient, totalPrice - platformFees); } } else { function burn(address account, uint256 id, uint256 value) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved." ); _burn(account, id, value); } function burnBatch(address account, uint256[] memory ids, uint256[] memory values) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved." ); _burnBatch(account, ids, values); } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (!hasRole(TRANSFER_ROLE, address(0)) && from != address(0) && to != address(0)) { require(hasRole(TRANSFER_ROLE, from) || hasRole(TRANSFER_ROLE, to), "restricted to TRANSFER_ROLE holders."); } if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] -= amounts[i]; } } } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (!hasRole(TRANSFER_ROLE, address(0)) && from != address(0) && to != address(0)) { require(hasRole(TRANSFER_ROLE, from) || hasRole(TRANSFER_ROLE, to), "restricted to TRANSFER_ROLE holders."); } if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] -= amounts[i]; } } } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (!hasRole(TRANSFER_ROLE, address(0)) && from != address(0) && to != address(0)) { require(hasRole(TRANSFER_ROLE, from) || hasRole(TRANSFER_ROLE, to), "restricted to TRANSFER_ROLE holders."); } if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] -= amounts[i]; } } } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (!hasRole(TRANSFER_ROLE, address(0)) && from != address(0) && to != address(0)) { require(hasRole(TRANSFER_ROLE, from) || hasRole(TRANSFER_ROLE, to), "restricted to TRANSFER_ROLE holders."); } if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] -= amounts[i]; } } } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (!hasRole(TRANSFER_ROLE, address(0)) && from != address(0) && to != address(0)) { require(hasRole(TRANSFER_ROLE, from) || hasRole(TRANSFER_ROLE, to), "restricted to TRANSFER_ROLE holders."); } if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] -= amounts[i]; } } } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (!hasRole(TRANSFER_ROLE, address(0)) && from != address(0) && to != address(0)) { require(hasRole(TRANSFER_ROLE, from) || hasRole(TRANSFER_ROLE, to), "restricted to TRANSFER_ROLE holders."); } if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] -= amounts[i]; } } } function setApprovalForAll( address operator, bool approved ) public override(ERC1155Upgradeable, IERC1155Upgradeable) onlyAllowedOperatorApproval(operator) { super.setApprovalForAll(operator, approved); } function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public override(ERC1155Upgradeable, IERC1155Upgradeable) onlyAllowedOperator(from) { super.safeTransferFrom(from, to, id, amount, data); } function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public override(ERC1155Upgradeable, IERC1155Upgradeable) onlyAllowedOperator(from) { super.safeBatchTransferFrom(from, to, ids, amounts, data); } function supportsInterface( bytes4 interfaceId ) public view virtual override(AccessControlEnumerableUpgradeable, ERC1155Upgradeable, IERC165Upgradeable, IERC165) returns (bool) { return super.supportsInterface(interfaceId) || interfaceId == type(IERC1155Upgradeable).interfaceId || interfaceId == type(IERC2981Upgradeable).interfaceId; } function _msgSender() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (address sender) { return ERC2771ContextUpgradeable._msgSender(); } function _msgData() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (bytes calldata) { return ERC2771ContextUpgradeable._msgData(); } }
5,577,779
[ 1, 1345, 508, 3155, 3273, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 95, 203, 565, 1450, 7773, 19748, 10784, 429, 364, 1731, 1578, 31, 203, 565, 1450, 8139, 10784, 429, 364, 2254, 5034, 31, 203, 203, 565, 1731, 1578, 3238, 5381, 14057, 67, 2399, 273, 1731, 1578, 2932, 1345, 654, 39, 2499, 2539, 8863, 203, 565, 2254, 5034, 3238, 5381, 8456, 273, 404, 31, 203, 203, 565, 533, 1071, 508, 31, 203, 203, 565, 533, 1071, 3273, 31, 203, 203, 565, 1731, 1578, 3238, 5381, 3463, 15920, 273, 203, 3639, 417, 24410, 581, 5034, 12, 203, 5411, 315, 49, 474, 691, 12, 2867, 358, 16, 2867, 721, 93, 15006, 18241, 16, 11890, 5034, 721, 93, 15006, 38, 1121, 16, 2867, 3354, 30746, 18241, 16, 11890, 5034, 1147, 548, 16, 1080, 2003, 16, 11890, 5034, 10457, 16, 11890, 5034, 6205, 2173, 1345, 16, 2867, 5462, 16, 11890, 10392, 13800, 1685, 4921, 16, 11890, 10392, 13800, 1638, 4921, 16, 3890, 1578, 4555, 2225, 203, 3639, 11272, 203, 203, 565, 1731, 1578, 3238, 5381, 4235, 17598, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 16596, 6553, 67, 16256, 8863, 203, 565, 1731, 1578, 3238, 5381, 6989, 2560, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 6236, 2560, 67, 16256, 8863, 203, 203, 565, 2254, 5034, 3238, 5381, 4552, 67, 38, 5857, 273, 1728, 67, 3784, 31, 203, 203, 565, 1758, 3238, 389, 8443, 31, 203, 203, 565, 2254, 5034, 1071, 9617, 28803, 49, 474, 31, 203, 203, 565, 1758, 1071, 3354, 30746, 18241, 31, 203, 203, 565, 1758, 1071, 4072, 14667, 18241, 31, 203, 203, 565, 1758, 3238, 721, 2 ]
./full_match/1/0x9bC228711706db212ED2BC12d9dC1643cf304EEA/sources/lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement on the return value: the return value is optional (but if data is returned, it must not be false). @param token The token targeted by the call. @param data The call data (encoded using abi.encode or one of its variants). This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead./ 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 cannot use {Address-functionCall} here since this should return false and not revert is the subcall reverts.
function _callOptionalReturnBool(IERC20Upgradeable token, bytes memory data) private returns (bool) { (bool success, bytes memory returndata) = address(token).call(data); return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0; }
8,424,069
[ 1, 1170, 305, 815, 279, 348, 7953, 560, 3551, 17, 2815, 745, 261, 77, 18, 73, 18, 279, 6736, 445, 745, 358, 279, 6835, 3631, 25744, 310, 326, 12405, 603, 326, 327, 460, 30, 326, 327, 460, 353, 3129, 261, 12885, 309, 501, 353, 2106, 16, 518, 1297, 486, 506, 629, 2934, 225, 1147, 1021, 1147, 20715, 635, 326, 745, 18, 225, 501, 1021, 745, 501, 261, 10787, 1450, 24126, 18, 3015, 578, 1245, 434, 2097, 12935, 2934, 1220, 353, 279, 5437, 434, 288, 67, 1991, 6542, 990, 97, 716, 17714, 4877, 1044, 281, 777, 15226, 87, 471, 1135, 279, 1426, 3560, 18, 19, 1660, 1608, 358, 3073, 279, 4587, 1801, 745, 2674, 16, 358, 17587, 348, 7953, 560, 1807, 327, 501, 963, 6728, 12860, 16, 3241, 732, 4565, 19981, 518, 19801, 18, 1660, 2780, 999, 288, 1887, 17, 915, 1477, 97, 2674, 3241, 333, 1410, 327, 629, 471, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 389, 1991, 6542, 990, 7464, 12, 45, 654, 39, 3462, 10784, 429, 1147, 16, 1731, 3778, 501, 13, 3238, 1135, 261, 6430, 13, 288, 203, 203, 3639, 261, 6430, 2216, 16, 1731, 3778, 327, 892, 13, 273, 1758, 12, 2316, 2934, 1991, 12, 892, 1769, 203, 3639, 327, 2216, 597, 261, 2463, 892, 18, 2469, 422, 374, 747, 24126, 18, 3922, 12, 2463, 892, 16, 261, 6430, 20349, 597, 1758, 12, 2316, 2934, 710, 18, 2469, 405, 374, 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 ]
./partial_match/3/0xD1958E0e29196A0D198D391B97648Ae8fDCa9e71/sources/Escrow.sol
solhint-disable-line
function () public {
5,280,484
[ 1, 18281, 11317, 17, 8394, 17, 1369, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1832, 1071, 288, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x77fB32743eDF3FefEA422cF71dA22c2594F75663/sources/SaffronERC20StakingPool.sol
Update state for removal via dsec token Get info about the v1 dsec token from its address and check that it exists Token epoch must be a past epoch Dsec gives user claim over a tranche's earned SFI and interest Update state for removal via principal token Get info about the v1 dsec token from its address and check that it exists Token epoch must be a past epoch Transfer
function remove_liquidity(address dsec_token_address, uint256 dsec_amount, address principal_token_address, uint256 principal_amount) external override { require(dsec_amount > 0 || principal_amount > 0, "can't remove 0"); uint256 SFI_owned; uint256 dsec_percent; if (dsec_token_address != address(0x0) && dsec_amount > 0) { SaffronLPTokenInfo memory token_info = saffron_LP_token_info[dsec_token_address]; require(token_info.exists, "balance token lookup failed"); SaffronLPBalanceToken sbt = SaffronLPBalanceToken(dsec_token_address); require(sbt.balanceOf(msg.sender) >= dsec_amount, "insufficient dsec balance"); uint256 token_epoch = token_info.epoch; require(token_info.token_type == LPTokenType.dsec, "bad dsec address"); require(token_epoch == 16, "v1.16: bal token epoch must be 16"); require(epoch_wound_down[token_epoch], "can't remove from wound up epoch"); dsec_percent = dsec_amount.mul(1 ether).div(total_dsec[token_epoch]); SFI_owned = SFI_earned[token_epoch].mul(dsec_percent) / 1 ether; SFI_earned[token_epoch] = SFI_earned[token_epoch].sub(SFI_owned); total_dsec[token_epoch] = total_dsec[token_epoch].sub(dsec_amount); } if (principal_token_address != address(0x0) && principal_amount > 0) { SaffronLPTokenInfo memory token_info = saffron_LP_token_info[principal_token_address]; require(token_info.exists, "balance token info lookup failed"); SaffronLPBalanceToken sbt = SaffronLPBalanceToken(principal_token_address); require(sbt.balanceOf(msg.sender) >= principal_amount, "insufficient principal balance"); uint256 token_epoch = token_info.epoch; require(token_info.token_type == LPTokenType.principal, "bad balance token address"); require(token_epoch == 16, "v1.16: bal token epoch must be 16"); require(epoch_wound_down[token_epoch], "can't remove from wound up epoch"); epoch_principal[token_epoch] = epoch_principal[token_epoch].sub(principal_amount); pool_principal = pool_principal.sub(principal_amount); } if (dsec_token_address != address(0x0) && dsec_amount > 0) { SaffronLPBalanceToken sbt = SaffronLPBalanceToken(dsec_token_address); require(sbt.balanceOf(msg.sender) >= dsec_amount, "insufficient dsec balance"); sbt.burn(msg.sender, dsec_amount); IERC20(SFI_address).safeTransfer(msg.sender, SFI_owned); emit RemoveLiquidityDsec(dsec_percent, SFI_owned); } if (principal_token_address != address(0x0) && principal_amount > 0) { SaffronLPBalanceToken sbt = SaffronLPBalanceToken(principal_token_address); require(sbt.balanceOf(msg.sender) >= principal_amount, "insufficient principal balance"); sbt.burn(msg.sender, principal_amount); IERC20(base_asset_address).safeTransfer(msg.sender, principal_amount); emit RemoveLiquidityPrincipal(principal_amount); } require((dsec_token_address != address(0x0) && dsec_amount > 0) || (principal_token_address != address(0x0) && principal_amount > 0), "no action performed"); }
2,702,027
[ 1, 1891, 919, 364, 14817, 3970, 302, 3321, 1147, 968, 1123, 2973, 326, 331, 21, 302, 3321, 1147, 628, 2097, 1758, 471, 866, 716, 518, 1704, 3155, 7632, 1297, 506, 279, 8854, 7632, 463, 3321, 14758, 729, 7516, 1879, 279, 13637, 18706, 1807, 425, 1303, 329, 348, 1653, 471, 16513, 2315, 919, 364, 14817, 3970, 8897, 1147, 968, 1123, 2973, 326, 331, 21, 302, 3321, 1147, 628, 2097, 1758, 471, 866, 716, 518, 1704, 3155, 7632, 1297, 506, 279, 8854, 7632, 12279, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1206, 67, 549, 372, 24237, 12, 2867, 302, 3321, 67, 2316, 67, 2867, 16, 2254, 5034, 302, 3321, 67, 8949, 16, 1758, 8897, 67, 2316, 67, 2867, 16, 2254, 5034, 8897, 67, 8949, 13, 3903, 3849, 288, 203, 565, 2583, 12, 72, 3321, 67, 8949, 405, 374, 747, 8897, 67, 8949, 405, 374, 16, 315, 4169, 1404, 1206, 374, 8863, 203, 565, 2254, 5034, 348, 1653, 67, 995, 329, 31, 203, 565, 2254, 5034, 302, 3321, 67, 8849, 31, 203, 203, 565, 309, 261, 72, 3321, 67, 2316, 67, 2867, 480, 1758, 12, 20, 92, 20, 13, 597, 302, 3321, 67, 8949, 405, 374, 13, 288, 203, 1377, 348, 7329, 1949, 14461, 1345, 966, 3778, 1147, 67, 1376, 273, 272, 7329, 1949, 67, 14461, 67, 2316, 67, 1376, 63, 72, 3321, 67, 2316, 67, 2867, 15533, 203, 1377, 2583, 12, 2316, 67, 1376, 18, 1808, 16, 315, 12296, 1147, 3689, 2535, 8863, 203, 1377, 348, 7329, 1949, 14461, 13937, 1345, 2393, 88, 273, 348, 7329, 1949, 14461, 13937, 1345, 12, 72, 3321, 67, 2316, 67, 2867, 1769, 203, 1377, 2583, 12, 18366, 88, 18, 12296, 951, 12, 3576, 18, 15330, 13, 1545, 302, 3321, 67, 8949, 16, 315, 2679, 11339, 302, 3321, 11013, 8863, 203, 203, 1377, 2254, 5034, 1147, 67, 12015, 273, 1147, 67, 1376, 18, 12015, 31, 203, 1377, 2583, 12, 2316, 67, 1376, 18, 2316, 67, 723, 422, 511, 52, 28675, 18, 72, 3321, 16, 315, 8759, 302, 3321, 1758, 8863, 203, 1377, 2583, 12, 2316, 67, 12015, 422, 2 ]
pragma solidity ^0.5.6; // It's important to avoid vulnerabilities due to numeric overflow bugs // OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs // More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/ import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; /************************************************** */ /* FlightSurety Smart Contract */ /************************************************** */ contract FlightSuretyApp { using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript) /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ // Flight status codees uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; uint256 public constant INSURANCE_COST = 1 ether; uint256 private constant INSURANCE_MULTIPLIER = 150; uint256 public constant AIRLINE_FUNDING_VALUE = 10 ether; uint256 private constant MULTIPARTY_MINMUM_AIRLINES = 4; uint256 private constant MULTIPARTY_CONSENSUS_DIVIDER = 2; mapping(address => address[]) private airlineMultiCallers; address private contractOwner; // Account used to deploy contract FlightSuretyData flightSuretyData; // Contract Data /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { // Modify to call data contract's status require(isOperational(), "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } modifier requireRegisteredAirline(address airline) { require(flightSuretyData.hasAirlineRegistered(airline), "Sender is not registered airline"); _; } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier paidEnough(uint256 value) { require(msg.value >= value, "Insufficient value"); _; } modifier checkValue(uint256 amount) { _; uint amountToReturn = msg.value - amount; msg.sender.transfer(amountToReturn); } modifier airlineIsFunded(address airline) { require(flightSuretyData.hasAirlineFunded(airline), "Airline is not funded!"); _; } modifier airlineIsNotRegistered(address airline) { require(!flightSuretyData.hasAirlineRegistered(airline), "Airline has already registered!"); _; } modifier passengerIsNotInsured(bytes32 flightKey, address passenger) { require(!flightSuretyData.isPassengerInsured(flightKey, passenger), "Passenger is already insured for flight"); _; } modifier flightIsNotRegistered(bytes32 flightKey) { require(!flightSuretyData.hasFlightRegistered(flightKey), "Flight is already registered!"); _; } modifier flightIsRegistered(bytes32 flightKey) { require(flightSuretyData.hasFlightRegistered(flightKey), "Flight is not registered!"); _; } modifier flightIsNotLanded(bytes32 flightKey) { require(!flightSuretyData.hasFlightLanded(flightKey)); _; } /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Contract constructor * */ constructor(address contractAddress) public { contractOwner = msg.sender; flightSuretyData = FlightSuretyData(contractAddress); } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ function isOperational() public view returns (bool) { return flightSuretyData.isOperational(); // Modify to call data contract's status } function isFlightRegistered(address airline, string memory flight, string memory timestamp) public view returns (bool) { bytes32 flightKey = getFlightKey(airline, flight, timestamp); return flightSuretyData.hasFlightRegistered(flightKey); } function isPassengerInsuredForFlight(address airline, string memory flight, string memory timestamp, address passenger) public view returns (bool) { bytes32 flightKey = getFlightKey(airline, flight, timestamp); return flightSuretyData.isPassengerInsured(flightKey, passenger); } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * */ function getUintAddress() public view returns (address) { return address(uint160(address(flightSuretyData))); } function fundAirline() external payable requireIsOperational requireRegisteredAirline(msg.sender) paidEnough(AIRLINE_FUNDING_VALUE) checkValue(AIRLINE_FUNDING_VALUE) { flightSuretyData.fundAirline(msg.sender); } function getRegisteredAirlines() public view returns (uint256) { return flightSuretyData.getRegisteredAirlines(); } function registerAirline(address airline) external requireIsOperational() airlineIsFunded(msg.sender) airlineIsNotRegistered(airline) returns (bool success, uint256 votes) { if (getRegisteredAirlines() < MULTIPARTY_MINMUM_AIRLINES) { flightSuretyData.registerAirline(airline, msg.sender); airlineMultiCallers[airline] = [msg.sender]; return (success, airlineMultiCallers[airline].length); } else { bool isDuplicate = false; for (uint c = 0; c < airlineMultiCallers[airline].length; c ++) { if (airlineMultiCallers[airline][c] == msg.sender) { isDuplicate = true; break; } } require(!isDuplicate, "Voting airline has already submitted vote for this new airline"); airlineMultiCallers[airline].push(msg.sender); if (airlineMultiCallers[airline].length >= getRegisteredAirlines().div(MULTIPARTY_CONSENSUS_DIVIDER)) { flightSuretyData.registerAirline(airline, msg.sender); return (success, airlineMultiCallers[airline].length); } return (false, airlineMultiCallers[airline].length); } } function registerFlight(string calldata flight, string calldata timestamp, string calldata departure, string calldata destination) external requireIsOperational airlineIsFunded(msg.sender) flightIsNotRegistered(getFlightKey(msg.sender, flight, timestamp)) { bytes32 flightKey = getFlightKey(msg.sender, flight, timestamp); flightSuretyData.registerFlight(flightKey, msg.sender, flight, timestamp, departure, destination); } function buyInsurance(address airline, string calldata flight, string calldata timestamp, bytes32 flightKey) external payable requireIsOperational() flightIsRegistered(flightKey) flightIsNotLanded(flightKey) passengerIsNotInsured(flightKey, msg.sender) paidEnough(INSURANCE_COST) checkValue(INSURANCE_COST) { uint256 amount = msg.value; flightSuretyData.buy(getFlightKey(airline, flight, timestamp), msg.sender, amount, INSURANCE_MULTIPLIER); } function processFlightStatus(address airline, string memory flight, string memory timestamp, uint8 statusCode) internal { bytes32 flightKey = getFlightKey(airline, flight, timestamp); flightSuretyData.updateFlightStatus(flightKey, statusCode); } function pay() public requireIsOperational { flightSuretyData.pay(address(uint160(address(msg.sender)))); } function fetchFlightStatus(address airline, string calldata flight, string calldata timestamp) external { uint8 index = getRandomIndex(msg.sender); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); oracleResponses[key] = ResponseInfo ({ requester: msg.sender, isOpen: true }); emit OracleRequest(index, airline, flight, timestamp); } // region ORACLE MANAGEMENT // Incremented to add pseudo-randomness at various points uint8 private nonce = 0; // Fee to be paid when registering oracle uint256 public constant REGISTRATION_FEE = 1 ether; // Number of oracles that must respond for valid status uint256 private constant MIN_RESPONSES = 3; struct Oracle { bool isRegistered; uint8[3] indexes; } // Track all registered oracles mapping(address => Oracle) private oracles; // Model for responses from oracles struct ResponseInfo { address requester; // Account that requested status bool isOpen; // If open, oracle responses are accepted mapping(uint8 => address[]) responses; // Mapping key is the status code reported // This lets us group responses and identify // the response that majority of the oracles } // Track all oracle responses // Key = hash(index, flight, timestamp) mapping(bytes32 => ResponseInfo) private oracleResponses; // Event fired each time an oracle submits a response event FlightStatusInfo(address airline, string flight, string timestamp, uint8 status); event OracleReport(address airline, string flight, string timestamp, uint8 status); // Event fired when flight status request is submitted // Oracles track this and if they have a matching index // they fetch data and submit a response event OracleRequest(uint8 index, address airline, string flight, string timestamp); // Register an oracle with the contract function registerOracle() external payable { // Require registration fee require(msg.value >= REGISTRATION_FEE, "Registration fee is required"); uint8[3] memory indexes = generateIndexes(msg.sender); oracles[msg.sender] = Oracle({ isRegistered: true, indexes: indexes }); } function getMyIndexes() view external returns(uint8[3] memory) { require(oracles[msg.sender].isRegistered, "Not registered as an oracle"); return oracles[msg.sender].indexes; } // Called by oracle when a response is available to an outstanding request // For the response to be accepted, there must be a pending request that is open // and matches one of the three Indexes randomly assigned to the oracle at the // time of registration (i.e. uninvited oracles are not welcome) function submitOracleResponse(uint8 index, address airline, string calldata flight, string calldata timestamp, uint8 statusCode) external { require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request"); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request"); oracleResponses[key].responses[statusCode].push(msg.sender); // Information isn't considered verified until at least MIN_RESPONSES // oracles respond with the *** same *** information emit OracleReport(airline, flight, timestamp, statusCode); if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) { emit FlightStatusInfo(airline, flight, timestamp, statusCode); // Handle flight status as appropriate processFlightStatus(airline, flight, timestamp, statusCode); } } function getFlightKey(address airline, string memory flight, string memory timestamp) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } // Returns array of three non-duplicating integers from 0-9 function generateIndexes(address account) internal returns(uint8[3] memory) { uint8[3] memory indexes; indexes[0] = getRandomIndex(account); indexes[1] = indexes[0]; while(indexes[1] == indexes[0]) { indexes[1] = getRandomIndex(account); } indexes[2] = indexes[1]; while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = getRandomIndex(account); } return indexes; } // Returns array of three non-duplicating integers from 0-9 function getRandomIndex(address account) internal returns (uint8) { uint8 maxValue = 10; // Pseudo random number...the incrementing nonce adds variation uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue); if (nonce > 250) { nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt } return random; } } contract FlightSuretyData { function isOperational() public view returns(bool); function hasAirlineFunded(address airline) external view returns (bool); function hasAirlineRegistered(address airline) external view returns (bool); function registerAirline(address newAirline, address registeredAirline) external; function fundAirline(address airline) payable external; function getRegisteredAirlines() public view returns (uint256); function isPassengerInsured(bytes32 flightKey, address passenger) external view returns (bool); function registerFlight(bytes32 flightKey, address airline, string calldata flight, string calldata timestamp, string calldata departure, string calldata destination) external; function hasFlightRegistered(bytes32 flightKey) public view returns (bool); function hasFlightLanded(bytes32 flightKey) public view returns (bool); function buy(bytes32 flightKey, address passenger, uint256 amount, uint256 multiplier) external payable; function updateFlightStatus(bytes32 flightKey, uint8 statusCode) external; function pay(address caller) external; }
* @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/ Modify to call data contract's status
modifier requireIsOperational() { require(isOperational(), "Contract is currently not operational"); }
12,890,428
[ 1, 9829, 716, 4991, 326, 315, 22716, 6, 1250, 2190, 358, 506, 315, 3767, 6, 1377, 1220, 353, 1399, 603, 777, 919, 12770, 4186, 358, 11722, 326, 6835, 316, 1377, 326, 871, 1915, 353, 392, 5672, 716, 4260, 358, 506, 5499, 19, 9518, 358, 745, 501, 6835, 1807, 1267, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 9606, 2583, 2520, 2988, 287, 1435, 288, 203, 3639, 2583, 12, 291, 2988, 287, 9334, 315, 8924, 353, 4551, 486, 1674, 287, 8863, 21281, 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 ]
pragma solidity ^0.4.18; import './MintableAsset.sol'; import './PricedAsset.sol'; import './Asset.sol'; /** * @title Share * @dev Contract representing shares of a fund */ contract Shares is MintableAsset, PricedAsset { function Shares(bytes32 _symbol, PricingOracle _pricingOracle) public Asset(_symbol) PricedAsset(_pricingOracle) { } function issueShares(address _shareHolder, uint256 _amount) public onlyOwner returns(bool) { //Connect fund controller, compliance and audit proxies return super.mint(_shareHolder, _amount); } }
* @title Share @dev Contract representing shares of a fund/
contract Shares is MintableAsset, PricedAsset { function Shares(bytes32 _symbol, PricingOracle _pricingOracle) public Asset(_symbol) PricedAsset(_pricingOracle) { } function issueShares(address _shareHolder, uint256 _amount) public onlyOwner returns(bool) { return super.mint(_shareHolder, _amount); } }
12,722,298
[ 1, 9535, 225, 13456, 5123, 24123, 434, 279, 284, 1074, 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, 16351, 2638, 4807, 353, 490, 474, 429, 6672, 16, 20137, 72, 6672, 288, 203, 203, 565, 445, 2638, 4807, 12, 3890, 1578, 389, 7175, 16, 453, 1512, 310, 23601, 389, 683, 14774, 23601, 13, 1071, 203, 3639, 10494, 24899, 7175, 13, 203, 3639, 20137, 72, 6672, 24899, 683, 14774, 23601, 13, 288, 203, 203, 565, 289, 203, 203, 565, 445, 5672, 24051, 12, 2867, 389, 14419, 6064, 16, 2254, 5034, 389, 8949, 13, 1071, 1338, 5541, 1135, 12, 6430, 13, 288, 203, 3639, 327, 2240, 18, 81, 474, 24899, 14419, 6064, 16, 389, 8949, 1769, 203, 565, 289, 203, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x4575478CB8De1785604FedfeB26ABc88372D9E12/sources/contracts/LegionBase.sol
Mapping from the gamer ID => wallet address Mapping from owner => list of owned token IDs.
contract Legion is ERC721Base, PermissionsEnumerable { mapping(string => address) private gamerWallet; mapping (address => uint256[]) private ownedItems; Getter functions pragma solidity ^0.8.0; function getGamerAddress(string memory gamerId) public view virtual returns (address) { address walletAddress = gamerWallet[gamerId]; require(walletAddress != address(0), "Wallet not connected to Gamer ID"); return walletAddress ; } function getGamerItems(string memory gamerId) public view virtual returns (uint256[] memory gamerItems) { address walletAddress = gamerWallet[gamerId]; require(walletAddress != address(0), "Wallet not connected to Gamer ID"); gamerItems = ownedItems[walletAddress]; } function mintTo(address _to, string memory _tokenURI) public override { require(_canMint(), "Not authorized to mint."); uint256 tokenId = nextTokenIdToMint(); _setTokenURI(tokenId, _tokenURI); ownedItems[_to].push(tokenId); _safeMint(_to, 1, ""); } Internal (overrideable) functions function _setGamerAddress(address _gamerAddress, string memory _gamerId) internal virtual { require(_canSetGamerWallet(), "Not authorized to set gamer wallet"); gamerWallet[_gamerId] = _gamerAddress; } function _canSetGamerWallet() internal view virtual returns (bool) { return msg.sender == owner(); } constructor( string memory _name, string memory _symbol, address _royaltyRecipient, uint128 _royaltyBps ) ERC721Base( _name, _symbol, _royaltyRecipient, _royaltyBps ) { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } }
1,943,551
[ 1, 3233, 628, 326, 23411, 264, 1599, 516, 9230, 1758, 9408, 628, 3410, 516, 666, 434, 16199, 1147, 7115, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 17167, 285, 353, 4232, 39, 27, 5340, 2171, 16, 15684, 3572, 25121, 225, 288, 203, 203, 565, 2874, 12, 1080, 225, 516, 1758, 13, 3238, 23411, 264, 16936, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 63, 5717, 3238, 16199, 3126, 31, 203, 203, 13491, 968, 387, 4186, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 445, 7162, 24458, 1887, 12, 1080, 3778, 23411, 264, 548, 13, 1071, 1476, 5024, 1135, 261, 2867, 13, 288, 203, 3639, 1758, 9230, 1887, 273, 23411, 264, 16936, 63, 75, 24458, 548, 15533, 203, 3639, 2583, 12, 19177, 1887, 480, 1758, 12, 20, 3631, 315, 16936, 486, 5840, 358, 611, 24458, 1599, 8863, 203, 3639, 327, 9230, 1887, 274, 203, 565, 289, 203, 203, 565, 445, 7162, 24458, 3126, 12, 1080, 3778, 23411, 264, 548, 13, 1071, 1476, 5024, 1135, 261, 11890, 5034, 8526, 3778, 23411, 264, 3126, 13, 288, 203, 3639, 1758, 9230, 1887, 273, 23411, 264, 16936, 63, 75, 24458, 548, 15533, 203, 3639, 2583, 12, 19177, 1887, 480, 1758, 12, 20, 3631, 315, 16936, 486, 5840, 358, 611, 24458, 1599, 8863, 203, 3639, 23411, 264, 3126, 273, 16199, 3126, 63, 19177, 1887, 15533, 203, 565, 289, 203, 203, 565, 445, 312, 474, 774, 12, 2867, 389, 869, 16, 533, 3778, 389, 2316, 3098, 13, 1071, 3849, 288, 203, 3639, 2583, 24899, 4169, 49, 474, 9334, 315, 1248, 10799, 358, 312, 474, 1199, 1769, 203, 3639, 2254, 5034, 1147, 548, 273, 225, 9617, 28803, 49, 474, 5621, 2 ]
./partial_match/1/0xBA4F8bBEE30181678ECB14564D78Db39d223E960/sources/MaximusSniper.sol
//Constructor/// Pancake RouterCreates a Pancake Paircontract creator is by default marketing walletowner pancake router and contract is excluded from Taxes
constructor () { uint deployerBalance=_circulatingSupply; _balances[msg.sender] = deployerBalance; emit Transfer(address(0), msg.sender, deployerBalance); _pancakeRouter = IPancakeRouter(PancakeRouter); _pancakePairAddress = IPancakeFactory(_pancakeRouter.factory()).createPair(address(this), _pancakeRouter.WETH()); isAMM[_pancakePairAddress]=true; marketingWallet=msg.sender; excludedFromFees[msg.sender]=true; excludedFromFees[PancakeRouter]=true; excludedFromFees[address(this)]=true; }
2,757,920
[ 1, 759, 6293, 28111, 12913, 23780, 9703, 2729, 279, 12913, 23780, 8599, 16351, 11784, 353, 635, 805, 13667, 310, 9230, 8443, 2800, 23780, 4633, 471, 6835, 353, 8845, 628, 399, 10855, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 565, 3885, 1832, 288, 203, 3639, 2254, 7286, 264, 13937, 33, 67, 11614, 1934, 1776, 3088, 1283, 31, 203, 3639, 389, 70, 26488, 63, 3576, 18, 15330, 65, 273, 7286, 264, 13937, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 1234, 18, 15330, 16, 7286, 264, 13937, 1769, 203, 203, 3639, 389, 7355, 23780, 8259, 273, 2971, 19292, 911, 8259, 12, 4069, 23780, 8259, 1769, 203, 3639, 389, 7355, 23780, 4154, 1887, 273, 2971, 19292, 911, 1733, 24899, 7355, 23780, 8259, 18, 6848, 1435, 2934, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 7355, 23780, 8259, 18, 59, 1584, 44, 10663, 203, 3639, 353, 2192, 49, 63, 67, 7355, 23780, 4154, 1887, 65, 33, 3767, 31, 203, 540, 203, 3639, 13667, 310, 16936, 33, 3576, 18, 15330, 31, 203, 3639, 8845, 1265, 2954, 281, 63, 3576, 18, 15330, 65, 33, 3767, 31, 203, 3639, 8845, 1265, 2954, 281, 63, 4069, 23780, 8259, 65, 33, 3767, 31, 203, 3639, 8845, 1265, 2954, 281, 63, 2867, 12, 2211, 25887, 33, 3767, 31, 203, 565, 289, 203, 377, 203, 203, 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 ]
./partial_match/1/0xa1a5143b4044cC3B710FfB8D7130b24a542536f0/sources/lib/forge-std/src/safeconsole.sol
Selector of `log(bool,uint256,bool,uint256)`.
function log(bool p0, uint256 p1, bool p2, uint256 p3) internal pure { bytes32 m0; bytes32 m1; bytes32 m2; bytes32 m3; bytes32 m4; assembly { m0 := mload(0x00) m1 := mload(0x20) m2 := mload(0x40) m3 := mload(0x60) m4 := mload(0x80) mstore(0x00, 0x7f9bbca2) mstore(0x20, p0) mstore(0x40, p1) mstore(0x60, p2) mstore(0x80, p3) } _sendLogPayload(0x1c, 0x84); assembly { mstore(0x00, m0) mstore(0x20, m1) mstore(0x40, m2) mstore(0x60, m3) mstore(0x80, m4) } }
16,053,123
[ 1, 4320, 434, 1375, 1330, 12, 6430, 16, 11890, 5034, 16, 6430, 16, 11890, 5034, 13, 8338, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 613, 12, 6430, 293, 20, 16, 2254, 5034, 293, 21, 16, 1426, 293, 22, 16, 2254, 5034, 293, 23, 13, 2713, 16618, 288, 203, 3639, 1731, 1578, 312, 20, 31, 203, 3639, 1731, 1578, 312, 21, 31, 203, 3639, 1731, 1578, 312, 22, 31, 203, 3639, 1731, 1578, 312, 23, 31, 203, 3639, 1731, 1578, 312, 24, 31, 203, 3639, 19931, 288, 203, 5411, 312, 20, 519, 312, 945, 12, 20, 92, 713, 13, 203, 5411, 312, 21, 519, 312, 945, 12, 20, 92, 3462, 13, 203, 5411, 312, 22, 519, 312, 945, 12, 20, 92, 7132, 13, 203, 5411, 312, 23, 519, 312, 945, 12, 20, 92, 4848, 13, 203, 5411, 312, 24, 519, 312, 945, 12, 20, 92, 3672, 13, 203, 5411, 312, 2233, 12, 20, 92, 713, 16, 374, 92, 27, 74, 29, 9897, 5353, 22, 13, 203, 5411, 312, 2233, 12, 20, 92, 3462, 16, 293, 20, 13, 203, 5411, 312, 2233, 12, 20, 92, 7132, 16, 293, 21, 13, 203, 5411, 312, 2233, 12, 20, 92, 4848, 16, 293, 22, 13, 203, 5411, 312, 2233, 12, 20, 92, 3672, 16, 293, 23, 13, 203, 3639, 289, 203, 3639, 389, 4661, 1343, 6110, 12, 20, 92, 21, 71, 16, 374, 92, 5193, 1769, 203, 3639, 19931, 288, 203, 5411, 312, 2233, 12, 20, 92, 713, 16, 312, 20, 13, 203, 5411, 312, 2233, 12, 20, 92, 3462, 16, 312, 21, 13, 203, 5411, 312, 2233, 12, 20, 92, 7132, 16, 312, 22, 13, 203, 5411, 312, 2233, 12, 2 ]
./partial_match/1/0x5f86D4960DfA54d4fFa109f71259bE3c5CB965C6/sources/ZoxE.sol
3% max wallet amount
maxSizeForWallet = totalSupply * 3 / 100;
4,174,871
[ 1, 23, 9, 943, 9230, 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, 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, 14777, 1290, 16936, 273, 2078, 3088, 1283, 380, 890, 342, 2130, 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 ]
./partial_match/1/0x49E6f06fb6d10D787Ab56b6543556c9249d052BE/sources/D3MJob.sol
Execute the D3M and see if the assets deployed change enough to warrant an update Found a valid execution For some reason this errored -- carry on
function workable(bytes32 network) external override returns (bool, bytes memory) { if (!sequencer.isMaster(network)) return (false, bytes("Network is not master")); bytes32[] memory ilks = ilkRegistry.list(); for (uint256 i = 0; i < ilks.length; i++) { bytes32 ilk = ilks[i]; address pool = hub.pool(ilk); (, uint256 part) = vat.urns(ilk, pool); try hub.exec(ilk) { (, uint256 nart) = vat.urns(ilk, pool); if (block.timestamp < expiry[ilk]) continue; if (!shouldTrigger(part, nart)) continue; return (true, abi.encode(ilk)); } } return (false, bytes("No ilks ready")); }
16,031,820
[ 1, 5289, 326, 463, 23, 49, 471, 2621, 309, 326, 7176, 19357, 2549, 7304, 358, 341, 5399, 970, 392, 1089, 10750, 279, 923, 4588, 2457, 2690, 3971, 333, 6445, 23226, 1493, 9331, 603, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1440, 429, 12, 3890, 1578, 2483, 13, 3903, 3849, 1135, 261, 6430, 16, 1731, 3778, 13, 288, 203, 3639, 309, 16051, 307, 372, 23568, 18, 291, 7786, 12, 5185, 3719, 327, 261, 5743, 16, 1731, 2932, 3906, 353, 486, 4171, 7923, 1769, 203, 203, 3639, 1731, 1578, 8526, 3778, 14254, 7904, 273, 14254, 79, 4243, 18, 1098, 5621, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 14254, 7904, 18, 2469, 31, 277, 27245, 288, 203, 5411, 1731, 1578, 14254, 79, 273, 14254, 7904, 63, 77, 15533, 203, 5411, 1758, 2845, 273, 11891, 18, 6011, 12, 330, 79, 1769, 203, 203, 203, 5411, 261, 16, 2254, 5034, 1087, 13, 273, 17359, 18, 321, 87, 12, 330, 79, 16, 2845, 1769, 203, 5411, 775, 11891, 18, 4177, 12, 330, 79, 13, 288, 203, 7734, 261, 16, 2254, 5034, 290, 485, 13, 273, 17359, 18, 321, 87, 12, 330, 79, 16, 2845, 1769, 203, 7734, 309, 261, 2629, 18, 5508, 411, 10839, 63, 330, 79, 5717, 1324, 31, 203, 7734, 309, 16051, 13139, 6518, 12, 2680, 16, 290, 485, 3719, 1324, 31, 203, 203, 7734, 327, 261, 3767, 16, 24126, 18, 3015, 12, 330, 79, 10019, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 327, 261, 5743, 16, 1731, 2932, 2279, 14254, 7904, 5695, 7923, 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 ]
// File: @openzeppelin/contracts/proxy/Proxy.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { // solhint-disable-next-line no-inline-assembly assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback () external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive () external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual { } } // 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/proxy/UpgradeableProxy.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an * implementation address that can be changed. This address is stored in storage in the location specified by * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. * * Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see * {TransparentUpgradeableProxy}. */ contract UpgradeableProxy is Proxy { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializating the storage of the proxy like a Solidity constructor. */ constructor(address _logic, bytes memory _data) public payable { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _setImplementation(_logic); if(_data.length > 0) { Address.functionDelegateCall(_logic, _data); } } /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @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 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation address. */ function _implementation() internal view virtual override returns (address impl) { bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal virtual { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "UpgradeableProxy: new implementation is not a contract"); bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newImplementation) } } } // File: contracts/UpgradeableExtension.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev This contract implements an upgradeable extension. It is upgradeable because calls are delegated to an * implementation address that can be changed. This address is stored in storage in the location specified by * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. * * Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see * {TransparentUpgradeableProxy}. */ contract UpgradeableExtension is Proxy { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializating the storage of the proxy like a Solidity constructor. */ constructor() public payable { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); } /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @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 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation address. */ function _implementation() internal view virtual override returns (address impl) { bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal virtual { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require( newImplementation == address(0x0) || Address.isContract(newImplementation), "UpgradeableExtension: new implementation must be 0x0 or a contract" ); bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newImplementation) } } } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol 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); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol 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; } } // File: openzeppelin-solidity/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address62 { /** * @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); } } } } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address62 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: openzeppelin-solidity/contracts/GSN/Context.sol 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; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address62 for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: openzeppelin-solidity/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: openzeppelin-solidity/contracts/math/Math.sol pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: contracts/ReentrancyGuardPausable.sol pragma solidity ^0.6.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Reuse openzeppelin's ReentrancyGuard with Pausable feature */ contract ReentrancyGuardPausable { // 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 constant _PAUSEDV1 = 4; 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 nonReentrantAndUnpaused(uint256 version) { { uint256 status = _status; // On the first call to nonReentrant, _notEntered will be true require((status & (1 << (version + 1))) == 0, "ReentrancyGuard: paused"); require((status & _ENTERED) == 0, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = status ^ _ENTERED; } _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status ^= _ENTERED; } modifier nonReentrantAndUnpausedV1() { { uint256 status = _status; // On the first call to nonReentrant, _notEntered will be true require((status & _PAUSEDV1) == 0, "ReentrancyGuard: paused"); require((status & _ENTERED) == 0, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = status ^ _ENTERED; } _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status ^= _ENTERED; } function _pause(uint256 flag) internal { _status |= flag; } function _unpause(uint256 flag) internal { _status &= ~flag; } } // File: contracts/YERC20.sol pragma solidity ^0.6.0; /* TODO: Actually methods are public instead of external */ interface YERC20 is IERC20 { function getPricePerFullShare() external view returns (uint256); function deposit(uint256 _amount) external; function withdraw(uint256 _shares) external; } // File: contracts/SmoothyV1.sol pragma solidity ^0.6.0; contract SmoothyV1 is ReentrancyGuardPausable, ERC20, Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 constant W_ONE = 1e18; uint256 constant U256_1 = 1; uint256 constant SWAP_FEE_MAX = 2e17; uint256 constant REDEEM_FEE_MAX = 2e17; uint256 constant ADMIN_FEE_PCT_MAX = 5e17; /** @dev Fee collector of the contract */ address public _rewardCollector; // Using mapping instead of array to save gas mapping(uint256 => uint256) public _tokenInfos; mapping(uint256 => address) public _yTokenAddresses; // Best estimate of token balance in y pool. // Save the gas cost of calling yToken to evaluate balanceInToken. mapping(uint256 => uint256) public _yBalances; /* * _totalBalance is expected to >= sum(_getBalance()'s), where the diff is the admin fee * collected by _collectReward(). */ uint256 public _totalBalance; uint256 public _swapFee = 4e14; // 1E18 means 100% uint256 public _redeemFee = 0; // 1E18 means 100% uint256 public _adminFeePct = 0; // % of swap/redeem fee to admin uint256 public _adminInterestPct = 0; // % of interest to admins uint256 public _ntokens; uint256 constant YENABLE_OFF = 40; uint256 constant DECM_OFF = 41; uint256 constant TID_OFF = 46; event Swap( address indexed buyer, uint256 bTokenIdIn, uint256 bTokenIdOut, uint256 inAmount, uint256 outAmount ); event SwapAll( address indexed provider, uint256[] amounts, uint256 inOutFlag, uint256 sTokenMintedOrBurned ); event Mint( address indexed provider, uint256 inAmounts, uint256 sTokenMinted ); event Redeem( address indexed provider, uint256 bTokenAmount, uint256 sTokenBurn ); constructor ( address[] memory tokens, address[] memory yTokens, uint256[] memory decMultipliers, uint256[] memory softWeights, uint256[] memory hardWeights ) public ERC20("Smoothy LP Token", "syUSD") { require(tokens.length == yTokens.length, "tokens and ytokens must have the same length"); require( tokens.length == decMultipliers.length, "tokens and decMultipliers must have the same length" ); require( tokens.length == hardWeights.length, "incorrect hard wt. len" ); require( tokens.length == softWeights.length, "incorrect soft wt. len" ); _rewardCollector = msg.sender; for (uint8 i = 0; i < tokens.length; i++) { uint256 info = uint256(tokens[i]); require(hardWeights[i] >= softWeights[i], "hard wt. must >= soft wt."); require(hardWeights[i] <= W_ONE, "hard wt. must <= 1e18"); info = _setHardWeight(info, hardWeights[i]); info = _setSoftWeight(info, softWeights[i]); info = _setDecimalMultiplier(info, decMultipliers[i]); info = _setTID(info, i); _yTokenAddresses[i] = yTokens[i]; // _balances[i] = 0; // no need to set if (yTokens[i] != address(0x0)) { info = _setYEnabled(info, true); } _tokenInfos[i] = info; } _ntokens = tokens.length; } /*************************************** * Methods to change a token info ***************************************/ /* return soft weight in 1e18 */ function _getSoftWeight(uint256 info) internal pure returns (uint256 w) { return ((info >> 160) & ((U256_1 << 20) - 1)) * 1e12; } function _setSoftWeight( uint256 info, uint256 w ) internal pure returns (uint256 newInfo) { require (w <= W_ONE, "soft weight must <= 1e18"); // Only maintain 1e6 resolution. newInfo = info & ~(((U256_1 << 20) - 1) << 160); newInfo = newInfo | ((w / 1e12) << 160); } function _getHardWeight(uint256 info) internal pure returns (uint256 w) { return ((info >> 180) & ((U256_1 << 20) - 1)) * 1e12; } function _setHardWeight( uint256 info, uint256 w ) internal pure returns (uint256 newInfo) { require (w <= W_ONE, "hard weight must <= 1e18"); // Only maintain 1e6 resolution. newInfo = info & ~(((U256_1 << 20) - 1) << 180); newInfo = newInfo | ((w / 1e12) << 180); } function _getDecimalMulitiplier(uint256 info) internal pure returns (uint256 dec) { return (info >> (160 + DECM_OFF)) & ((U256_1 << 5) - 1); } function _setDecimalMultiplier( uint256 info, uint256 decm ) internal pure returns (uint256 newInfo) { require (decm < 18, "decimal multipler is too large"); newInfo = info & ~(((U256_1 << 5) - 1) << (160 + DECM_OFF)); newInfo = newInfo | (decm << (160 + DECM_OFF)); } function _isYEnabled(uint256 info) internal pure returns (bool) { return (info >> (160 + YENABLE_OFF)) & 0x1 == 0x1; } function _setYEnabled(uint256 info, bool enabled) internal pure returns (uint256) { if (enabled) { return info | (U256_1 << (160 + YENABLE_OFF)); } else { return info & ~(U256_1 << (160 + YENABLE_OFF)); } } function _setTID(uint256 info, uint256 tid) internal pure returns (uint256) { require (tid < 256, "tid is too large"); require (_getTID(info) == 0, "tid cannot set again"); return info | (tid << (160 + TID_OFF)); } function _getTID(uint256 info) internal pure returns (uint256) { return (info >> (160 + TID_OFF)) & 0xFF; } /**************************************** * Owner methods ****************************************/ function pause(uint256 flag) external onlyOwner { _pause(flag); } function unpause(uint256 flag) external onlyOwner { _unpause(flag); } function changeRewardCollector(address newCollector) external onlyOwner { _rewardCollector = newCollector; } function adjustWeights( uint8 tid, uint256 newSoftWeight, uint256 newHardWeight ) external onlyOwner { require(newSoftWeight <= newHardWeight, "Soft-limit weight must <= Hard-limit weight"); require(newHardWeight <= W_ONE, "hard-limit weight must <= 1"); require(tid < _ntokens, "Backed token not exists"); _tokenInfos[tid] = _setSoftWeight(_tokenInfos[tid], newSoftWeight); _tokenInfos[tid] = _setHardWeight(_tokenInfos[tid], newHardWeight); } function changeSwapFee(uint256 swapFee) external onlyOwner { require(swapFee <= SWAP_FEE_MAX, "Swap fee must is too large"); _swapFee = swapFee; } function changeRedeemFee( uint256 redeemFee ) external onlyOwner { require(redeemFee <= REDEEM_FEE_MAX, "Redeem fee is too large"); _redeemFee = redeemFee; } function changeAdminFeePct(uint256 pct) external onlyOwner { require (pct <= ADMIN_FEE_PCT_MAX, "Admin fee pct is too large"); _adminFeePct = pct; } function changeAdminInterestPct(uint256 pct) external onlyOwner { require (pct <= ADMIN_FEE_PCT_MAX, "Admin interest fee pct is too large"); _adminInterestPct = pct; } function initialize( uint8 tid, uint256 bTokenAmount ) external onlyOwner { require(tid < _ntokens, "Backed token not exists"); uint256 info = _tokenInfos[tid]; address addr = address(info); IERC20(addr).safeTransferFrom( msg.sender, address(this), bTokenAmount ); _totalBalance = _totalBalance.add(bTokenAmount.mul(_normalizeBalance(info))); _mint(msg.sender, bTokenAmount.mul(_normalizeBalance(info))); } function addToken( address addr, address yAddr, uint256 softWeight, uint256 hardWeight, uint256 decMultiplier ) external onlyOwner { uint256 tid = _ntokens; for (uint256 i = 0; i < tid; i++) { require(address(_tokenInfos[i]) != addr, "cannot add dup token"); } require (softWeight <= hardWeight, "soft weight must <= hard weight"); uint256 info = uint256(addr); info = _setTID(info, tid); info = _setYEnabled(info, yAddr != address(0x0)); info = _setSoftWeight(info, softWeight); info = _setHardWeight(info, hardWeight); info = _setDecimalMultiplier(info, decMultiplier); _tokenInfos[tid] = info; _yTokenAddresses[tid] = yAddr; // _balances[tid] = 0; // no need to set _ntokens = tid.add(1); } function setYEnabled(uint256 tid, address yAddr) external onlyOwner { uint256 info = _tokenInfos[tid]; if (_yTokenAddresses[tid] != address(0x0)) { // Withdraw all tokens from yToken, and clear yBalance. uint256 pricePerShare = YERC20(_yTokenAddresses[tid]).getPricePerFullShare(); uint256 share = YERC20(_yTokenAddresses[tid]).balanceOf(address(this)); uint256 cash = _getCashBalance(info); YERC20(_yTokenAddresses[tid]).withdraw(share); uint256 dcash = _getCashBalance(info).sub(cash); require(dcash >= pricePerShare.mul(share).div(W_ONE), "ytoken withdraw amount < expected"); // Update _totalBalance with interest _updateTotalBalanceWithNewYBalance(tid, dcash); _yBalances[tid] = 0; } info = _setYEnabled(info, yAddr != address(0x0)); _yTokenAddresses[tid] = yAddr; _tokenInfos[tid] = info; // If yAddr != 0x0, we will rebalance in next swap/mint/redeem/rebalance call. } /** * Calculate binary logarithm of x. Revert if x <= 0. * See LICENSE_LOG.md for license. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function lg2(int128 x) internal pure returns (int128) { require (x > 0, "x must be positive"); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) {xc >>= 64; msb += 64;} if (xc >= 0x100000000) {xc >>= 32; msb += 32;} if (xc >= 0x10000) {xc >>= 16; msb += 16;} if (xc >= 0x100) {xc >>= 8; msb += 8;} if (xc >= 0x10) {xc >>= 4; msb += 4;} if (xc >= 0x4) {xc >>= 2; msb += 2;} if (xc >= 0x2) {msb += 1;} // No need to shift xc anymore int256 result = (msb - 64) << 64; uint256 ux = uint256 (x) << (127 - msb); /* 20 iterations so that the resolution is aboout 2^-20 \approx 5e-6 */ for (int256 bit = 0x8000000000000000; bit > 0x80000000000; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256(b); } return int128(result); } function _safeToInt128(uint256 x) internal pure returns (int128 y) { y = int128(x); require(x == uint256(y), "Conversion to int128 failed"); return y; } /** * @dev Return the approx logarithm of a value with log(x) where x <= 1.1. * All values are in integers with (1e18 == 1.0). * * Requirements: * * - input value x must be greater than 1e18 */ function _logApprox(uint256 x) internal pure returns (uint256 y) { uint256 one = W_ONE; require(x >= one, "logApprox: x must >= 1"); uint256 z = x - one; uint256 zz = z.mul(z).div(one); uint256 zzz = zz.mul(z).div(one); uint256 zzzz = zzz.mul(z).div(one); uint256 zzzzz = zzzz.mul(z).div(one); return z.sub(zz.div(2)).add(zzz.div(3)).sub(zzzz.div(4)).add(zzzzz.div(5)); } /** * @dev Return the logarithm of a value. * All values are in integers with (1e18 == 1.0). * * Requirements: * * - input value x must be greater than 1e18 */ function _log(uint256 x) internal pure returns (uint256 y) { require(x >= W_ONE, "log(x): x must be greater than 1"); require(x < (W_ONE << 63), "log(x): x is too large"); if (x <= W_ONE.add(W_ONE.div(10))) { return _logApprox(x); } /* Convert to 64.64 float point */ int128 xx = _safeToInt128((x << 64) / W_ONE); int128 yy = lg2(xx); /* log(2) * 1e18 \approx 693147180559945344 */ y = (uint256(yy) * 693147180559945344) >> 64; return y; } /** * Return weights and cached balances of all tokens * Note that the cached balance does not include the accrued interest since last rebalance. */ function _getBalancesAndWeights() internal view returns (uint256[] memory balances, uint256[] memory softWeights, uint256[] memory hardWeights, uint256 totalBalance) { uint256 ntokens = _ntokens; balances = new uint256[](ntokens); softWeights = new uint256[](ntokens); hardWeights = new uint256[](ntokens); totalBalance = 0; for (uint8 i = 0; i < ntokens; i++) { uint256 info = _tokenInfos[i]; balances[i] = _getCashBalance(info); if (_isYEnabled(info)) { balances[i] = balances[i].add(_yBalances[i]); } totalBalance = totalBalance.add(balances[i]); softWeights[i] = _getSoftWeight(info); hardWeights[i] = _getHardWeight(info); } } function _getBalancesAndInfos() internal view returns (uint256[] memory balances, uint256[] memory infos, uint256 totalBalance) { uint256 ntokens = _ntokens; balances = new uint256[](ntokens); infos = new uint256[](ntokens); totalBalance = 0; for (uint8 i = 0; i < ntokens; i++) { infos[i] = _tokenInfos[i]; balances[i] = _getCashBalance(infos[i]); if (_isYEnabled(infos[i])) { balances[i] = balances[i].add(_yBalances[i]); } totalBalance = totalBalance.add(balances[i]); } } function _getBalance(uint256 info) internal view returns (uint256 balance) { balance = _getCashBalance(info); if (_isYEnabled(info)) { balance = balance.add(_yBalances[_getTID(info)]); } } function getBalance(uint256 tid) public view returns (uint256) { return _getBalance(_tokenInfos[tid]); } function _normalizeBalance(uint256 info) internal pure returns (uint256) { uint256 decm = _getDecimalMulitiplier(info); return 10 ** decm; } /* @dev Return normalized cash balance of a token */ function _getCashBalance(uint256 info) internal view returns (uint256) { return IERC20(address(info)).balanceOf(address(this)) .mul(_normalizeBalance(info)); } function _getBalanceDetail( uint256 info ) internal view returns (uint256 pricePerShare, uint256 cashUnnormalized, uint256 yBalanceUnnormalized) { address yAddr = _yTokenAddresses[_getTID(info)]; pricePerShare = YERC20(yAddr).getPricePerFullShare(); cashUnnormalized = IERC20(address(info)).balanceOf(address(this)); uint256 share = YERC20(yAddr).balanceOf(address(this)); yBalanceUnnormalized = share.mul(pricePerShare).div(W_ONE); } /************************************************************************************** * Methods for rebalance cash reserve * After rebalancing, we will have cash reserve equaling to 10% of total balance * There are two conditions to trigger a rebalancing * - if there is insufficient cash for withdraw; or * - if the cash reserve is greater than 20% of total balance. * Note that we use a cached version of total balance to avoid high gas cost on calling * getPricePerFullShare(). *************************************************************************************/ function _updateTotalBalanceWithNewYBalance( uint256 tid, uint256 yBalanceNormalizedNew ) internal { uint256 adminFee = 0; uint256 yBalanceNormalizedOld = _yBalances[tid]; // They yBalance should not be decreasing, but just in case, if (yBalanceNormalizedNew >= yBalanceNormalizedOld) { adminFee = (yBalanceNormalizedNew - yBalanceNormalizedOld).mul(_adminInterestPct).div(W_ONE); } _totalBalance = _totalBalance .sub(yBalanceNormalizedOld) .add(yBalanceNormalizedNew) .sub(adminFee); } function _rebalanceReserve( uint256 info ) internal { require(_isYEnabled(info), "yToken must be enabled for rebalancing"); uint256 pricePerShare; uint256 cashUnnormalized; uint256 yBalanceUnnormalized; (pricePerShare, cashUnnormalized, yBalanceUnnormalized) = _getBalanceDetail(info); uint256 tid = _getTID(info); // Update _totalBalance with interest _updateTotalBalanceWithNewYBalance(tid, yBalanceUnnormalized.mul(_normalizeBalance(info))); uint256 targetCash = yBalanceUnnormalized.add(cashUnnormalized).div(10); if (cashUnnormalized > targetCash) { uint256 depositAmount = cashUnnormalized.sub(targetCash); // Reset allowance to bypass possible allowance check (e.g., USDT) IERC20(address(info)).safeApprove(_yTokenAddresses[tid], 0); IERC20(address(info)).safeApprove(_yTokenAddresses[tid], depositAmount); // Calculate acutal deposit in the case that some yTokens may return partial deposit. uint256 balanceBefore = IERC20(address(info)).balanceOf(address(this)); YERC20(_yTokenAddresses[tid]).deposit(depositAmount); uint256 actualDeposit = balanceBefore.sub(IERC20(address(info)).balanceOf(address(this))); _yBalances[tid] = yBalanceUnnormalized.add(actualDeposit).mul(_normalizeBalance(info)); } else { uint256 expectedWithdraw = targetCash.sub(cashUnnormalized); if (expectedWithdraw == 0) { return; } uint256 balanceBefore = IERC20(address(info)).balanceOf(address(this)); // Withdraw +1 wei share to make sure actual withdraw >= expected. YERC20(_yTokenAddresses[tid]).withdraw(expectedWithdraw.mul(W_ONE).div(pricePerShare).add(1)); uint256 actualWithdraw = IERC20(address(info)).balanceOf(address(this)).sub(balanceBefore); require(actualWithdraw >= expectedWithdraw, "insufficient cash withdrawn from yToken"); _yBalances[tid] = yBalanceUnnormalized.sub(actualWithdraw).mul(_normalizeBalance(info)); } } /* @dev Forcibly rebalance so that cash reserve is about 10% of total. */ function rebalanceReserve( uint256 tid ) external nonReentrantAndUnpausedV1 { _rebalanceReserve(_tokenInfos[tid]); } /* * @dev Rebalance the cash reserve so that * cash reserve consists of 10% of total balance after substracting amountUnnormalized. * * Assume that current cash reserve < amountUnnormalized. */ function _rebalanceReserveSubstract( uint256 info, uint256 amountUnnormalized ) internal { require(_isYEnabled(info), "yToken must be enabled for rebalancing"); uint256 pricePerShare; uint256 cashUnnormalized; uint256 yBalanceUnnormalized; (pricePerShare, cashUnnormalized, yBalanceUnnormalized) = _getBalanceDetail(info); // Update _totalBalance with interest _updateTotalBalanceWithNewYBalance( _getTID(info), yBalanceUnnormalized.mul(_normalizeBalance(info)) ); // Evaluate the shares to withdraw so that cash = 10% of total uint256 expectedWithdraw = cashUnnormalized.add(yBalanceUnnormalized).sub( amountUnnormalized).div(10).add(amountUnnormalized).sub(cashUnnormalized); if (expectedWithdraw == 0) { return; } // Withdraw +1 wei share to make sure actual withdraw >= expected. uint256 withdrawShares = expectedWithdraw.mul(W_ONE).div(pricePerShare).add(1); uint256 balanceBefore = IERC20(address(info)).balanceOf(address(this)); YERC20(_yTokenAddresses[_getTID(info)]).withdraw(withdrawShares); uint256 actualWithdraw = IERC20(address(info)).balanceOf(address(this)).sub(balanceBefore); require(actualWithdraw >= expectedWithdraw, "insufficient cash withdrawn from yToken"); _yBalances[_getTID(info)] = yBalanceUnnormalized.sub(actualWithdraw) .mul(_normalizeBalance(info)); } /* @dev Transfer the amount of token out. Rebalance the cash reserve if needed */ function _transferOut( uint256 info, uint256 amountUnnormalized, uint256 adminFee ) internal { uint256 amountNormalized = amountUnnormalized.mul(_normalizeBalance(info)); if (_isYEnabled(info)) { if (IERC20(address(info)).balanceOf(address(this)) < amountUnnormalized) { _rebalanceReserveSubstract(info, amountUnnormalized); } } IERC20(address(info)).safeTransfer( msg.sender, amountUnnormalized ); _totalBalance = _totalBalance .sub(amountNormalized) .sub(adminFee.mul(_normalizeBalance(info))); } /* @dev Transfer the amount of token in. Rebalance the cash reserve if needed */ function _transferIn( uint256 info, uint256 amountUnnormalized ) internal { uint256 amountNormalized = amountUnnormalized.mul(_normalizeBalance(info)); IERC20(address(info)).safeTransferFrom( msg.sender, address(this), amountUnnormalized ); _totalBalance = _totalBalance.add(amountNormalized); // If there is saving ytoken, save the balance in _balance. if (_isYEnabled(info)) { uint256 tid = _getTID(info); /* Check rebalance if needed */ uint256 cash = _getCashBalance(info); if (cash > cash.add(_yBalances[tid]).mul(2).div(10)) { _rebalanceReserve(info); } } } /************************************************************************************** * Methods for minting LP tokens *************************************************************************************/ /* * @dev Return the amount of sUSD should be minted after depositing bTokenAmount into the pool * @param bTokenAmountNormalized - normalized amount of token to be deposited * @param oldBalance - normalized amount of all tokens before the deposit * @param oldTokenBlance - normalized amount of the balance of the token to be deposited in the pool * @param softWeight - percentage that will incur penalty if the resulting token percentage is greater * @param hardWeight - maximum percentage of the token */ function _getMintAmount( uint256 bTokenAmountNormalized, uint256 oldBalance, uint256 oldTokenBalance, uint256 softWeight, uint256 hardWeight ) internal pure returns (uint256 s) { /* Evaluate new percentage */ uint256 newBalance = oldBalance.add(bTokenAmountNormalized); uint256 newTokenBalance = oldTokenBalance.add(bTokenAmountNormalized); /* If new percentage <= soft weight, no penalty */ if (newTokenBalance.mul(W_ONE) <= softWeight.mul(newBalance)) { return bTokenAmountNormalized; } require ( newTokenBalance.mul(W_ONE) <= hardWeight.mul(newBalance), "mint: new percentage exceeds hard weight" ); s = 0; /* if new percentage <= soft weight, get the beginning of integral with penalty. */ if (oldTokenBalance.mul(W_ONE) <= softWeight.mul(oldBalance)) { s = oldBalance.mul(softWeight).sub(oldTokenBalance.mul(W_ONE)).div(W_ONE.sub(softWeight)); } // bx + (tx - bx) * (w - 1) / (w - v) + (S - x) * ln((S + tx) / (S + bx)) / (w - v) uint256 t; { // avoid stack too deep error uint256 ldelta = _log(newBalance.mul(W_ONE).div(oldBalance.add(s))); t = oldBalance.sub(oldTokenBalance).mul(ldelta); } t = t.sub(bTokenAmountNormalized.sub(s).mul(W_ONE.sub(hardWeight))); t = t.div(hardWeight.sub(softWeight)); s = s.add(t); require(s <= bTokenAmountNormalized, "penalty should be positive"); } /* * @dev Given the token id and the amount to be deposited, return the amount of lp token */ function getMintAmount( uint256 bTokenIdx, uint256 bTokenAmount ) public view returns (uint256 lpTokenAmount) { require(bTokenAmount > 0, "Amount must be greater than 0"); uint256 info = _tokenInfos[bTokenIdx]; require(info != 0, "Backed token is not found!"); // Obtain normalized balances uint256 bTokenAmountNormalized = bTokenAmount.mul(_normalizeBalance(info)); // Gas saving: Use cached totalBalance with accrued interest since last rebalance. uint256 totalBalance = _totalBalance; uint256 sTokenAmount = _getMintAmount( bTokenAmountNormalized, totalBalance, _getBalance(info), _getSoftWeight(info), _getHardWeight(info) ); return sTokenAmount.mul(totalSupply()).div(totalBalance); } /* * @dev Given the token id and the amount to be deposited, mint lp token */ function mint( uint256 bTokenIdx, uint256 bTokenAmount, uint256 lpTokenMintedMin ) external nonReentrantAndUnpausedV1 { uint256 lpTokenAmount = getMintAmount(bTokenIdx, bTokenAmount); require( lpTokenAmount >= lpTokenMintedMin, "lpToken minted should >= minimum lpToken asked" ); _transferIn(_tokenInfos[bTokenIdx], bTokenAmount); _mint(msg.sender, lpTokenAmount); emit Mint(msg.sender, bTokenAmount, lpTokenAmount); } /************************************************************************************** * Methods for redeeming LP tokens *************************************************************************************/ /* * @dev Return number of sUSD that is needed to redeem corresponding amount of token for another * token * Withdrawing a token will result in increased percentage of other tokens, where * the function is used to calculate the penalty incured by the increase of one token. * @param totalBalance - normalized amount of the sum of all tokens * @param tokenBlance - normalized amount of the balance of a non-withdrawn token * @param redeemAount - normalized amount of the token to be withdrawn * @param softWeight - percentage that will incur penalty if the resulting token percentage is greater * @param hardWeight - maximum percentage of the token */ function _redeemPenaltyFor( uint256 totalBalance, uint256 tokenBalance, uint256 redeemAmount, uint256 softWeight, uint256 hardWeight ) internal pure returns (uint256) { uint256 newTotalBalance = totalBalance.sub(redeemAmount); /* Soft weight is satisfied. No penalty is incurred */ if (tokenBalance.mul(W_ONE) <= newTotalBalance.mul(softWeight)) { return 0; } require ( tokenBalance.mul(W_ONE) <= newTotalBalance.mul(hardWeight), "redeem: hard-limit weight is broken" ); uint256 bx = 0; // Evaluate the beginning of the integral for broken soft weight if (tokenBalance.mul(W_ONE) < totalBalance.mul(softWeight)) { bx = totalBalance.sub(tokenBalance.mul(W_ONE).div(softWeight)); } // x * (w - v) / w / w * ln(1 + (tx - bx) * w / (w * (S - tx) - x)) - (tx - bx) * v / w uint256 tdelta = tokenBalance.mul( _log(W_ONE.add(redeemAmount.sub(bx).mul(hardWeight).div(hardWeight.mul(newTotalBalance).div(W_ONE).sub(tokenBalance))))); uint256 s1 = tdelta.mul(hardWeight.sub(softWeight)) .div(hardWeight).div(hardWeight); uint256 s2 = redeemAmount.sub(bx).mul(softWeight).div(hardWeight); return s1.sub(s2); } /* * @dev Return number of sUSD that is needed to redeem corresponding amount of token * Withdrawing a token will result in increased percentage of other tokens, where * the function is used to calculate the penalty incured by the increase. * @param bTokenIdx - token id to be withdrawn * @param totalBalance - normalized amount of the sum of all tokens * @param balances - normalized amount of the balance of each token * @param softWeights - percentage that will incur penalty if the resulting token percentage is greater * @param hardWeights - maximum percentage of the token * @param redeemAount - normalized amount of the token to be withdrawn */ function _redeemPenaltyForAll( uint256 bTokenIdx, uint256 totalBalance, uint256[] memory balances, uint256[] memory softWeights, uint256[] memory hardWeights, uint256 redeemAmount ) internal pure returns (uint256) { uint256 s = 0; for (uint256 k = 0; k < balances.length; k++) { if (k == bTokenIdx) { continue; } s = s.add( _redeemPenaltyFor(totalBalance, balances[k], redeemAmount, softWeights[k], hardWeights[k])); } return s; } /* * @dev Calculate the derivative of the penalty function. * Same parameters as _redeemPenaltyFor. */ function _redeemPenaltyDerivativeForOne( uint256 totalBalance, uint256 tokenBalance, uint256 redeemAmount, uint256 softWeight, uint256 hardWeight ) internal pure returns (uint256) { uint256 dfx = W_ONE; uint256 newTotalBalance = totalBalance.sub(redeemAmount); /* Soft weight is satisfied. No penalty is incurred */ if (tokenBalance.mul(W_ONE) <= newTotalBalance.mul(softWeight)) { return dfx; } // dx = dx + x * (w - v) / (w * (S - tx) - x) / w - v / w return dfx.add(tokenBalance.mul(hardWeight.sub(softWeight)) .div(hardWeight.mul(newTotalBalance).div(W_ONE).sub(tokenBalance))) .sub(softWeight.mul(W_ONE).div(hardWeight)); } /* * @dev Calculate the derivative of the penalty function. * Same parameters as _redeemPenaltyForAll. */ function _redeemPenaltyDerivativeForAll( uint256 bTokenIdx, uint256 totalBalance, uint256[] memory balances, uint256[] memory softWeights, uint256[] memory hardWeights, uint256 redeemAmount ) internal pure returns (uint256) { uint256 dfx = W_ONE; uint256 newTotalBalance = totalBalance.sub(redeemAmount); for (uint256 k = 0; k < balances.length; k++) { if (k == bTokenIdx) { continue; } /* Soft weight is satisfied. No penalty is incurred */ uint256 softWeight = softWeights[k]; uint256 balance = balances[k]; if (balance.mul(W_ONE) <= newTotalBalance.mul(softWeight)) { continue; } // dx = dx + x * (w - v) / (w * (S - tx) - x) / w - v / w uint256 hardWeight = hardWeights[k]; dfx = dfx.add(balance.mul(hardWeight.sub(softWeight)) .div(hardWeight.mul(newTotalBalance).div(W_ONE).sub(balance))) .sub(softWeight.mul(W_ONE).div(hardWeight)); } return dfx; } /* * @dev Given the amount of sUSD to be redeemed, find the max token can be withdrawn * This function is for swap only. * @param tidOutBalance - the balance of the token to be withdrawn * @param totalBalance - total balance of all tokens * @param tidInBalance - the balance of the token to be deposited * @param sTokenAmount - the amount of sUSD to be redeemed * @param softWeight/hardWeight - normalized weights for the token to be withdrawn. */ function _redeemFindOne( uint256 tidOutBalance, uint256 totalBalance, uint256 tidInBalance, uint256 sTokenAmount, uint256 softWeight, uint256 hardWeight ) internal pure returns (uint256) { uint256 redeemAmountNormalized = Math.min( sTokenAmount, tidOutBalance.mul(999).div(1000) ); for (uint256 i = 0; i < 256; i++) { uint256 sNeeded = redeemAmountNormalized.add( _redeemPenaltyFor( totalBalance, tidInBalance, redeemAmountNormalized, softWeight, hardWeight )); uint256 fx = 0; if (sNeeded > sTokenAmount) { fx = sNeeded - sTokenAmount; } else { fx = sTokenAmount - sNeeded; } // penalty < 1e-5 of out amount if (fx < redeemAmountNormalized / 100000) { require(redeemAmountNormalized <= sTokenAmount, "Redeem error: out amount > lp amount"); require(redeemAmountNormalized <= tidOutBalance, "Redeem error: insufficient balance"); return redeemAmountNormalized; } uint256 dfx = _redeemPenaltyDerivativeForOne( totalBalance, tidInBalance, redeemAmountNormalized, softWeight, hardWeight ); if (sNeeded > sTokenAmount) { redeemAmountNormalized = redeemAmountNormalized.sub(fx.mul(W_ONE).div(dfx)); } else { redeemAmountNormalized = redeemAmountNormalized.add(fx.mul(W_ONE).div(dfx)); } } require (false, "cannot find proper resolution of fx"); } /* * @dev Given the amount of sUSD token to be redeemed, find the max token can be withdrawn * @param bTokenIdx - the id of the token to be withdrawn * @param sTokenAmount - the amount of sUSD token to be redeemed * @param totalBalance - total balance of all tokens * @param balances/softWeight/hardWeight - normalized balances/weights of all tokens */ function _redeemFind( uint256 bTokenIdx, uint256 sTokenAmount, uint256 totalBalance, uint256[] memory balances, uint256[] memory softWeights, uint256[] memory hardWeights ) internal pure returns (uint256) { uint256 bTokenAmountNormalized = Math.min( sTokenAmount, balances[bTokenIdx].mul(999).div(1000) ); for (uint256 i = 0; i < 256; i++) { uint256 sNeeded = bTokenAmountNormalized.add( _redeemPenaltyForAll( bTokenIdx, totalBalance, balances, softWeights, hardWeights, bTokenAmountNormalized )); uint256 fx = 0; if (sNeeded > sTokenAmount) { fx = sNeeded - sTokenAmount; } else { fx = sTokenAmount - sNeeded; } // penalty < 1e-5 of out amount if (fx < bTokenAmountNormalized / 100000) { require(bTokenAmountNormalized <= sTokenAmount, "Redeem error: out amount > lp amount"); require(bTokenAmountNormalized <= balances[bTokenIdx], "Redeem error: insufficient balance"); return bTokenAmountNormalized; } uint256 dfx = _redeemPenaltyDerivativeForAll( bTokenIdx, totalBalance, balances, softWeights, hardWeights, bTokenAmountNormalized ); if (sNeeded > sTokenAmount) { bTokenAmountNormalized = bTokenAmountNormalized.sub(fx.mul(W_ONE).div(dfx)); } else { bTokenAmountNormalized = bTokenAmountNormalized.add(fx.mul(W_ONE).div(dfx)); } } require (false, "cannot find proper resolution of fx"); } /* * @dev Given token id and LP token amount, return the max amount of token can be withdrawn * @param tid - the id of the token to be withdrawn * @param lpTokenAmount - the amount of LP token */ function _getRedeemByLpTokenAmount( uint256 tid, uint256 lpTokenAmount ) internal view returns (uint256 bTokenAmount, uint256 totalBalance, uint256 adminFee) { require(lpTokenAmount > 0, "Amount must be greater than 0"); uint256 info = _tokenInfos[tid]; require(info != 0, "Backed token is not found!"); // Obtain normalized balances. // Gas saving: Use cached balances/totalBalance without accrued interest since last rebalance. uint256[] memory balances; uint256[] memory softWeights; uint256[] memory hardWeights; (balances, softWeights, hardWeights, totalBalance) = _getBalancesAndWeights(); bTokenAmount = _redeemFind( tid, lpTokenAmount.mul(totalBalance).div(totalSupply()), totalBalance, balances, softWeights, hardWeights ).div(_normalizeBalance(info)); uint256 fee = bTokenAmount.mul(_redeemFee).div(W_ONE); adminFee = fee.mul(_adminFeePct).div(W_ONE); bTokenAmount = bTokenAmount.sub(fee); } function getRedeemByLpTokenAmount( uint256 tid, uint256 lpTokenAmount ) public view returns (uint256 bTokenAmount) { (bTokenAmount,,) = _getRedeemByLpTokenAmount(tid, lpTokenAmount); } function redeemByLpToken( uint256 bTokenIdx, uint256 lpTokenAmount, uint256 bTokenMin ) external nonReentrantAndUnpausedV1 { (uint256 bTokenAmount, uint256 totalBalance, uint256 adminFee) = _getRedeemByLpTokenAmount( bTokenIdx, lpTokenAmount ); require(bTokenAmount >= bTokenMin, "bToken returned < min bToken asked"); // Make sure _totalBalance == sum(balances) _collectReward(totalBalance); _burn(msg.sender, lpTokenAmount); _transferOut(_tokenInfos[bTokenIdx], bTokenAmount, adminFee); emit Redeem(msg.sender, bTokenAmount, lpTokenAmount); } /* @dev Redeem a specific token from the pool. * Fee will be incured. Will incur penalty if the pool is unbalanced. */ function redeem( uint256 bTokenIdx, uint256 bTokenAmount, uint256 lpTokenBurnedMax ) external nonReentrantAndUnpausedV1 { require(bTokenAmount > 0, "Amount must be greater than 0"); uint256 info = _tokenInfos[bTokenIdx]; require (info != 0, "Backed token is not found!"); // Obtain normalized balances. // Gas saving: Use cached balances/totalBalance without accrued interest since last rebalance. ( uint256[] memory balances, uint256[] memory softWeights, uint256[] memory hardWeights, uint256 totalBalance ) = _getBalancesAndWeights(); uint256 bTokenAmountNormalized = bTokenAmount.mul(_normalizeBalance(info)); require(balances[bTokenIdx] >= bTokenAmountNormalized, "Insufficient token to redeem"); _collectReward(totalBalance); uint256 lpAmount = bTokenAmountNormalized.add( _redeemPenaltyForAll( bTokenIdx, totalBalance, balances, softWeights, hardWeights, bTokenAmountNormalized )).mul(totalSupply()).div(totalBalance); require(lpAmount <= lpTokenBurnedMax, "burned token should <= maximum lpToken offered"); _burn(msg.sender, lpAmount); /* Transfer out the token after deducting the fee. Rebalance cash reserve if needed */ uint256 fee = bTokenAmount.mul(_redeemFee).div(W_ONE); _transferOut( _tokenInfos[bTokenIdx], bTokenAmount.sub(fee), fee.mul(_adminFeePct).div(W_ONE) ); emit Redeem(msg.sender, bTokenAmount, lpAmount); } /************************************************************************************** * Methods for swapping tokens *************************************************************************************/ /* * @dev Return the maximum amount of token can be withdrawn after depositing another token. * @param bTokenIdIn - the id of the token to be deposited * @param bTokenIdOut - the id of the token to be withdrawn * @param bTokenInAmount - the amount (unnormalized) of the token to be deposited */ function getSwapAmount( uint256 bTokenIdxIn, uint256 bTokenIdxOut, uint256 bTokenInAmount ) external view returns (uint256 bTokenOutAmount) { uint256 infoIn = _tokenInfos[bTokenIdxIn]; uint256 infoOut = _tokenInfos[bTokenIdxOut]; (bTokenOutAmount,) = _getSwapAmount(infoIn, infoOut, bTokenInAmount); } function _getSwapAmount( uint256 infoIn, uint256 infoOut, uint256 bTokenInAmount ) internal view returns (uint256 bTokenOutAmount, uint256 adminFee) { require(bTokenInAmount > 0, "Amount must be greater than 0"); require(infoIn != 0, "Backed token is not found!"); require(infoOut != 0, "Backed token is not found!"); require (infoIn != infoOut, "Tokens for swap must be different!"); // Gas saving: Use cached totalBalance without accrued interest since last rebalance. // Here we assume that the interest earned from the underlying platform is too small to // impact the result significantly. uint256 totalBalance = _totalBalance; uint256 tidInBalance = _getBalance(infoIn); uint256 sMinted = 0; uint256 softWeight = _getSoftWeight(infoIn); uint256 hardWeight = _getHardWeight(infoIn); { // avoid stack too deep error uint256 bTokenInAmountNormalized = bTokenInAmount.mul(_normalizeBalance(infoIn)); sMinted = _getMintAmount( bTokenInAmountNormalized, totalBalance, tidInBalance, softWeight, hardWeight ); totalBalance = totalBalance.add(bTokenInAmountNormalized); tidInBalance = tidInBalance.add(bTokenInAmountNormalized); } uint256 tidOutBalance = _getBalance(infoOut); // Find the bTokenOutAmount, only account for penalty from bTokenIdxIn // because other tokens should not have penalty since // bTokenOutAmount <= sMinted <= bTokenInAmount (normalized), and thus // for other tokens, the percentage decreased by bTokenInAmount will be // >= the percetnage increased by bTokenOutAmount. bTokenOutAmount = _redeemFindOne( tidOutBalance, totalBalance, tidInBalance, sMinted, softWeight, hardWeight ).div(_normalizeBalance(infoOut)); uint256 fee = bTokenOutAmount.mul(_swapFee).div(W_ONE); adminFee = fee.mul(_adminFeePct).div(W_ONE); bTokenOutAmount = bTokenOutAmount.sub(fee); } /* * @dev Swap a token to another. * @param bTokenIdIn - the id of the token to be deposited * @param bTokenIdOut - the id of the token to be withdrawn * @param bTokenInAmount - the amount (unnormalized) of the token to be deposited * @param bTokenOutMin - the mininum amount (unnormalized) token that is expected to be withdrawn */ function swap( uint256 bTokenIdxIn, uint256 bTokenIdxOut, uint256 bTokenInAmount, uint256 bTokenOutMin ) external nonReentrantAndUnpausedV1 { uint256 infoIn = _tokenInfos[bTokenIdxIn]; uint256 infoOut = _tokenInfos[bTokenIdxOut]; ( uint256 bTokenOutAmount, uint256 adminFee ) = _getSwapAmount(infoIn, infoOut, bTokenInAmount); require(bTokenOutAmount >= bTokenOutMin, "Returned bTokenAmount < asked"); _transferIn(infoIn, bTokenInAmount); _transferOut(infoOut, bTokenOutAmount, adminFee); emit Swap( msg.sender, bTokenIdxIn, bTokenIdxOut, bTokenInAmount, bTokenOutAmount ); } /* * @dev Swap tokens given all token amounts * The amounts are pre-fee amounts, and the user will provide max fee expected. * Currently, do not support penalty. * @param inOutFlag - 0 means deposit, and 1 means withdraw with highest bit indicating mint/burn lp token * @param lpTokenMintedMinOrBurnedMax - amount of lp token to be minted/burnt * @param maxFee - maximum percentage of fee will be collected for withdrawal * @param amounts - list of unnormalized amounts of each token */ function swapAll( uint256 inOutFlag, uint256 lpTokenMintedMinOrBurnedMax, uint256 maxFee, uint256[] calldata amounts ) external nonReentrantAndUnpausedV1 { // Gas saving: Use cached balances/totalBalance without accrued interest since last rebalance. ( uint256[] memory balances, uint256[] memory infos, uint256 oldTotalBalance ) = _getBalancesAndInfos(); // Make sure _totalBalance = oldTotalBalance = sum(_getBalance()'s) _collectReward(oldTotalBalance); require (amounts.length == balances.length, "swapAll amounts length != ntokens"); uint256 newTotalBalance = 0; uint256 depositAmount = 0; { // avoid stack too deep error uint256[] memory newBalances = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { uint256 normalizedAmount = _normalizeBalance(infos[i]).mul(amounts[i]); if (((inOutFlag >> i) & 1) == 0) { // In depositAmount = depositAmount.add(normalizedAmount); newBalances[i] = balances[i].add(normalizedAmount); } else { // Out newBalances[i] = balances[i].sub(normalizedAmount); } newTotalBalance = newTotalBalance.add(newBalances[i]); } for (uint256 i = 0; i < balances.length; i++) { // If there is no mint/redeem, and the new total balance >= old one, // then the weight must be non-increasing and thus there is no penalty. if (amounts[i] == 0 && newTotalBalance >= oldTotalBalance) { continue; } /* * Accept the new amount if the following is satisfied * np_i <= max(p_i, w_i) */ if (newBalances[i].mul(W_ONE) <= newTotalBalance.mul(_getSoftWeight(infos[i]))) { continue; } // If no tokens in the pool, only weight contraints will be applied. require( oldTotalBalance != 0 && newBalances[i].mul(oldTotalBalance) <= newTotalBalance.mul(balances[i]), "penalty is not supported in swapAll now" ); } } // Calculate fee rate and mint/burn LP tokens uint256 feeRate = 0; uint256 lpMintedOrBurned = 0; if (newTotalBalance == oldTotalBalance) { // Swap only. No need to burn or mint. lpMintedOrBurned = 0; feeRate = _swapFee; } else if (((inOutFlag >> 255) & 1) == 0) { require (newTotalBalance >= oldTotalBalance, "swapAll mint: new total balance must >= old total balance"); lpMintedOrBurned = newTotalBalance.sub(oldTotalBalance).mul(totalSupply()).div(oldTotalBalance); require(lpMintedOrBurned >= lpTokenMintedMinOrBurnedMax, "LP tokend minted < asked"); feeRate = _swapFee; _mint(msg.sender, lpMintedOrBurned); } else { require (newTotalBalance <= oldTotalBalance, "swapAll redeem: new total balance must <= old total balance"); lpMintedOrBurned = oldTotalBalance.sub(newTotalBalance).mul(totalSupply()).div(oldTotalBalance); require(lpMintedOrBurned <= lpTokenMintedMinOrBurnedMax, "LP tokend burned > offered"); uint256 withdrawAmount = oldTotalBalance - newTotalBalance; /* * The fee is determined by swapAmount * swap_fee + withdrawAmount * withdraw_fee, * where swapAmount = depositAmount if withdrawAmount >= 0. */ feeRate = _swapFee.mul(depositAmount).add(_redeemFee.mul(withdrawAmount)).div(depositAmount + withdrawAmount); _burn(msg.sender, lpMintedOrBurned); } emit SwapAll(msg.sender, amounts, inOutFlag, lpMintedOrBurned); require (feeRate <= maxFee, "swapAll fee is greater than max fee user offered"); for (uint256 i = 0; i < balances.length; i++) { if (amounts[i] == 0) { continue; } if (((inOutFlag >> i) & 1) == 0) { // In _transferIn(infos[i], amounts[i]); } else { // Out (with fee) uint256 fee = amounts[i].mul(feeRate).div(W_ONE); uint256 adminFee = fee.mul(_adminFeePct).div(W_ONE); _transferOut(infos[i], amounts[i].sub(fee), adminFee); } } } /************************************************************************************** * Methods for others *************************************************************************************/ /* @dev Collect admin fee so that _totalBalance == sum(_getBalances()'s) */ function _collectReward(uint256 totalBalance) internal { uint256 oldTotalBalance = _totalBalance; if (totalBalance != oldTotalBalance) { if (totalBalance > oldTotalBalance) { _mint(_rewardCollector, totalSupply().mul(totalBalance - oldTotalBalance).div(oldTotalBalance)); } _totalBalance = totalBalance; } } /* @dev Collect admin fee. Can be called by anyone */ function collectReward() external nonReentrantAndUnpausedV1 { (,,,uint256 totalBalance) = _getBalancesAndWeights(); _collectReward(totalBalance); } function getTokenStats(uint256 bTokenIdx) public view returns (uint256 softWeight, uint256 hardWeight, uint256 balance, uint256 decimals) { require(bTokenIdx < _ntokens, "Backed token is not found!"); uint256 info = _tokenInfos[bTokenIdx]; balance = _getBalance(info).div(_normalizeBalance(info)); softWeight = _getSoftWeight(info); hardWeight = _getHardWeight(info); decimals = ERC20(address(info)).decimals(); } } // File: contracts/Root.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract Root is UpgradeableExtension, SmoothyV1 { constructor( address[] memory tokens, address[] memory yTokens, uint256[] memory decMultipliers, uint256[] memory softWeights, uint256[] memory hardWeights ) public UpgradeableExtension() SmoothyV1(tokens, yTokens, decMultipliers, softWeights, hardWeights) { } function upgradeTo(address newImplementation) external onlyOwner { _upgradeTo(newImplementation); } }
* @dev Return the approx logarithm of a value with log(x) where x <= 1.1. All values are in integers with (1e18 == 1.0). Requirements: - input value x must be greater than 1e18/
function _logApprox(uint256 x) internal pure returns (uint256 y) { uint256 one = W_ONE; require(x >= one, "logApprox: x must >= 1"); uint256 z = x - one; uint256 zz = z.mul(z).div(one); uint256 zzz = zz.mul(z).div(one); uint256 zzzz = zzz.mul(z).div(one); uint256 zzzzz = zzzz.mul(z).div(one); return z.sub(zz.div(2)).add(zzz.div(3)).sub(zzzz.div(4)).add(zzzzz.div(5)); }
523,967
[ 1, 990, 326, 10818, 613, 31249, 434, 279, 460, 598, 613, 12, 92, 13, 1625, 619, 1648, 404, 18, 21, 18, 4826, 924, 854, 316, 12321, 598, 261, 21, 73, 2643, 422, 404, 18, 20, 2934, 29076, 30, 300, 810, 460, 619, 1297, 506, 6802, 2353, 404, 73, 2643, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 1330, 25789, 12, 11890, 5034, 619, 13, 2713, 16618, 1135, 261, 11890, 5034, 677, 13, 288, 203, 3639, 2254, 5034, 1245, 273, 678, 67, 5998, 31, 203, 203, 3639, 2583, 12, 92, 1545, 1245, 16, 315, 1330, 25789, 30, 619, 1297, 1545, 404, 8863, 203, 203, 3639, 2254, 5034, 998, 273, 619, 300, 1245, 31, 203, 3639, 2254, 5034, 11273, 273, 998, 18, 16411, 12, 94, 2934, 2892, 12, 476, 1769, 203, 3639, 2254, 5034, 998, 6378, 273, 11273, 18, 16411, 12, 94, 2934, 2892, 12, 476, 1769, 203, 3639, 2254, 5034, 998, 6378, 94, 273, 998, 6378, 18, 16411, 12, 94, 2934, 2892, 12, 476, 1769, 203, 3639, 2254, 5034, 998, 6378, 6378, 273, 998, 6378, 94, 18, 16411, 12, 94, 2934, 2892, 12, 476, 1769, 203, 3639, 327, 998, 18, 1717, 12, 6378, 18, 2892, 12, 22, 13, 2934, 1289, 12, 6378, 94, 18, 2892, 12, 23, 13, 2934, 1717, 12, 6378, 6378, 18, 2892, 12, 24, 13, 2934, 1289, 12, 6378, 6378, 94, 18, 2892, 12, 25, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//HEXBET.sol // // pragma solidity 0.6.4; import "./SafeMath.sol"; import "./IERC20.sol"; import "./HEX.sol"; import "./Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function 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)); } /** * @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"); } } } //Uniswap factory interface interface UniswapFactoryInterface { // Create Exchange function createExchange(address token) external returns (address exchange); // Get Exchange and Token Info function getExchange(address token) external view returns (address exchange); function getToken(address exchange) external view returns (address token); function getTokenWithId(uint256 tokenId) external view returns (address token); // Never use function initializeFactory(address template) external; } //Uniswap Interface interface UniswapExchangeInterface { // Address of ERC20 token sold on this exchange function tokenAddress() external view returns (address token); // Address of Uniswap Factory function factoryAddress() external view returns (address factory); // Provide Liquidity function addLiquidity(uint256 min_liquidity, uint256 max_tokens, uint256 deadline) external payable returns (uint256); function removeLiquidity(uint256 amount, uint256 min_eth, uint256 min_tokens, uint256 deadline) external returns (uint256, uint256); // Get Prices function getEthToTokenInputPrice(uint256 eth_sold) external view returns (uint256 tokens_bought); function getEthToTokenOutputPrice(uint256 tokens_bought) external view returns (uint256 eth_sold); function getTokenToEthInputPrice(uint256 tokens_sold) external view returns (uint256 eth_bought); function getTokenToEthOutputPrice(uint256 eth_bought) external view returns (uint256 tokens_sold); // Trade ETH to ERC20 function ethToTokenSwapInput(uint256 min_tokens, uint256 deadline) external payable returns (uint256 tokens_bought); function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external payable returns (uint256 tokens_bought); function ethToTokenSwapOutput(uint256 tokens_bought, uint256 deadline) external payable returns (uint256 eth_sold); function ethToTokenTransferOutput(uint256 tokens_bought, uint256 deadline, address recipient) external payable returns (uint256 eth_sold); // Trade ERC20 to ETH function tokenToEthSwapInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline) external returns (uint256 eth_bought); function tokenToEthTransferInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient) external returns (uint256 eth_bought); function tokenToEthSwapOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline) external returns (uint256 tokens_sold); function tokenToEthTransferOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient) external returns (uint256 tokens_sold); // Trade ERC20 to ERC20 function tokenToTokenSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address token_addr) external returns (uint256 tokens_bought); function tokenToTokenTransferInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_bought); function tokenToTokenSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address token_addr) external returns (uint256 tokens_sold); function tokenToTokenTransferOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_sold); // Trade ERC20 to Custom Pool function tokenToExchangeSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address exchange_addr) external returns (uint256 tokens_bought); function tokenToExchangeTransferInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address exchange_addr) external returns (uint256 tokens_bought); function tokenToExchangeSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address exchange_addr) external returns (uint256 tokens_sold); function tokenToExchangeTransferOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address exchange_addr) external returns (uint256 tokens_sold); } //////////////////////////////////////////////// ////////////////////EVENTS///////////////////// ////////////////////////////////////////////// contract TokenEvents { //when a user locks tokens event TokenLock( address indexed user, uint value ); //when a user unlocks tokens event TokenUnlock( address indexed user, uint value ); //when founder tokens are locked event FounderLock ( uint hxbAmt, uint timestamp ); //when founder tokens are unlocked event FounderUnlock ( uint hxbAmt, uint timestamp ); } ////////////////////////////////////// //////////HEXBET TOKEN CONTRACT//////// //////////////////////////////////// contract HEXBET is IERC20, TokenEvents { using SafeMath for uint256; using SafeERC20 for HEXBET; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; //uniswap setup (used in setup only) address internal uniFactory = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; address internal uniETHHEX = 0x05cDe89cCfa0adA8C88D5A23caaa79Ef129E7883; address public uniETHHXB = address(0); UniswapExchangeInterface internal uniHEXInterface = UniswapExchangeInterface(uniETHHEX); UniswapExchangeInterface internal uniHXBInterface; UniswapFactoryInterface internal uniFactoryInterface = UniswapFactoryInterface(uniFactory); //hex contract setup address internal hexAddress = 0x2b591e99afE9f32eAA6214f7B7629768c40Eeb39; HEX internal hexInterface = HEX(hexAddress); //mint / lock uint public unlockLvl = 0; uint public founderLockStartTimestamp = 0; uint public founderLockDayLength = 3650;//10 years (10% released every year) uint public founderLockedTokens = 0; uint private allFounderLocked = 0; bool public mintBlock;//disables any more tokens ever being minted once _totalSupply reaches _maxSupply uint public mintRatio = 1000; //inital @ 1000, raises uint public minLockDayLength = 7; // min days to lock uint internal daySeconds = 86400; // seconds in a day uint public totalLocked = 0; mapping (address => uint) public tokenLockedBalances;//balance of HXB locked mapped by user //tokenomics uint256 public _maxSupply = 50000000000000000000;// max supply @ 500B uint256 internal _totalSupply; string public constant name = "hex.bet"; string public constant symbol = "HXB"; uint public constant decimals = 8; //multisig address payable internal MULTISIG = 0x35C7a87EbC3E9fBfd2a31579c70f0A2A8D4De4c5; //admin address payable internal _p1 = 0xD64FF89558Cd0EA20Ae7aA032873d290801865f3; address payable internal _p2 = 0xbf1984B12878c6A25f0921535c76C05a60bdEf39; bool private sync; //minters address[] public minterAddresses;// future contracts to enable minting of HXB relative to HEX mapping(address => bool) admins; mapping(address => bool) minters; mapping (address => Locked) public locked; struct Locked{ uint256 lockStartTimestamp; uint256 totalEarnedInterest; } modifier onlyMultisig(){ require(msg.sender == MULTISIG, "not authorized"); _; } modifier onlyAdmins(){ require(admins[msg.sender], "not an admin"); _; } modifier onlyMinters(){ require(minters[msg.sender], "not a minter"); _; } //protects against potential reentrancy modifier synchronized { require(!sync, "Sync lock"); sync = true; _; sync = false; } constructor() public { admins[_p1] = true; admins[_p2] = true; //mint founder tokens mintFounderTokens(_maxSupply.mul(20).div(100));//20% of max supply //create uni exchange uniETHHXB = uniFactoryInterface.createExchange(address(this)); uniHXBInterface = UniswapExchangeInterface(uniETHHXB); } //fallback for eth sent to contract - auto distribute as donation receive() external payable{ donate(); } function _initialLiquidity() public payable onlyAdmins synchronized { require(msg.value >= 0.001 ether, "eth value too low"); //add liquidity uint heartsForEth = uniHEXInterface.getEthToTokenInputPrice(msg.value);//price of eth value in hex uint hxb = heartsForEth / mintRatio; _mint(address(this), hxb);//mint tokens to this contract this.safeApprove(uniETHHXB, hxb);//approve uni exchange contract uniHXBInterface.addLiquidity{value:msg.value}(0, hxb, (now + 15 minutes)); //send tokens and eth to uni as liquidity*/ } /** * @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 override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view 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 override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].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 returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][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 returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][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 { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply unless mintBLock is true * * 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 { uint256 amt = amount; require(account != address(0), "ERC20: mint to the zero address"); if(!mintBlock){ if(_totalSupply < _maxSupply){ if(_totalSupply.add(amt) > _maxSupply){ amt = _maxSupply.sub(_totalSupply); _totalSupply = _maxSupply; mintBlock = true; } else{ _totalSupply = _totalSupply.add(amt); if(_totalSupply >= _maxSupply.mul(30).div(100)){ mintRatio = 2000; if(_totalSupply >= _maxSupply.mul(40).div(100)){ mintRatio = 3000; if(_totalSupply >= _maxSupply.mul(50).div(100)){ mintRatio = 4000; if(_totalSupply >= _maxSupply.mul(60).div(100)){ mintRatio = 5000; if(_totalSupply >= _maxSupply.mul(70).div(100)){ mintRatio = 6000; if(_totalSupply >= _maxSupply.mul(80).div(100)){ mintRatio = 8000; if(_totalSupply >= _maxSupply.mul(90).div(100)){ mintRatio = 10000; } } } } } } } } _balances[account] = _balances[account].add(amt); emit Transfer(address(0), account, amt); } } } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _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 { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount, "ERC20: burn amount exceeds allowance")); } /** * @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);//from address(0) for minting /** * @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); //mint HXB to founders (only ever called in constructor) function mintFounderTokens(uint tokens) internal synchronized returns(bool) { require(tokens <= _maxSupply.mul(20).div(100), "founder tokens cannot be over 20%"); _mint(_p1, tokens/4);//mint HXB _mint(_p2, tokens/4);//mint HXB _mint(address(this), tokens/2);//mint HXB to be locked for 10 years, 10% unlocked every year founderLock(tokens/2); return true; } function founderLock(uint tokens) internal { founderLockStartTimestamp = now; founderLockedTokens = tokens; allFounderLocked = tokens; emit FounderLock(tokens, founderLockStartTimestamp); } function unlock() public onlyAdmins synchronized { uint sixMonths = founderLockDayLength/10; require(unlockLvl < 10, "token unlock complete"); require(founderLockStartTimestamp.add(sixMonths.mul(daySeconds)) <= now, "tokens cannot be unlocked yet");//must be at least over 6 months uint value = allFounderLocked/10; if(founderLockStartTimestamp.add((sixMonths).mul(daySeconds)) <= now && unlockLvl == 0){ unlockLvl++; founderLockedTokens = founderLockedTokens.sub(value); transfer(_p1, value.div(2)); transfer(_p2, value.div(2)); } else if(founderLockStartTimestamp.add((sixMonths * 2).mul(daySeconds)) <= now && unlockLvl == 1){ unlockLvl++; founderLockedTokens = founderLockedTokens.sub(value); transfer(_p1, value.div(2)); transfer(_p2, value.div(2)); } else if(founderLockStartTimestamp.add((sixMonths * 3).mul(daySeconds)) <= now && unlockLvl == 2){ unlockLvl++; founderLockedTokens = founderLockedTokens.sub(value); transfer(_p1, value.div(2)); transfer(_p2, value.div(2)); } else if(founderLockStartTimestamp.add((sixMonths * 4).mul(daySeconds)) <= now && unlockLvl == 3){ unlockLvl++; founderLockedTokens = founderLockedTokens.sub(value); transfer(_p1, value.div(2)); transfer(_p2, value.div(2)); } else if(founderLockStartTimestamp.add((sixMonths * 5).mul(daySeconds)) <= now && unlockLvl == 4){ unlockLvl++; founderLockedTokens = founderLockedTokens.sub(value); transfer(_p1, value.div(2)); transfer(_p2, value.div(2)); } else if(founderLockStartTimestamp.add((sixMonths * 6).mul(daySeconds)) <= now && unlockLvl == 5){ unlockLvl++; founderLockedTokens = founderLockedTokens.sub(value); transfer(_p1, value.div(2)); transfer(_p2, value.div(2)); } else if(founderLockStartTimestamp.add((sixMonths * 7).mul(daySeconds)) <= now && unlockLvl == 6){ unlockLvl++; founderLockedTokens = founderLockedTokens.sub(value); transfer(_p1, value.div(2)); transfer(_p2, value.div(2)); } else if(founderLockStartTimestamp.add((sixMonths * 8).mul(daySeconds)) <= now && unlockLvl == 7) { unlockLvl++; founderLockedTokens = founderLockedTokens.sub(value); transfer(_p1, value.div(2)); transfer(_p2, value.div(2)); } else if(founderLockStartTimestamp.add((sixMonths * 9).mul(daySeconds)) <= now && unlockLvl == 8){ unlockLvl++; founderLockedTokens = founderLockedTokens.sub(value); transfer(_p1, value.div(2)); transfer(_p2, value.div(2)); } else if(founderLockStartTimestamp.add((sixMonths * 10).mul(daySeconds)) <= now && unlockLvl == 9){ unlockLvl++; if(founderLockedTokens >= value){ founderLockedTokens = founderLockedTokens.sub(value); } else{ value = founderLockedTokens; founderLockedTokens = 0; } transfer(_p1, value.div(2)); transfer(_p2, value.div(2)); } else{ revert(); } emit FounderUnlock(value, now); } //////////////////////////////////////////////////////// /////////////////PUBLIC FACING - HXB CONTROL////////// ////////////////////////////////////////////////////// //lock HXB tokens to contract function LockTokens(uint amt) public { require(amt > 0, "zero input"); require(tokenBalance() >= amt, "Error: insufficient balance");//ensure user has enough funds if(isLockFinished(msg.sender)){ UnlockTokens();//unlocks all currently locked tokens + profit } //update balances tokenLockedBalances[msg.sender] = tokenLockedBalances[msg.sender].add(amt); totalLocked = totalLocked.add(amt); locked[msg.sender].lockStartTimestamp = now; _transfer(msg.sender, address(this), amt);//make transfer emit TokenLock(msg.sender, amt); } //unlock HXB tokens from contract function UnlockTokens() public synchronized { require(tokenLockedBalances[msg.sender] > 0,"Error: unsufficient locked balance");//ensure user has enough locked funds require(isLockFinished(msg.sender), "tokens cannot be unlocked yet. min 7 day lock"); uint amt = tokenLockedBalances[msg.sender]; uint256 interest = calcLockingRewards(msg.sender); _mint(msg.sender, interest);//mint HXB - total unlocked / 1000 * (minLockDayLength + days past) locked[msg.sender].totalEarnedInterest += interest; tokenLockedBalances[msg.sender] = 0; locked[msg.sender].lockStartTimestamp = 0; totalLocked = totalLocked.sub(amt); _transfer(address(this), msg.sender, amt);//make transfer emit TokenUnlock(msg.sender, amt); } //returns locking reward in hxb function calcLockingRewards(address _user) public view returns(uint) { return (tokenLockedBalances[_user].div(2500) * (minLockDayLength + daysPastMinLockTime())); } //returns amount of days locked past min lock time of 7 days function daysPastMinLockTime() public view returns(uint) { uint daysPast = now.sub(locked[msg.sender].lockStartTimestamp).div(daySeconds); if(daysPast >= minLockDayLength){ return daysPast - minLockDayLength;// returns 0 if under 1 day passed } else{ return 0; } } //mint HXB to address ( for use in external contracts within the ecosystem) function mintHXB(uint value, address receiver) public onlyMinters returns(bool) { uint amt = value.div(mintRatio); address minter = receiver; _mint(minter, amt);//mint HXB return true; } /////////////////////////////// ////////ADMIN ONLY////////////// /////////////////////////////// //allows addition of contract addresses that can call this contracts mint function. function addMinter(address minter) public onlyMultisig returns (bool) { minters[minter] = true; minterAddresses.push(minter); return true; } /////////////////////////////// ////////VIEW ONLY////////////// /////////////////////////////// //total HXB locked in contract function totalLockedTokenBalance() public view returns (uint256) { return totalLocked; } //HXB balance of caller function tokenBalance() public view returns (uint256) { return balanceOf(msg.sender); } // function isLockFinished(address _user) public view returns(bool) { if(locked[_user].lockStartTimestamp == 0){ return false; } else{ return locked[_user].lockStartTimestamp.add((minLockDayLength).mul(daySeconds)) <= now; } } function donate() public payable { require(msg.value > 0); bool success = false; uint256 balance = msg.value; //distribute uint256 share = balance.div(2); (success, ) = _p1.call{value:share}{gas:21000}(''); require(success, "Transfer failed"); (success, ) = _p2.call{value:share}{gas:21000}(''); require(success, "Transfer failed"); } }
* @dev Creates `amount` tokens and assigns them to `account`, increasing the total supply unless mintBLock is true 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 { uint256 amt = amount; require(account != address(0), "ERC20: mint to the zero address"); if(!mintBlock){ if(_totalSupply < _maxSupply){ if(_totalSupply.add(amt) > _maxSupply){ amt = _maxSupply.sub(_totalSupply); _totalSupply = _maxSupply; mintBlock = true; } else{ _totalSupply = _totalSupply.add(amt); if(_totalSupply >= _maxSupply.mul(30).div(100)){ mintRatio = 2000; if(_totalSupply >= _maxSupply.mul(40).div(100)){ mintRatio = 3000; if(_totalSupply >= _maxSupply.mul(50).div(100)){ mintRatio = 4000; if(_totalSupply >= _maxSupply.mul(60).div(100)){ mintRatio = 5000; if(_totalSupply >= _maxSupply.mul(70).div(100)){ mintRatio = 6000; if(_totalSupply >= _maxSupply.mul(80).div(100)){ mintRatio = 8000; if(_totalSupply >= _maxSupply.mul(90).div(100)){ mintRatio = 10000; } } } } } } } } _balances[account] = _balances[account].add(amt); emit Transfer(address(0), account, amt); } } }
11,774,512
[ 1, 2729, 1375, 8949, 68, 2430, 471, 22698, 2182, 358, 1375, 4631, 9191, 21006, 326, 2078, 14467, 3308, 312, 474, 38, 2531, 353, 638, 7377, 1282, 279, 288, 5912, 97, 871, 598, 1375, 2080, 68, 444, 358, 326, 3634, 1758, 18, 29076, 300, 1375, 869, 68, 2780, 506, 326, 3634, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 389, 81, 474, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 2713, 288, 203, 3639, 2254, 5034, 25123, 273, 3844, 31, 203, 3639, 2583, 12, 4631, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 312, 474, 358, 326, 3634, 1758, 8863, 203, 3639, 309, 12, 5, 81, 474, 1768, 15329, 203, 5411, 309, 24899, 4963, 3088, 1283, 411, 389, 1896, 3088, 1283, 15329, 203, 7734, 309, 24899, 4963, 3088, 1283, 18, 1289, 12, 301, 88, 13, 405, 389, 1896, 3088, 1283, 15329, 203, 10792, 25123, 273, 389, 1896, 3088, 1283, 18, 1717, 24899, 4963, 3088, 1283, 1769, 203, 10792, 389, 4963, 3088, 1283, 273, 389, 1896, 3088, 1283, 31, 203, 10792, 312, 474, 1768, 273, 638, 31, 203, 7734, 289, 203, 7734, 469, 95, 203, 10792, 389, 4963, 3088, 1283, 273, 389, 4963, 3088, 1283, 18, 1289, 12, 301, 88, 1769, 203, 10792, 309, 24899, 4963, 3088, 1283, 1545, 389, 1896, 3088, 1283, 18, 16411, 12, 5082, 2934, 2892, 12, 6625, 3719, 95, 203, 13491, 312, 474, 8541, 273, 16291, 31, 203, 13491, 309, 24899, 4963, 3088, 1283, 1545, 389, 1896, 3088, 1283, 18, 16411, 12, 7132, 2934, 2892, 12, 6625, 3719, 95, 203, 18701, 312, 474, 8541, 273, 29839, 31, 203, 18701, 309, 24899, 4963, 3088, 1283, 1545, 389, 1896, 3088, 1283, 18, 16411, 12, 3361, 2934, 2892, 12, 6625, 3719, 95, 203, 27573, 312, 474, 8541, 273, 1059, 3784, 31, 203, 27573, 309, 24899, 4963, 3088, 1283, 1545, 389, 1896, 3088, 1283, 18, 16411, 12, 4848, 2934, 2892, 2 ]
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn'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 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 totalSupply() constant returns (uint256 supply); 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); } /// @title ServiceAllowance. /// /// Provides a way to delegate operation allowance decision to a service contract contract ServiceAllowance { function isTransferAllowed(address _from, address _to, address _sender, address _token, uint _value) public view returns (bool); } /// @title DepositWalletInterface /// /// Defines an interface for a wallet that can be deposited/withdrawn by 3rd contract contract DepositWalletInterface { function deposit(address _asset, address _from, uint256 amount) public returns (uint); function withdraw(address _asset, address _to, uint256 amount) public returns (uint); } /** * @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 { /** * Contract owner address */ address public contractOwner; /** * Contract owner address */ address public pendingContractOwner; function Owned() { contractOwner = msg.sender; } /** * @dev Owner check modifier */ modifier onlyContractOwner() { if (contractOwner == msg.sender) { _; } } /** * @dev Destroy contract and scrub a data * @notice Only owner can call it */ function destroy() onlyContractOwner { suicide(msg.sender); } /** * Prepares ownership pass. * * Can only be called by current owner. * * @param _to address of the next owner. 0x0 is not allowed. * * @return success. */ function changeContractOwnership(address _to) onlyContractOwner() returns(bool) { if (_to == 0x0) { return false; } pendingContractOwner = _to; return true; } /** * Finalize ownership pass. * * Can only be called by pending owner. * * @return success. */ function claimContractOwnership() returns(bool) { if (pendingContractOwner != msg.sender) { return false; } contractOwner = pendingContractOwner; delete pendingContractOwner; return true; } } /** * @title Generic owned destroyable contract */ contract Object is Owned { /** * Common result code. Means everything is fine. */ uint constant OK = 1; uint constant OWNED_ACCESS_DENIED_ONLY_CONTRACT_OWNER = 8; function withdrawnTokens(address[] tokens, address _to) onlyContractOwner returns(uint) { for(uint i=0;i<tokens.length;i++) { address token = tokens[i]; uint balance = ERC20Interface(token).balanceOf(this); if(balance != 0) ERC20Interface(token).transfer(_to,balance); } return OK; } function checkOnlyContractOwner() internal constant returns(uint) { if (contractOwner == msg.sender) { return OK; } return OWNED_ACCESS_DENIED_ONLY_CONTRACT_OWNER; } } contract OracleContractAdapter is Object { event OracleAdded(address _oracle); event OracleRemoved(address _oracle); mapping(address => bool) public oracles; /// @dev Allow access only for oracle modifier onlyOracle { if (oracles[msg.sender]) { _; } } modifier onlyOracleOrOwner { if (oracles[msg.sender] || msg.sender == contractOwner) { _; } } /// @notice Add oracles to whitelist. /// /// @param _whitelist user list. function addOracles(address[] _whitelist) onlyContractOwner external returns (uint) { for (uint _idx = 0; _idx < _whitelist.length; ++_idx) { address _oracle = _whitelist[_idx]; if (_oracle != 0x0 && !oracles[_oracle]) { oracles[_oracle] = true; _emitOracleAdded(_oracle); } } return OK; } /// @notice Removes oracles from whitelist. /// /// @param _blacklist user in whitelist. function removeOracles(address[] _blacklist) onlyContractOwner external returns (uint) { for (uint _idx = 0; _idx < _blacklist.length; ++_idx) { address _oracle = _blacklist[_idx]; if (_oracle != 0x0 && oracles[_oracle]) { delete oracles[_oracle]; _emitOracleRemoved(_oracle); } } return OK; } function _emitOracleAdded(address _oracle) internal { OracleAdded(_oracle); } function _emitOracleRemoved(address _oracle) internal { OracleRemoved(_oracle); } } contract ProfiteroleEmitter { event DepositPendingAdded(uint amount, address from, uint timestamp); event BonusesWithdrawn(bytes32 userKey, uint amount, uint timestamp); event Error(uint errorCode); function _emitError(uint _errorCode) internal returns (uint) { Error(_errorCode); return _errorCode; } } contract TreasuryEmitter { event TreasuryDeposited(bytes32 userKey, uint value, uint lockupDate); event TreasuryWithdrawn(bytes32 userKey, uint value); } contract ERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from, address indexed spender, uint256 value); string public symbol; function totalSupply() constant returns (uint256 supply); 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); } /// @title Treasury contract. /// /// Treasury for CCs deposits for particular fund with bmc-days calculations. /// Accept BMC deposits from Continuous Contributors via oracle and /// calculates bmc-days metric for each CC's role. contract Treasury is OracleContractAdapter, ServiceAllowance, TreasuryEmitter { /* ERROR CODES */ uint constant PERCENT_PRECISION = 10000; uint constant TREASURY_ERROR_SCOPE = 108000; uint constant TREASURY_ERROR_TOKEN_NOT_SET_ALLOWANCE = TREASURY_ERROR_SCOPE + 1; using SafeMath for uint; struct LockedDeposits { uint counter; mapping(uint => uint) index2Date; mapping(uint => uint) date2deposit; } struct Period { uint transfersCount; uint totalBmcDays; uint bmcDaysPerDay; uint startDate; mapping(bytes32 => uint) user2bmcDays; mapping(bytes32 => uint) user2lastTransferIdx; mapping(bytes32 => uint) user2balance; mapping(uint => uint) transfer2date; } /* FIELDS */ address token; address profiterole; uint periodsCount; mapping(uint => Period) periods; mapping(uint => uint) periodDate2periodIdx; mapping(bytes32 => uint) user2lastPeriodParticipated; mapping(bytes32 => LockedDeposits) user2lockedDeposits; /* MODIFIERS */ /// @dev Only profiterole contract allowed to invoke guarded functions modifier onlyProfiterole { require(profiterole == msg.sender); _; } /* PUBLIC */ function Treasury(address _token) public { require(address(_token) != 0x0); token = _token; periodsCount = 1; } function init(address _profiterole) public onlyContractOwner returns (uint) { require(_profiterole != 0x0); profiterole = _profiterole; return OK; } /// @notice Do not accept Ether transfers function() payable public { revert(); } /* EXTERNAL */ /// @notice Deposits tokens on behalf of users /// Allowed only for oracle. /// /// @param _userKey aggregated user key (user ID + role ID) /// @param _value amount of tokens to deposit /// @param _feeAmount amount of tokens that will be taken from _value as fee /// @param _feeAddress destination address for fee transfer /// @param _lockupDate lock up date for deposit. Until that date the deposited value couldn't be withdrawn /// /// @return result code of an operation function deposit(bytes32 _userKey, uint _value, uint _feeAmount, address _feeAddress, uint _lockupDate) external onlyOracle returns (uint) { require(_userKey != bytes32(0)); require(_value != 0); require(_feeAmount < _value); ERC20 _token = ERC20(token); if (_token.allowance(msg.sender, address(this)) < _value) { return TREASURY_ERROR_TOKEN_NOT_SET_ALLOWANCE; } uint _depositedAmount = _value - _feeAmount; _makeDepositForPeriod(_userKey, _depositedAmount, _lockupDate); uint _periodsCount = periodsCount; user2lastPeriodParticipated[_userKey] = _periodsCount; delete periods[_periodsCount].startDate; if (!_token.transferFrom(msg.sender, address(this), _value)) { revert(); } if (!(_feeAddress == 0x0 || _feeAmount == 0 || _token.transfer(_feeAddress, _feeAmount))) { revert(); } TreasuryDeposited(_userKey, _depositedAmount, _lockupDate); return OK; } /// @notice Withdraws deposited tokens on behalf of users /// Allowed only for oracle /// /// @param _userKey aggregated user key (user ID + role ID) /// @param _value an amount of tokens that is requrested to withdraw /// @param _withdrawAddress address to withdraw; should not be 0x0 /// @param _feeAmount amount of tokens that will be taken from _value as fee /// @param _feeAddress destination address for fee transfer /// /// @return result of an operation function withdraw(bytes32 _userKey, uint _value, address _withdrawAddress, uint _feeAmount, address _feeAddress) external onlyOracle returns (uint) { require(_userKey != bytes32(0)); require(_value != 0); require(_feeAmount < _value); _makeWithdrawForPeriod(_userKey, _value); uint _periodsCount = periodsCount; user2lastPeriodParticipated[_userKey] = periodsCount; delete periods[_periodsCount].startDate; ERC20 _token = ERC20(token); if (!(_feeAddress == 0x0 || _feeAmount == 0 || _token.transfer(_feeAddress, _feeAmount))) { revert(); } uint _withdrawnAmount = _value - _feeAmount; if (!_token.transfer(_withdrawAddress, _withdrawnAmount)) { revert(); } TreasuryWithdrawn(_userKey, _withdrawnAmount); return OK; } /// @notice Gets shares (in percents) the user has on provided date /// /// @param _userKey aggregated user key (user ID + role ID) /// @param _date date where period ends /// /// @return percent from total amount of bmc-days the treasury has on this date. /// Use PERCENT_PRECISION to get right precision function getSharesPercentForPeriod(bytes32 _userKey, uint _date) public view returns (uint) { uint _periodIdx = periodDate2periodIdx[_date]; if (_date != 0 && _periodIdx == 0) { return 0; } if (_date == 0) { _date = now; _periodIdx = periodsCount; } uint _bmcDays = _getBmcDaysAmountForUser(_userKey, _date, _periodIdx); uint _totalBmcDeposit = _getTotalBmcDaysAmount(_date, _periodIdx); return _totalBmcDeposit != 0 ? _bmcDays * PERCENT_PRECISION / _totalBmcDeposit : 0; } /// @notice Gets user balance that is deposited /// @param _userKey aggregated user key (user ID + role ID) /// @return an amount of tokens deposited on behalf of user function getUserBalance(bytes32 _userKey) public view returns (uint) { uint _lastPeriodForUser = user2lastPeriodParticipated[_userKey]; if (_lastPeriodForUser == 0) { return 0; } if (_lastPeriodForUser <= periodsCount.sub(1)) { return periods[_lastPeriodForUser].user2balance[_userKey]; } return periods[periodsCount].user2balance[_userKey]; } /// @notice Gets amount of locked deposits for user /// @param _userKey aggregated user key (user ID + role ID) /// @return an amount of tokens locked function getLockedUserBalance(bytes32 _userKey) public returns (uint) { return _syncLockedDepositsAmount(_userKey); } /// @notice Gets list of locked up deposits with dates when they will be available to withdraw /// @param _userKey aggregated user key (user ID + role ID) /// @return { /// "_lockupDates": "list of lockup dates of deposits", /// "_deposits": "list of deposits" /// } function getLockedUserDeposits(bytes32 _userKey) public view returns (uint[] _lockupDates, uint[] _deposits) { LockedDeposits storage _lockedDeposits = user2lockedDeposits[_userKey]; uint _lockedDepositsCounter = _lockedDeposits.counter; _lockupDates = new uint[](_lockedDepositsCounter); _deposits = new uint[](_lockedDepositsCounter); uint _pointer = 0; for (uint _idx = 1; _idx < _lockedDepositsCounter; ++_idx) { uint _lockDate = _lockedDeposits.index2Date[_idx]; if (_lockDate > now) { _lockupDates[_pointer] = _lockDate; _deposits[_pointer] = _lockedDeposits.date2deposit[_lockDate]; ++_pointer; } } } /// @notice Gets total amount of bmc-day accumulated due provided date /// @param _date date where period ends /// @return an amount of bmc-days function getTotalBmcDaysAmount(uint _date) public view returns (uint) { return _getTotalBmcDaysAmount(_date, periodsCount); } /// @notice Makes a checkpoint to start counting a new period /// @dev Should be used only by Profiterole contract function addDistributionPeriod() public onlyProfiterole returns (uint) { uint _periodsCount = periodsCount; uint _nextPeriod = _periodsCount.add(1); periodDate2periodIdx[now] = _periodsCount; Period storage _previousPeriod = periods[_periodsCount]; uint _totalBmcDeposit = _getTotalBmcDaysAmount(now, _periodsCount); periods[_nextPeriod].startDate = now; periods[_nextPeriod].bmcDaysPerDay = _previousPeriod.bmcDaysPerDay; periods[_nextPeriod].totalBmcDays = _totalBmcDeposit; periodsCount = _nextPeriod; return OK; } function isTransferAllowed(address, address, address, address, uint) public view returns (bool) { return true; } /* INTERNAL */ function _makeDepositForPeriod(bytes32 _userKey, uint _value, uint _lockupDate) internal { Period storage _transferPeriod = periods[periodsCount]; _transferPeriod.user2bmcDays[_userKey] = _getBmcDaysAmountForUser(_userKey, now, periodsCount); _transferPeriod.totalBmcDays = _getTotalBmcDaysAmount(now, periodsCount); _transferPeriod.bmcDaysPerDay = _transferPeriod.bmcDaysPerDay.add(_value); uint _userBalance = getUserBalance(_userKey); uint _updatedTransfersCount = _transferPeriod.transfersCount.add(1); _transferPeriod.transfersCount = _updatedTransfersCount; _transferPeriod.transfer2date[_transferPeriod.transfersCount] = now; _transferPeriod.user2balance[_userKey] = _userBalance.add(_value); _transferPeriod.user2lastTransferIdx[_userKey] = _updatedTransfersCount; _registerLockedDeposits(_userKey, _value, _lockupDate); } function _makeWithdrawForPeriod(bytes32 _userKey, uint _value) internal { uint _userBalance = getUserBalance(_userKey); uint _lockedBalance = _syncLockedDepositsAmount(_userKey); require(_userBalance.sub(_lockedBalance) >= _value); uint _periodsCount = periodsCount; Period storage _transferPeriod = periods[_periodsCount]; _transferPeriod.user2bmcDays[_userKey] = _getBmcDaysAmountForUser(_userKey, now, _periodsCount); uint _totalBmcDeposit = _getTotalBmcDaysAmount(now, _periodsCount); _transferPeriod.totalBmcDays = _totalBmcDeposit; _transferPeriod.bmcDaysPerDay = _transferPeriod.bmcDaysPerDay.sub(_value); uint _updatedTransferCount = _transferPeriod.transfersCount.add(1); _transferPeriod.transfer2date[_updatedTransferCount] = now; _transferPeriod.user2lastTransferIdx[_userKey] = _updatedTransferCount; _transferPeriod.user2balance[_userKey] = _userBalance.sub(_value); _transferPeriod.transfersCount = _updatedTransferCount; } function _registerLockedDeposits(bytes32 _userKey, uint _amount, uint _lockupDate) internal { if (_lockupDate <= now) { return; } LockedDeposits storage _lockedDeposits = user2lockedDeposits[_userKey]; uint _lockedBalance = _lockedDeposits.date2deposit[_lockupDate]; if (_lockedBalance == 0) { uint _lockedDepositsCounter = _lockedDeposits.counter.add(1); _lockedDeposits.counter = _lockedDepositsCounter; _lockedDeposits.index2Date[_lockedDepositsCounter] = _lockupDate; } _lockedDeposits.date2deposit[_lockupDate] = _lockedBalance.add(_amount); } function _syncLockedDepositsAmount(bytes32 _userKey) internal returns (uint _lockedSum) { LockedDeposits storage _lockedDeposits = user2lockedDeposits[_userKey]; uint _lockedDepositsCounter = _lockedDeposits.counter; for (uint _idx = 1; _idx <= _lockedDepositsCounter; ++_idx) { uint _lockDate = _lockedDeposits.index2Date[_idx]; if (_lockDate <= now) { _lockedDeposits.index2Date[_idx] = _lockedDeposits.index2Date[_lockedDepositsCounter]; delete _lockedDeposits.index2Date[_lockedDepositsCounter]; delete _lockedDeposits.date2deposit[_lockDate]; _lockedDepositsCounter = _lockedDepositsCounter.sub(1); continue; } _lockedSum = _lockedSum.add(_lockedDeposits.date2deposit[_lockDate]); } _lockedDeposits.counter = _lockedDepositsCounter; } function _getBmcDaysAmountForUser(bytes32 _userKey, uint _date, uint _periodIdx) internal view returns (uint) { uint _lastPeriodForUserIdx = user2lastPeriodParticipated[_userKey]; if (_lastPeriodForUserIdx == 0) { return 0; } Period storage _transferPeriod = _lastPeriodForUserIdx <= _periodIdx ? periods[_lastPeriodForUserIdx] : periods[_periodIdx]; uint _lastTransferDate = _transferPeriod.transfer2date[_transferPeriod.user2lastTransferIdx[_userKey]]; // NOTE: It is an intended substraction separation to correctly round dates uint _daysLong = (_date / 1 days) - (_lastTransferDate / 1 days); uint _bmcDays = _transferPeriod.user2bmcDays[_userKey]; return _bmcDays.add(_transferPeriod.user2balance[_userKey] * _daysLong); } /* PRIVATE */ function _getTotalBmcDaysAmount(uint _date, uint _periodIdx) private view returns (uint) { Period storage _depositPeriod = periods[_periodIdx]; uint _transfersCount = _depositPeriod.transfersCount; uint _lastRecordedDate = _transfersCount != 0 ? _depositPeriod.transfer2date[_transfersCount] : _depositPeriod.startDate; if (_lastRecordedDate == 0) { return 0; } // NOTE: It is an intended substraction separation to correctly round dates uint _daysLong = (_date / 1 days).sub((_lastRecordedDate / 1 days)); uint _totalBmcDeposit = _depositPeriod.totalBmcDays.add(_depositPeriod.bmcDaysPerDay.mul(_daysLong)); return _totalBmcDeposit; } } /// @title Profiterole contract /// Collector and distributor for creation and redemption fees. /// Accepts bonus tokens from EmissionProvider, BurningMan or other distribution source. /// Calculates CCs shares in bonuses. Uses Treasury Contract as source of shares in bmc-days. /// Allows to withdraw bonuses on request. contract Profiterole is OracleContractAdapter, ServiceAllowance, ProfiteroleEmitter { uint constant PERCENT_PRECISION = 10000; uint constant PROFITEROLE_ERROR_SCOPE = 102000; uint constant PROFITEROLE_ERROR_INSUFFICIENT_DISTRIBUTION_BALANCE = PROFITEROLE_ERROR_SCOPE + 1; uint constant PROFITEROLE_ERROR_INSUFFICIENT_BONUS_BALANCE = PROFITEROLE_ERROR_SCOPE + 2; uint constant PROFITEROLE_ERROR_TRANSFER_ERROR = PROFITEROLE_ERROR_SCOPE + 3; using SafeMath for uint; struct Balance { uint left; bool initialized; } struct Deposit { uint balance; uint left; uint nextDepositDate; mapping(bytes32 => Balance) leftToWithdraw; } struct UserBalance { uint lastWithdrawDate; } mapping(address => bool) distributionSourcesList; mapping(bytes32 => UserBalance) bonusBalances; mapping(uint => Deposit) public distributionDeposits; uint public firstDepositDate; uint public lastDepositDate; address public bonusToken; address public treasury; address public wallet; /// @dev Guards functions only for distributionSource invocations modifier onlyDistributionSource { if (!distributionSourcesList[msg.sender]) { revert(); } _; } function Profiterole(address _bonusToken, address _treasury, address _wallet) public { require(_bonusToken != 0x0); require(_treasury != 0x0); require(_wallet != 0x0); bonusToken = _bonusToken; treasury = _treasury; wallet = _wallet; } function() payable public { revert(); } /* EXTERNAL */ /// @notice Sets new treasury address /// Only for contract owner. function updateTreasury(address _treasury) external onlyContractOwner returns (uint) { require(_treasury != 0x0); treasury = _treasury; return OK; } /// @notice Sets new wallet address for profiterole /// Only for contract owner. function updateWallet(address _wallet) external onlyContractOwner returns (uint) { require(_wallet != 0x0); wallet = _wallet; return OK; } /// @notice Add distribution sources to whitelist. /// /// @param _whitelist addresses list. function addDistributionSources(address[] _whitelist) external onlyContractOwner returns (uint) { for (uint _idx = 0; _idx < _whitelist.length; ++_idx) { distributionSourcesList[_whitelist[_idx]] = true; } return OK; } /// @notice Removes distribution sources from whitelist. /// Only for contract owner. /// /// @param _blacklist addresses in whitelist. function removeDistributionSources(address[] _blacklist) external onlyContractOwner returns (uint) { for (uint _idx = 0; _idx < _blacklist.length; ++_idx) { delete distributionSourcesList[_blacklist[_idx]]; } return OK; } /// @notice Allows to withdraw user's bonuses that he deserves due to Treasury shares for /// every distribution period. /// Only oracles allowed to invoke this function. /// /// @param _userKey aggregated user key (user ID + role ID) on behalf of whom bonuses will be withdrawn /// @param _value an amount of tokens to withdraw /// @param _withdrawAddress destination address of withdrawal (usually user's address) /// @param _feeAmount an amount of fee that will be taken from resulted _value /// @param _feeAddress destination address of fee transfer /// /// @return result code of an operation function withdrawBonuses(bytes32 _userKey, uint _value, address _withdrawAddress, uint _feeAmount, address _feeAddress) external onlyOracle returns (uint) { require(_userKey != bytes32(0)); require(_value != 0); require(_feeAmount < _value); require(_withdrawAddress != 0x0); DepositWalletInterface _wallet = DepositWalletInterface(wallet); ERC20Interface _bonusToken = ERC20Interface(bonusToken); if (_bonusToken.balanceOf(_wallet) < _value) { return _emitError(PROFITEROLE_ERROR_INSUFFICIENT_BONUS_BALANCE); } if (OK != _withdrawBonuses(_userKey, _value)) { revert(); } if (!(_feeAddress == 0x0 || _feeAmount == 0 || OK == _wallet.withdraw(_bonusToken, _feeAddress, _feeAmount))) { revert(); } if (OK != _wallet.withdraw(_bonusToken, _withdrawAddress, _value - _feeAmount)) { revert(); } BonusesWithdrawn(_userKey, _value, now); return OK; } /* PUBLIC */ /// @notice Gets total amount of bonuses user has during all distribution periods /// @param _userKey aggregated user key (user ID + role ID) /// @return _sum available amount of bonuses to withdraw function getTotalBonusesAmountAvailable(bytes32 _userKey) public view returns (uint _sum) { uint _startDate = _getCalculationStartDate(_userKey); Treasury _treasury = Treasury(treasury); for ( uint _endDate = lastDepositDate; _startDate <= _endDate && _startDate != 0; _startDate = distributionDeposits[_startDate].nextDepositDate ) { Deposit storage _pendingDeposit = distributionDeposits[_startDate]; Balance storage _userBalance = _pendingDeposit.leftToWithdraw[_userKey]; if (_userBalance.initialized) { _sum = _sum.add(_userBalance.left); } else { uint _sharesPercent = _treasury.getSharesPercentForPeriod(_userKey, _startDate); _sum = _sum.add(_pendingDeposit.balance.mul(_sharesPercent).div(PERCENT_PRECISION)); } } } /// @notice Gets an amount of bonuses user has for concrete distribution date /// @param _userKey aggregated user key (user ID + role ID) /// @param _distributionDate date of distribution operation /// @return available amount of bonuses to withdraw for selected distribution date function getBonusesAmountAvailable(bytes32 _userKey, uint _distributionDate) public view returns (uint) { Deposit storage _deposit = distributionDeposits[_distributionDate]; if (_deposit.leftToWithdraw[_userKey].initialized) { return _deposit.leftToWithdraw[_userKey].left; } uint _sharesPercent = Treasury(treasury).getSharesPercentForPeriod(_userKey, _distributionDate); return _deposit.balance.mul(_sharesPercent).div(PERCENT_PRECISION); } /// @notice Gets total amount of deposits that has left after users' bonus withdrawals /// @return amount of deposits available for bonus payments function getTotalDepositsAmountLeft() public view returns (uint _amount) { uint _lastDepositDate = lastDepositDate; for ( uint _startDate = firstDepositDate; _startDate <= _lastDepositDate || _startDate != 0; _startDate = distributionDeposits[_startDate].nextDepositDate ) { _amount = _amount.add(distributionDeposits[_startDate].left); } } /// @notice Gets an amount of deposits that has left after users' bonus withdrawals for selected date /// @param _distributionDate date of distribution operation /// @return amount of deposits available for bonus payments for concrete distribution date function getDepositsAmountLeft(uint _distributionDate) public view returns (uint _amount) { return distributionDeposits[_distributionDate].left; } /// @notice Makes checkmark and deposits tokens on profiterole account /// to pay them later as bonuses for Treasury shares holders. Timestamp of transaction /// counts as the distribution period date. /// Only addresses that were added as a distributionSource are allowed to call this function. /// /// @param _amount an amount of tokens to distribute /// /// @return result code of an operation. /// PROFITEROLE_ERROR_INSUFFICIENT_DISTRIBUTION_BALANCE, PROFITEROLE_ERROR_TRANSFER_ERROR errors /// are possible function distributeBonuses(uint _amount) public onlyDistributionSource returns (uint) { ERC20Interface _bonusToken = ERC20Interface(bonusToken); if (_bonusToken.allowance(msg.sender, address(this)) < _amount) { return _emitError(PROFITEROLE_ERROR_INSUFFICIENT_DISTRIBUTION_BALANCE); } if (!_bonusToken.transferFrom(msg.sender, wallet, _amount)) { return _emitError(PROFITEROLE_ERROR_TRANSFER_ERROR); } if (firstDepositDate == 0) { firstDepositDate = now; } uint _lastDepositDate = lastDepositDate; if (_lastDepositDate != 0) { distributionDeposits[_lastDepositDate].nextDepositDate = now; } lastDepositDate = now; distributionDeposits[now] = Deposit(_amount, _amount, 0); Treasury(treasury).addDistributionPeriod(); DepositPendingAdded(_amount, msg.sender, now); return OK; } function isTransferAllowed(address, address, address, address, uint) public view returns (bool) { return false; } /* PRIVATE */ function _getCalculationStartDate(bytes32 _userKey) private view returns (uint _startDate) { _startDate = bonusBalances[_userKey].lastWithdrawDate; return _startDate != 0 ? _startDate : firstDepositDate; } function _withdrawBonuses(bytes32 _userKey, uint _value) private returns (uint) { uint _startDate = _getCalculationStartDate(_userKey); uint _lastWithdrawDate = _startDate; Treasury _treasury = Treasury(treasury); for ( uint _endDate = lastDepositDate; _startDate <= _endDate && _startDate != 0 && _value > 0; _startDate = distributionDeposits[_startDate].nextDepositDate ) { uint _balanceToWithdraw = _withdrawBonusesFromDeposit(_userKey, _startDate, _value, _treasury); _value = _value.sub(_balanceToWithdraw); } if (_lastWithdrawDate != _startDate) { bonusBalances[_userKey].lastWithdrawDate = _lastWithdrawDate; } if (_value > 0) { revert(); } return OK; } function _withdrawBonusesFromDeposit(bytes32 _userKey, uint _periodDate, uint _value, Treasury _treasury) private returns (uint) { Deposit storage _pendingDeposit = distributionDeposits[_periodDate]; Balance storage _userBalance = _pendingDeposit.leftToWithdraw[_userKey]; uint _balanceToWithdraw; if (_userBalance.initialized) { _balanceToWithdraw = _userBalance.left; } else { uint _sharesPercent = _treasury.getSharesPercentForPeriod(_userKey, _periodDate); _balanceToWithdraw = _pendingDeposit.balance.mul(_sharesPercent).div(PERCENT_PRECISION); _userBalance.initialized = true; } if (_balanceToWithdraw > _value) { _userBalance.left = _balanceToWithdraw - _value; _balanceToWithdraw = _value; } else { delete _userBalance.left; } _pendingDeposit.left = _pendingDeposit.left.sub(_balanceToWithdraw); return _balanceToWithdraw; } }
@dev Guards functions only for distributionSource invocations
modifier onlyDistributionSource { if (!distributionSourcesList[msg.sender]) { revert(); } _; }
1,373,681
[ 1, 6099, 14727, 4186, 1338, 364, 7006, 1830, 27849, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 9606, 1338, 9003, 1830, 288, 203, 3639, 309, 16051, 16279, 8628, 682, 63, 3576, 18, 15330, 5717, 288, 203, 5411, 15226, 5621, 203, 3639, 289, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x3046269Ae463391EE81b529043f46CAd08CEe05E/sources/contracts/NFT/XERC721.sol
* @dev See {IERC721-ownerOf}./
function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _ownerOf(tokenId); if (tokenId >=1 && tokenId <= 1200 && owner == address(0)) { return address(this); } require(owner != address(0), "ERC721: invalid token ID"); return owner; }
2,907,291
[ 1, 9704, 288, 45, 654, 39, 27, 5340, 17, 8443, 951, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3410, 951, 12, 11890, 5034, 1147, 548, 13, 1071, 1476, 5024, 3849, 1135, 261, 2867, 13, 288, 203, 3639, 1758, 3410, 273, 389, 8443, 951, 12, 2316, 548, 1769, 203, 3639, 309, 261, 2316, 548, 1545, 21, 597, 1147, 548, 1648, 2593, 713, 597, 3410, 422, 1758, 12, 20, 3719, 288, 203, 5411, 327, 1758, 12, 2211, 1769, 203, 3639, 289, 203, 3639, 2583, 12, 8443, 480, 1758, 12, 20, 3631, 315, 654, 39, 27, 5340, 30, 2057, 1147, 1599, 8863, 203, 3639, 327, 3410, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IVault.sol"; import "./interfaces/IController.sol"; import "./interfaces/IHarvester.sol"; import "./interfaces/ILegacyController.sol"; import "./interfaces/IManager.sol"; import "./interfaces/IStrategy.sol"; import "./interfaces/ISwap.sol"; /** * @title Harvester * @notice This contract is to be used as a central point to call * harvest on all strategies for any given vault. It has its own * permissions for harvesters (set by the strategist or governance). */ contract Harvester is IHarvester { using SafeMath for uint256; uint256 public constant ONE_HUNDRED_PERCENT = 10000; IManager public immutable override manager; IController public immutable controller; ILegacyController public immutable legacyController; uint256 public override slippage; struct Strategy { uint256 timeout; uint256 lastCalled; address[] addresses; } mapping(address => Strategy) public strategies; mapping(address => bool) public isHarvester; /** * @notice Logged when harvest is called for a strategy */ event Harvest( address indexed controller, address indexed strategy ); /** * @notice Logged when a harvester is set */ event HarvesterSet(address indexed harvester, bool status); /** * @notice Logged when a strategy is added for a vault */ event StrategyAdded(address indexed vault, address indexed strategy, uint256 timeout); /** * @notice Logged when a strategy is removed for a vault */ event StrategyRemoved(address indexed vault, address indexed strategy, uint256 timeout); /** * @param _manager The address of the yAxisMetaVaultManager contract * @param _controller The address of the controller */ constructor( address _manager, address _controller, address _legacyController ) public { manager = IManager(_manager); controller = IController(_controller); legacyController = ILegacyController(_legacyController); } /** * (GOVERNANCE|STRATEGIST)-ONLY FUNCTIONS */ /** * @notice Adds a strategy to the rotation for a given vault and sets a timeout * @param _vault The address of the vault * @param _strategy The address of the strategy * @param _timeout The timeout between harvests */ function addStrategy( address _vault, address _strategy, uint256 _timeout ) external override onlyController { strategies[_vault].addresses.push(_strategy); strategies[_vault].timeout = _timeout; emit StrategyAdded(_vault, _strategy, _timeout); } /** * @notice Removes a strategy from the rotation for a given vault and sets a timeout * @param _vault The address of the vault * @param _strategy The address of the strategy * @param _timeout The timeout between harvests */ function removeStrategy( address _vault, address _strategy, uint256 _timeout ) external override onlyController { uint256 tail = strategies[_vault].addresses.length; uint256 index; bool found; for (uint i; i < tail; i++) { if (strategies[_vault].addresses[i] == _strategy) { index = i; found = true; break; } } if (found) { strategies[_vault].addresses[index] = strategies[_vault].addresses[tail.sub(1)]; strategies[_vault].addresses.pop(); strategies[_vault].timeout = _timeout; emit StrategyRemoved(_vault, _strategy, _timeout); } } /** * @notice Sets the status of a harvester address to be able to call harvest functions * @param _harvester The address of the harvester * @param _status The status to allow the harvester to harvest */ function setHarvester( address _harvester, bool _status ) external onlyStrategist { isHarvester[_harvester] = _status; emit HarvesterSet(_harvester, _status); } function setSlippage( uint256 _slippage ) external onlyStrategist { require(_slippage < ONE_HUNDRED_PERCENT, "!_slippage"); slippage = _slippage; } /** * HARVESTER-ONLY FUNCTIONS */ function earn( address _strategy, address _vault ) external onlyHarvester { IVault(_vault).earn(_strategy); } /** * @notice Harvests a given strategy on the provided controller * @dev This function ignores the timeout * @param _controller The address of the controller * @param _strategy The address of the strategy * @param _estimates The estimated outputs from swaps during harvest */ function harvest( IController _controller, address _strategy, uint256[] calldata _estimates ) public onlyHarvester { _controller.harvestStrategy(_strategy, _estimates); emit Harvest(address(_controller), _strategy); } /** * @notice Harvests the next available strategy for a given vault and * rotates the strategies * @param _vault The address of the vault * @param _estimates The estimated outputs from swaps during harvest */ function harvestNextStrategy( address _vault, uint256[] calldata _estimates ) external { require(canHarvest(_vault), "!canHarvest"); address strategy = strategies[_vault].addresses[0]; harvest(controller, strategy, _estimates); uint256 k = strategies[_vault].addresses.length; if (k > 1) { address[] memory _strategies = new address[](k); for (uint i; i < k-1; i++) { _strategies[i] = strategies[_vault].addresses[i+1]; } _strategies[k-1] = strategy; strategies[_vault].addresses = _strategies; } // solhint-disable-next-line not-rely-on-time strategies[_vault].lastCalled = block.timestamp; } /** * @notice Earns tokens in the LegacyController to the v3 vault * @param _expected The expected amount to deposit after conversion */ function legacyEarn( uint256 _expected ) external onlyHarvester { legacyController.legacyDeposit(_expected); } /** * EXTERNAL VIEW FUNCTIONS */ /** * @notice Returns the addresses of the strategies for a given vault * @param _vault The address of the vault */ function strategyAddresses( address _vault ) external view returns (address[] memory) { return strategies[_vault].addresses; } /** * PUBLIC VIEW FUNCTIONS */ /** * @notice Returns the availability of a vault's strategy to be harvested * @param _vault The address of the vault */ function canHarvest( address _vault ) public view returns (bool) { Strategy storage strategy = strategies[_vault]; // only can harvest if there are strategies, and when sufficient time has elapsed // solhint-disable-next-line not-rely-on-time return (strategy.addresses.length > 0 && strategy.lastCalled <= block.timestamp.sub(strategy.timeout)); } /** * @notice Returns the estimated amount of WETH and YAXIS for the given strategy * @param _strategy The address of the strategy */ function getEstimates( address _strategy ) public view returns (uint256[] memory _estimates) { _estimates = IStrategyExtended(_strategy).getEstimates(); } /** * MODIFIERS */ modifier onlyController() { require(manager.allowedControllers(msg.sender), "!controller"); _; } modifier onlyHarvester() { require(isHarvester[msg.sender], "!harvester"); _; } modifier onlyStrategist() { require(msg.sender == manager.strategist(), "!strategist"); _; } } // 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.12; import "./IManager.sol"; interface IVault { function available() external view returns (uint256); function balance() external view returns (uint256); function deposit(uint256 _amount) external returns (uint256); function earn(address _strategy) external; function gauge() external returns (address); function getLPToken() external view returns (address); function getPricePerFullShare() external view returns (uint256); function getToken() external view returns (address); function manager() external view returns (IManager); function withdraw(uint256 _amount) external; function withdrawAll() external; function withdrawFee(uint256 _amount) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./IManager.sol"; interface IController { function balanceOf() external view returns (uint256); function converter(address _vault) external view returns (address); function earn(address _strategy, address _token, uint256 _amount) external; function investEnabled() external view returns (bool); function harvestStrategy(address _strategy, uint256[] calldata _estimates) external; function manager() external view returns (IManager); function strategies() external view returns (uint256); function withdraw(address _token, uint256 _amount) external; function withdrawAll(address _strategy, address _convert) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./IManager.sol"; interface IHarvester { function addStrategy(address, address, uint256) external; function manager() external view returns (IManager); function removeStrategy(address, address, uint256) external; function slippage() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface ILegacyController { function legacyDeposit(uint256 _expected) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IManager { function addVault(address) external; function allowedControllers(address) external view returns (bool); function allowedConverters(address) external view returns (bool); function allowedStrategies(address) external view returns (bool); function allowedVaults(address) external view returns (bool); function controllers(address) external view returns (address); function getHarvestFeeInfo() external view returns (address, address, uint256); function getToken(address) external view returns (address); function governance() external view returns (address); function halted() external view returns (bool); function harvester() external view returns (address); function insuranceFee() external view returns (uint256); function insurancePool() external view returns (address); function insurancePoolFee() external view returns (uint256); function pendingStrategist() external view returns (address); function removeVault(address) external; function stakingPool() external view returns (address); function stakingPoolShareFee() external view returns (uint256); function strategist() external view returns (address); function treasury() external view returns (address); function treasuryFee() external view returns (uint256); function withdrawalProtectionFee() external view returns (uint256); function yaxis() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./IManager.sol"; import "./ISwap.sol"; interface IStrategy { function balanceOf() external view returns (uint256); function balanceOfPool() external view returns (uint256); function balanceOfWant() external view returns (uint256); function deposit() external; function harvest(uint256[] calldata) external; function manager() external view returns (IManager); function name() external view returns (string memory); function router() external view returns (ISwap); function skim() external; function want() external view returns (address); function weth() external view returns (address); function withdraw(address) external; function withdraw(uint256) external; function withdrawAll() external; } interface IStrategyExtended { function getEstimates() external view returns (uint256[] memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; interface ISwap { function swapExactTokensForTokens(uint256, uint256, address[] calldata, address, uint256) external; function getAmountsOut(uint256, address[] calldata) external view returns (uint256[] memory); }
* @notice Harvests the next available strategy for a given vault and rotates the strategies @param _vault The address of the vault @param _estimates The estimated outputs from swaps during harvest/
function harvestNextStrategy( address _vault, uint256[] calldata _estimates ) external { require(canHarvest(_vault), "!canHarvest"); address strategy = strategies[_vault].addresses[0]; harvest(controller, strategy, _estimates); uint256 k = strategies[_vault].addresses.length; if (k > 1) { address[] memory _strategies = new address[](k); for (uint i; i < k-1; i++) { _strategies[i] = strategies[_vault].addresses[i+1]; } _strategies[k-1] = strategy; strategies[_vault].addresses = _strategies; } }
5,957,957
[ 1, 44, 297, 90, 25563, 326, 1024, 2319, 6252, 364, 279, 864, 9229, 471, 4168, 815, 326, 20417, 225, 389, 26983, 1021, 1758, 434, 326, 9229, 225, 389, 395, 29678, 1021, 13137, 6729, 628, 1352, 6679, 4982, 17895, 26923, 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, 565, 445, 17895, 26923, 2134, 4525, 12, 203, 3639, 1758, 389, 26983, 16, 203, 3639, 2254, 5034, 8526, 745, 892, 389, 395, 29678, 203, 565, 262, 203, 3639, 3903, 203, 565, 288, 203, 3639, 2583, 12, 4169, 44, 297, 26923, 24899, 26983, 3631, 17528, 4169, 44, 297, 26923, 8863, 203, 3639, 1758, 6252, 273, 20417, 63, 67, 26983, 8009, 13277, 63, 20, 15533, 203, 3639, 17895, 26923, 12, 5723, 16, 6252, 16, 389, 395, 29678, 1769, 203, 3639, 2254, 5034, 417, 273, 20417, 63, 67, 26983, 8009, 13277, 18, 2469, 31, 203, 3639, 309, 261, 79, 405, 404, 13, 288, 203, 5411, 1758, 8526, 3778, 389, 701, 15127, 273, 394, 1758, 8526, 12, 79, 1769, 203, 5411, 364, 261, 11890, 277, 31, 277, 411, 417, 17, 21, 31, 277, 27245, 288, 203, 7734, 389, 701, 15127, 63, 77, 65, 273, 20417, 63, 67, 26983, 8009, 13277, 63, 77, 15, 21, 15533, 203, 5411, 289, 203, 5411, 389, 701, 15127, 63, 79, 17, 21, 65, 273, 6252, 31, 203, 5411, 20417, 63, 67, 26983, 8009, 13277, 273, 389, 701, 15127, 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 ]
/* from https://www.ethereum.org/token */ pragma solidity ^0.4.11; import "./IToken.sol"; contract BasicToken is IToken { string public name; string public symbol; uint256 public decimals; uint256 internal totalSupplyField; /* This creates an array with all balances */ mapping (address => uint256) internal balanceOfField; mapping (address => mapping (address => uint256)) internal allowanceField; function BasicToken( uint256 initialSupply, string tokenName, uint256 decimalUnits, string tokenSymbol ) public { totalSupplyField = initialSupply; // Update total supply name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes } function totalSupply() constant public returns (uint) { return totalSupplyField; } function balanceOf(address _owner) constant public returns (uint256 balance) { return balanceOfField[_owner]; } function allowance(address _owner, address _spender) constant public returns (uint256 _allowance) { return allowanceField[_owner][_spender]; } function transfer(address _to, uint256 _value) public returns (bool success) { require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require(balanceOfField[msg.sender] >= _value); // Check if the sender has enough require(balanceOfField[_to] + _value >= balanceOfField[_to]); // Check for overflows balanceOfField[msg.sender] -= _value; // Subtract from the sender balanceOfField[_to] += _value; // Add the same to the recipient Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place return true; } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) public returns (bool success) { allowanceField[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require(balanceOfField[_from] >= _value); // Check if the sender has enough require(balanceOfField[_to] + _value >= balanceOfField[_to]); // Check for overflows require(_value <= allowanceField[_from][msg.sender]); // Check allowance balanceOfField[_from] -= _value; // Subtract from the sender balanceOfField[_to] += _value; // Add the same to the recipient allowanceField[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } }
Update total supply
totalSupplyField = initialSupply;
894,811
[ 1, 1891, 2078, 14467, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2078, 3088, 1283, 974, 273, 2172, 3088, 1283, 31, 7682, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "./interfaces/IERC20.sol"; import "./interfaces/IMasterChefJoe.sol"; import "./interfaces/IRewarder.sol"; import "./libraries/BoringJoeERC20.sol"; /// @notice The (older) MasterChefJoeV2 contract gives out a constant number of JOE /// tokens per block. It is the only address with minting rights for JOE. The idea /// for this BoostedMasterChefJoe (BMCJ) contract is therefore to be the owner of a /// dummy token that is deposited into the MasterChefJoeV2 (MCJV2) contract. The /// allocation point for this pool on MCJV2 is the total allocation point for all /// pools on BMCJ. /// /// This MasterChef also skews how many rewards users receive, it does this by /// modifying the algorithm that calculates how many tokens are rewarded to /// depositors. Whereas MasterChef calculates rewards based on emission rate and /// total liquidity, this version uses adjusted parameters to this calculation. /// /// A users `boostedAmount` (liquidity multiplier) is calculated by the actual supplied /// liquidity multiplied by a boost factor. The boost factor is calculated by the /// amount of veJOE held by the user over the total veJOE amount held by all pool /// participants. Total liquidity is the sum of all boosted liquidity. contract BoostedMasterChefJoe is Initializable, OwnableUpgradeable, ReentrancyGuardUpgradeable { using SafeMathUpgradeable for uint256; using BoringJoeERC20 for IERC20; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; /// @notice Info of each BMCJ user /// `amount` LP token amount the user has provided /// `rewardDebt` The amount of JOE entitled to the user /// `veJoeBalance` the users balance of veJOE token. This needs /// to be stored so we have a prior value when updating the `PoolInfo` struct UserInfo { uint256 amount; uint256 rewardDebt; uint256 veJoeBalance; } /// @notice Info of each BMCJ pool /// `allocPoint` The amount of allocation points assigned to the pool /// Also known as the amount of JOE to distribute per block struct PoolInfo { IERC20 lpToken; uint256 accJoePerShare; uint256 lastRewardTimestamp; uint256 allocPoint; IRewarder rewarder; // The sum of all veJoe held by users participating in this farm // This value is updated when // - A user enter/leaves a farm // - A user claims veJOE // - A user unstakes JOE uint256 totalVeJoe; // The total boosted `amount` on the farm // This is the sum of all users boosted amounts in the farm. Updated when // totalVeJoe is updated // This is used instead of the usual `lpToken.balanceOf(address(this))` uint256 totalBoostedAmount; // Even though it seems redundant to keep track of two variables here // the `totalBoostedAmount` means we don't need to iterate over all // depositors to calculate the pending reward. } /// @notice Address of MCJV2 contract IMasterChefJoe public MASTER_CHEF_V2; /// @notice Address of JOE contract IERC20 public JOE; /// @notice Address of veJOE contract IERC20 public VEJOE; /// @notice The index of BMCJ master pool in MCJV2 uint256 public MASTER_PID; /// @notice Info of each BMCJ pool PoolInfo[] public poolInfo; /// @dev Set of all LP tokens that have been added as pools EnumerableSetUpgradeable.AddressSet private lpTokens; /// @notice Info of each user that stakes LP tokens mapping(uint256 => mapping(address => UserInfo)) public userInfo; /// @dev Total allocation points. Must be the sum of all allocation points in all pools uint256 public totalAllocPoint; uint256 private ACC_TOKEN_PRECISION; /// @dev A maximum scaling factor applied to boosted amounts uint256 public maxBoostFactor; /// @dev Amount of claimable Joe the user has, this is required as we /// need to update rewardDebt after a token operation but we don't /// want to send a reward at this point. This amount gets added onto /// the pending amount when a user claims mapping(uint256 => mapping(address => uint256)) public claimableJoe; event Add(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder); event Set(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite); event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event UpdatePool(uint256 indexed pid, uint256 lastRewardTimestamp, uint256 lpSupply, uint256 accJoePerShare); event Harvest(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event Init(uint256 amount); /// @param _MASTER_CHEF_V2 The MCJV2 contract address /// @param _joe The JOE token contract address /// @param _veJoe The veJOE token contract address /// @param _MASTER_PID The pool ID of the dummy token on the base MCJV2 contract function initialize( IMasterChefJoe _MASTER_CHEF_V2, IERC20 _joe, IERC20 _veJoe, uint256 _MASTER_PID ) public initializer { __Ownable_init(); MASTER_CHEF_V2 = _MASTER_CHEF_V2; JOE = _joe; VEJOE = _veJoe; MASTER_PID = _MASTER_PID; ACC_TOKEN_PRECISION = 1e18; maxBoostFactor = 1500; } /// @notice Deposits a dummy token to `MASTER_CHEF_V2` MCJV2. This is required because MCJV2 /// holds the minting rights for JOE. Any balance of transaction sender in `_dummyToken` is transferred. /// The allocation point for the pool on MCJV2 is the total allocation point for all pools that receive /// double incentives. /// @param _dummyToken The address of the ERC-20 token to deposit into MCJV2. function init(IERC20 _dummyToken) external onlyOwner { require( _dummyToken.balanceOf(address(MASTER_CHEF_V2)) == 0, "BoostedMasterChefJoe: Already has a balance of dummy token" ); uint256 balance = _dummyToken.balanceOf(msg.sender); require(balance != 0, "BoostedMasterChefJoe: Balance must exceed 0"); _dummyToken.safeTransferFrom(msg.sender, address(this), balance); _dummyToken.approve(address(MASTER_CHEF_V2), balance); MASTER_CHEF_V2.deposit(MASTER_PID, balance); emit Init(balance); } /// @notice Returns the number of BMCJ pools. /// @return pools The amount of pools in this farm function poolLength() external view returns (uint256 pools) { pools = poolInfo.length; } /// @notice Add a new LP to the pool. Can only be called by the owner. /// @param _allocPoint AP of the new pool. /// @param _lpToken Address of the LP ERC-20 token. /// @param _rewarder Address of the rewarder delegate. function add( uint256 _allocPoint, IERC20 _lpToken, IRewarder _rewarder ) external onlyOwner { require(!lpTokens.contains(address(_lpToken)), "BoostedMasterChefJoe: LP already added"); require(poolInfo.length <= 50, "BoostedMasterChefJoe: Too many pools"); // Sanity check to ensure _lpToken is an ERC20 token _lpToken.balanceOf(address(this)); // Sanity check if we add a rewarder if (address(_rewarder) != address(0)) { _rewarder.onJoeReward(address(0), 0); } uint256 lastRewardTimestamp = block.timestamp; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardTimestamp: lastRewardTimestamp, accJoePerShare: 0, rewarder: _rewarder, totalVeJoe: 0, totalBoostedAmount: 0 }) ); lpTokens.add(address(_lpToken)); emit Add(poolInfo.length.sub(1), _allocPoint, _lpToken, _rewarder); } /// @notice Update the given pool's JOE allocation point and `IRewarder` contract. Can only be called by the owner. /// @param _pid The index of the pool. See `poolInfo` /// @param _allocPoint New AP of the pool /// @param _rewarder Address of the rewarder delegate /// @param _overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored function set( uint256 _pid, uint256 _allocPoint, IRewarder _rewarder, bool _overwrite ) external onlyOwner { PoolInfo memory pool = poolInfo[_pid]; totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add(_allocPoint); pool.allocPoint = _allocPoint; if (_overwrite) { if (address(_rewarder) != address(0)) { _rewarder.onJoeReward(address(0), 0); } pool.rewarder = _rewarder; } poolInfo[_pid] = pool; emit Set(_pid, _allocPoint, _overwrite ? _rewarder : pool.rewarder, _overwrite); } /// @notice View function to see pending JOE on frontend /// @param _pid The index of the pool. See `poolInfo` /// @param _user Address of user /// @return pendingJoe JOE reward for a given user. /// @return bonusTokenAddress The address of the bonus reward. /// @return bonusTokenSymbol The symbol of the bonus token. /// @return pendingBonusToken The amount of bonus rewards pending. function pendingTokens(uint256 _pid, address _user) external view returns ( uint256 pendingJoe, address bonusTokenAddress, string memory bonusTokenSymbol, uint256 pendingBonusToken ) { PoolInfo memory pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accJoePerShare = pool.accJoePerShare; if (block.timestamp > pool.lastRewardTimestamp && pool.totalBoostedAmount != 0) { uint256 secondsElapsed = block.timestamp.sub(pool.lastRewardTimestamp); uint256 joeReward = secondsElapsed.mul(joePerSec()).mul(pool.allocPoint).div(totalAllocPoint); accJoePerShare = accJoePerShare.add(joeReward.mul(ACC_TOKEN_PRECISION).div(pool.totalBoostedAmount)); } uint256 userLiquidity = getBoostedLiquidity(_pid, _user); pendingJoe = userLiquidity.mul(accJoePerShare).div(ACC_TOKEN_PRECISION).sub(user.rewardDebt).add( claimableJoe[_pid][_user] ); // If it's a double reward farm, we return info about the bonus token if (address(pool.rewarder) != address(0)) { bonusTokenAddress = address(pool.rewarder.rewardToken()); bonusTokenSymbol = IERC20(pool.rewarder.rewardToken()).safeSymbol(); pendingBonusToken = pool.rewarder.pendingTokens(_user); } } /// @notice Update reward variables for all pools. Be careful of gas spending! /// @param _pids Pool IDs of all to be updated. Make sure to update all active pools function massUpdatePools(uint256[] calldata _pids) external { uint256 len = _pids.length; for (uint256 i = 0; i < len; ++i) { updatePool(_pids[i]); } } /// @notice Calculates and returns the `amount` of JOE per second /// @return amount The amount of JOE emitted per second function joePerSec() public view returns (uint256 amount) { uint256 total = 1000; uint256 lpPercent = total.sub(MASTER_CHEF_V2.devPercent()).sub(MASTER_CHEF_V2.treasuryPercent()).sub( MASTER_CHEF_V2.investorPercent() ); uint256 lpShare = MASTER_CHEF_V2.joePerSec().mul(lpPercent).div(total); amount = lpShare.mul(MASTER_CHEF_V2.poolInfo(MASTER_PID).allocPoint).div(MASTER_CHEF_V2.totalAllocPoint()); } /// @notice Update reward variables of the given pool /// @param _pid The index of the pool. See `poolInfo` function updatePool(uint256 _pid) public { PoolInfo memory pool = poolInfo[_pid]; if (block.timestamp > pool.lastRewardTimestamp) { uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply != 0) { uint256 secondsElapsed = block.timestamp.sub(pool.lastRewardTimestamp); uint256 joeReward = secondsElapsed.mul(joePerSec()).mul(pool.allocPoint).div(totalAllocPoint); pool.accJoePerShare = pool.accJoePerShare.add( joeReward.mul(ACC_TOKEN_PRECISION).div(pool.totalBoostedAmount) ); } pool.lastRewardTimestamp = block.timestamp; poolInfo[_pid] = pool; emit UpdatePool(_pid, pool.lastRewardTimestamp, lpSupply, pool.accJoePerShare); } } /// @notice Deposit LP tokens to BMCJ for JOE allocation /// @param _pid The index of the pool. See `poolInfo` /// @param _amount LP token amount to deposit function deposit(uint256 _pid, uint256 _amount) external nonReentrant { harvestFromMasterChef(); updatePool(_pid); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; // Pay a user any pending rewards if (user.amount != 0) { // Harvest JOE uint256 boostedLiquidity = getBoostedLiquidity(_pid, msg.sender); uint256 pending = boostedLiquidity .mul(pool.accJoePerShare) .div(ACC_TOKEN_PRECISION) .sub(user.rewardDebt) .add(claimableJoe[_pid][msg.sender]); claimableJoe[_pid][msg.sender] = 0; JOE.safeTransfer(msg.sender, pending); emit Harvest(msg.sender, _pid, pending); } uint256 balanceBefore = pool.lpToken.balanceOf(address(this)); pool.lpToken.safeTransferFrom(msg.sender, address(this), _amount); uint256 receivedAmount = pool.lpToken.balanceOf(address(this)).sub(balanceBefore); // Effects // Update the `pool.totalVeJoe` uint256 veJoeBalance = VEJOE.balanceOf(msg.sender); if (veJoeBalance != 0) { pool.totalVeJoe = pool.totalVeJoe.add(veJoeBalance).sub(user.veJoeBalance); } user.veJoeBalance = veJoeBalance; // Update the `pool.totalBoostedAmount` uint256 boostedLiquidityBefore = getBoostedLiquidity(_pid, msg.sender); user.amount = user.amount.add(receivedAmount); uint256 boostedLiquidityAfter = getBoostedLiquidity(_pid, msg.sender); pool.totalBoostedAmount = pool.totalBoostedAmount.add(boostedLiquidityAfter).sub(boostedLiquidityBefore); // Update users reward debt user.rewardDebt = boostedLiquidityAfter.mul(pool.accJoePerShare).div(ACC_TOKEN_PRECISION); // Interactions IRewarder _rewarder = pool.rewarder; if (address(_rewarder) != address(0)) { _rewarder.onJoeReward(msg.sender, user.amount); } emit Deposit(msg.sender, _pid, receivedAmount); } /// @notice Withdraw LP tokens from BMCJ /// @param _pid The index of the pool. See `poolInfo` /// @param _amount LP token amount to withdraw function withdraw(uint256 _pid, uint256 _amount) external nonReentrant { harvestFromMasterChef(); updatePool(_pid); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; if (user.amount != 0) { // Harvest JOE uint256 boostedLiquidity = getBoostedLiquidity(_pid, msg.sender); uint256 pending = boostedLiquidity .mul(pool.accJoePerShare) .div(ACC_TOKEN_PRECISION) .sub(user.rewardDebt) .add(claimableJoe[_pid][msg.sender]); claimableJoe[_pid][msg.sender] = 0; JOE.safeTransfer(msg.sender, pending); emit Harvest(msg.sender, _pid, pending); } // Effects uint256 boostedLiquidityBefore = getBoostedLiquidity(_pid, msg.sender); user.amount = user.amount.sub(_amount); uint256 boostedLiquidityAfter = getBoostedLiquidity(_pid, msg.sender); // Update the `pool.totalBoostedAmount` and `totalVeJoe` if needed if (user.amount == 0) { pool.totalVeJoe = pool.totalVeJoe.sub(user.veJoeBalance); } pool.totalBoostedAmount = pool.totalBoostedAmount.add(boostedLiquidityAfter).sub(boostedLiquidityBefore); user.rewardDebt = boostedLiquidityAfter.mul(pool.accJoePerShare).div(ACC_TOKEN_PRECISION); // Interactions IRewarder _rewarder = pool.rewarder; if (address(_rewarder) != address(0)) { _rewarder.onJoeReward(msg.sender, user.amount); } pool.lpToken.safeTransfer(msg.sender, _amount); emit Withdraw(msg.sender, _pid, _amount); } /// @notice Updates a pool and user boost factors after /// a veJoe token operation. This function needs to be called /// by the veJoe contract after every event. /// @param _user The users address we are updating /// @param _newUserBalance The new balance of the users veJoe function updateBoost(address _user, uint256 _newUserBalance) external { require(msg.sender == address(VEJOE), "BoostedMasterChefJoe: Caller not veJOE"); uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { UserInfo storage user = userInfo[pid][_user]; // Skip if user doesn't have any deposit in the pool if (user.amount == 0) { continue; } PoolInfo storage pool = poolInfo[pid]; updatePool(pid); // Calculate pending uint256 oldBoostedLiquidity = getBoostedLiquidity(pid, _user); uint256 pending = oldBoostedLiquidity.mul(pool.accJoePerShare).div(ACC_TOKEN_PRECISION).sub( user.rewardDebt ); // Increase claimableJoe claimableJoe[pid][_user] = claimableJoe[pid][_user].add(pending); // Update users veJoeBalance uint256 _oldBalance = user.veJoeBalance; user.veJoeBalance = _newUserBalance; // Update the pool total veJoe pool.totalVeJoe = pool.totalVeJoe.add(_newUserBalance).sub(_oldBalance); uint256 newBoostedLiquidity = getBoostedLiquidity(pid, _user); // Update the pools total boosted pool.totalBoostedAmount = pool.totalBoostedAmount.add(newBoostedLiquidity).sub(oldBoostedLiquidity); // Update reward debt, take into account new boost user.rewardDebt = newBoostedLiquidity.mul(pool.accJoePerShare).div(ACC_TOKEN_PRECISION); } } /// @notice Returns a users "boosted" liquidity /// @param _pid The index of the pool. See `poolInfo` /// @param _user The address of the depositor /// @return boostedLiquidity The users liquidity multiplied by their boost function getBoostedLiquidity(uint256 _pid, address _user) public view returns (uint256 boostedLiquidity) { UserInfo memory user = userInfo[_pid][_user]; boostedLiquidity = user.amount.mul(getUserBoost(_pid, _user)).div(1000); } /// @notice Returns a users boosted emission share /// @param _pid The index of the pool. See `poolInfo` /// @param _user The address of the depositor /// @dev `userBoost` is scaled by 1e3 /// @return userBoost A multiplier for a users liquidity function getUserBoost(uint256 _pid, address _user) public view returns (uint256 userBoost) { PoolInfo memory pool = poolInfo[_pid]; UserInfo memory user = userInfo[_pid][_user]; userBoost = 1000; if (user.veJoeBalance != 0 && pool.totalVeJoe != 0) { userBoost = userBoost.add(user.veJoeBalance.mul(maxBoostFactor).div(pool.totalVeJoe)); } } /// @notice Harvests JOE from `MASTER_CHEF_V2` MCJV2 and pool `MASTER_PID` to this BMCJ contract function harvestFromMasterChef() public { MASTER_CHEF_V2.deposit(MASTER_PID, 0); } /// @notice Withdraw without caring about rewards (EMERGENCY ONLY) /// @param _pid The index of the pool. See `poolInfo` function emergencyWithdraw(uint256 _pid) external nonReentrant { PoolInfo memory pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; IRewarder _rewarder = pool.rewarder; if (address(_rewarder) != address(0)) { _rewarder.onJoeReward(msg.sender, 0); } // Note: transfer can fail or succeed if `amount` is zero pool.lpToken.safeTransfer(msg.sender, amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } }
@notice Address of veJOE contract
IERC20 public VEJOE;
2,497,328
[ 1, 1887, 434, 10489, 22720, 41, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 467, 654, 39, 3462, 1071, 776, 41, 22720, 41, 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 ]
./full_match/5/0xeA8538B194742b992B19e694C13D63120908880e/sources/contracts/libraries/LibInput.sol
@notice called when a new epoch begins, clears deprecated inputs @param ds diamond storage pointer clear input box for new inputs the current input box should be accumulating inputs for the new epoch already. So we clear the other one.
function onNewEpoch(DiamondStorage storage ds) internal { ds.currentInputBox == 0 ? delete ds.inputBox1 : delete ds.inputBox0; }
1,891,786
[ 1, 11777, 1347, 279, 394, 7632, 17874, 16, 22655, 6849, 4540, 225, 3780, 4314, 301, 1434, 2502, 4407, 2424, 810, 3919, 364, 394, 4540, 326, 783, 810, 3919, 1410, 506, 8822, 1776, 4540, 364, 326, 394, 7632, 1818, 18, 6155, 732, 2424, 326, 1308, 1245, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 603, 1908, 14638, 12, 14521, 301, 1434, 3245, 2502, 3780, 13, 2713, 288, 203, 3639, 3780, 18, 2972, 1210, 3514, 422, 374, 692, 1430, 3780, 18, 2630, 3514, 21, 294, 1430, 3780, 18, 2630, 3514, 20, 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 ]
./full_match/4/0xB7e5F12ca069c018F85a0AA4282dfAFBA5DaFd8E/sources/Users/lugondev/DEV/truffle-sample/contracts/TokenCrowdsale.sol
* @dev Checks whether the period in which the crowdsale is open has already elapsed. @return Whether crowdsale period has elapsed/ solhint-disable-next-line not-rely-on-time
function hasClosed() public view returns (bool) { return _closingTime > 0 && block.timestamp > _closingTime; }
821,556
[ 1, 4081, 2856, 326, 3879, 316, 1492, 326, 276, 492, 2377, 5349, 353, 1696, 711, 1818, 9613, 18, 327, 17403, 276, 492, 2377, 5349, 3879, 711, 9613, 19, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 486, 17, 266, 715, 17, 265, 17, 957, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 711, 7395, 1435, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 389, 19506, 950, 405, 374, 597, 1203, 18, 5508, 405, 389, 19506, 950, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /** * @title MerkleProof * @dev Merkle proof verification based on * https://github.com/ameensol/merkle-tree-solidity/blob/master/src/MerkleProof.sol */ library MerkleProof { /** * @dev Verifies a Merkle proof proving the existence of a leaf in a Merkle tree. Assumes that each pair of leaves * and each pair of pre-images are sorted. * @param _proof Merkle proof containing sibling hashes on the branch from the leaf to the root of the Merkle tree * @param _root Merkle root * @param _leaf Leaf of Merkle tree */ function verifyProof( bytes32[] _proof, bytes32 _root, bytes32 _leaf ) internal pure returns (bool) { bytes32 computedHash = _leaf; for (uint256 i = 0; i < _proof.length; i++) { bytes32 proofElement = _proof[i]; if (computedHash < proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == _root; } } contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } address public controller; constructor() internal { controller = msg.sender; } /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) public onlyController { controller = _newController; } } // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 interface ERC20Token { /** * @notice send `_value` token to `_to` from `msg.sender` * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint256 _value) external returns (bool success); /** * @notice `msg.sender` approves `_spender` to spend `_value` tokens * @param _spender The address of the account able to transfer the tokens * @param _value The amount of tokens to be approved for transfer * @return Whether the approval was successful or not */ function approve(address _spender, uint256 _value) external returns (bool success); /** * @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); /** * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) external view returns (uint256 balance); /** * @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 remaining); /** * @notice return total supply of tokens */ function totalSupply() external view returns (uint256 supply); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; } interface ENS { // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed node, address owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed node, address resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed node, uint64 ttl); function setSubnodeOwner(bytes32 node, bytes32 label, address owner) public; function setResolver(bytes32 node, address resolver) public; function setOwner(bytes32 node, address owner) public; function setTTL(bytes32 node, uint64 ttl) public; function owner(bytes32 node) public view returns (address); function resolver(bytes32 node) public view returns (address); function ttl(bytes32 node) public view returns (uint64); } /** * A simple resolver anyone can use; only allows the owner of a node to set its * address. */ contract PublicResolver { bytes4 constant INTERFACE_META_ID = 0x01ffc9a7; bytes4 constant ADDR_INTERFACE_ID = 0x3b3b57de; bytes4 constant CONTENT_INTERFACE_ID = 0xd8389dc5; bytes4 constant NAME_INTERFACE_ID = 0x691f3431; bytes4 constant ABI_INTERFACE_ID = 0x2203ab56; bytes4 constant PUBKEY_INTERFACE_ID = 0xc8690233; bytes4 constant TEXT_INTERFACE_ID = 0x59d1d43c; bytes4 constant MULTIHASH_INTERFACE_ID = 0xe89401a1; event AddrChanged(bytes32 indexed node, address a); event ContentChanged(bytes32 indexed node, bytes32 hash); event NameChanged(bytes32 indexed node, string name); event ABIChanged(bytes32 indexed node, uint256 indexed contentType); event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y); event TextChanged(bytes32 indexed node, string indexedKey, string key); event MultihashChanged(bytes32 indexed node, bytes hash); struct PublicKey { bytes32 x; bytes32 y; } struct Record { address addr; bytes32 content; string name; PublicKey pubkey; mapping(string=>string) text; mapping(uint256=>bytes) abis; bytes multihash; } ENS ens; mapping (bytes32 => Record) records; modifier only_owner(bytes32 node) { require(ens.owner(node) == msg.sender); _; } /** * Constructor. * @param ensAddr The ENS registrar contract. */ constructor(ENS ensAddr) public { ens = ensAddr; } /** * Sets the address associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param addr The address to set. */ function setAddr(bytes32 node, address addr) public only_owner(node) { records[node].addr = addr; emit AddrChanged(node, addr); } /** * Sets the content hash associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The node to update. * @param hash The content hash to set */ function setContent(bytes32 node, bytes32 hash) public only_owner(node) { records[node].content = hash; emit ContentChanged(node, hash); } /** * Sets the multihash associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param hash The multihash to set */ function setMultihash(bytes32 node, bytes hash) public only_owner(node) { records[node].multihash = hash; emit MultihashChanged(node, hash); } /** * Sets the name associated with an ENS node, for reverse records. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param name The name to set. */ function setName(bytes32 node, string name) public only_owner(node) { records[node].name = name; emit NameChanged(node, name); } /** * Sets the ABI associated with an ENS node. * Nodes may have one ABI of each content type. To remove an ABI, set it to * the empty string. * @param node The node to update. * @param contentType The content type of the ABI * @param data The ABI data. */ function setABI(bytes32 node, uint256 contentType, bytes data) public only_owner(node) { // Content types must be powers of 2 require(((contentType - 1) & contentType) == 0); records[node].abis[contentType] = data; emit ABIChanged(node, contentType); } /** * Sets the SECP256k1 public key associated with an ENS node. * @param node The ENS node to query * @param x the X coordinate of the curve point for the public key. * @param y the Y coordinate of the curve point for the public key. */ function setPubkey(bytes32 node, bytes32 x, bytes32 y) public only_owner(node) { records[node].pubkey = PublicKey(x, y); emit PubkeyChanged(node, x, y); } /** * Sets the text data associated with an ENS node and key. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param key The key to set. * @param value The text data value to set. */ function setText(bytes32 node, string key, string value) public only_owner(node) { records[node].text[key] = value; emit TextChanged(node, key, key); } /** * Returns the text data associated with an ENS node and key. * @param node The ENS node to query. * @param key The text data key to query. * @return The associated text data. */ function text(bytes32 node, string key) public view returns (string) { return records[node].text[key]; } /** * Returns the SECP256k1 public key associated with an ENS node. * Defined in EIP 619. * @param node The ENS node to query * @return x, y the X and Y coordinates of the curve point for the public key. */ function pubkey(bytes32 node) public view returns (bytes32 x, bytes32 y) { return (records[node].pubkey.x, records[node].pubkey.y); } /** * Returns the ABI associated with an ENS node. * Defined in EIP205. * @param node The ENS node to query * @param contentTypes A bitwise OR of the ABI formats accepted by the caller. * @return contentType The content type of the return value * @return data The ABI data */ function ABI(bytes32 node, uint256 contentTypes) public view returns (uint256 contentType, bytes data) { Record storage record = records[node]; for (contentType = 1; contentType <= contentTypes; contentType <<= 1) { if ((contentType & contentTypes) != 0 && record.abis[contentType].length > 0) { data = record.abis[contentType]; return; } } contentType = 0; } /** * Returns the name associated with an ENS node, for reverse records. * Defined in EIP181. * @param node The ENS node to query. * @return The associated name. */ function name(bytes32 node) public view returns (string) { return records[node].name; } /** * Returns the content hash associated with an ENS node. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The ENS node to query. * @return The associated content hash. */ function content(bytes32 node) public view returns (bytes32) { return records[node].content; } /** * Returns the multihash associated with an ENS node. * @param node The ENS node to query. * @return The associated multihash. */ function multihash(bytes32 node) public view returns (bytes) { return records[node].multihash; } /** * Returns the address associated with an ENS node. * @param node The ENS node to query. * @return The associated address. */ function addr(bytes32 node) public view returns (address) { return records[node].addr; } /** * Returns true if the resolver implements the interface specified by the provided hash. * @param interfaceID The ID of the interface to check for. * @return True if the contract implements the requested interface. */ function supportsInterface(bytes4 interfaceID) public pure returns (bool) { return interfaceID == ADDR_INTERFACE_ID || interfaceID == CONTENT_INTERFACE_ID || interfaceID == NAME_INTERFACE_ID || interfaceID == ABI_INTERFACE_ID || interfaceID == PUBKEY_INTERFACE_ID || interfaceID == TEXT_INTERFACE_ID || interfaceID == MULTIHASH_INTERFACE_ID || interfaceID == INTERFACE_META_ID; } } /** * @author Ricardo Guilherme Schmidt (Status Research & Development GmbH) * @notice Registers usernames as ENS subnodes of the domain `ensNode` */ contract UsernameRegistrar is Controlled, ApproveAndCallFallBack { ERC20Token public token; ENS public ensRegistry; PublicResolver public resolver; address public parentRegistry; uint256 public constant releaseDelay = 365 days; mapping (bytes32 => Account) public accounts; mapping (bytes32 => SlashReserve) reservedSlashers; //Slashing conditions uint256 public usernameMinLength; bytes32 public reservedUsernamesMerkleRoot; event RegistryState(RegistrarState state); event RegistryPrice(uint256 price); event RegistryMoved(address newRegistry); event UsernameOwner(bytes32 indexed nameHash, address owner); enum RegistrarState { Inactive, Active, Moved } bytes32 public ensNode; uint256 public price; RegistrarState public state; uint256 public reserveAmount; struct Account { uint256 balance; uint256 creationTime; address owner; } struct SlashReserve { address reserver; uint256 blockNumber; } /** * @notice Callable only by `parentRegistry()` to continue migration of ENSSubdomainRegistry. */ modifier onlyParentRegistry { require(msg.sender == parentRegistry, "Migration only."); _; } /** * @notice Initializes UsernameRegistrar contract. * The only parameter from this list that can be changed later is `_resolver`. * Other updates require a new contract and migration of domain. * @param _token ERC20 token with optional `approveAndCall(address,uint256,bytes)` for locking fee. * @param _ensRegistry Ethereum Name Service root contract address. * @param _resolver Public Resolver for resolving usernames. * @param _ensNode ENS node (domain) being used for usernames subnodes (subdomain) * @param _usernameMinLength Minimum length of usernames * @param _reservedUsernamesMerkleRoot Merkle root of reserved usernames * @param _parentRegistry Address of old registry (if any) for optional account migration. */ constructor( ERC20Token _token, ENS _ensRegistry, PublicResolver _resolver, bytes32 _ensNode, uint256 _usernameMinLength, bytes32 _reservedUsernamesMerkleRoot, address _parentRegistry ) public { require(address(_token) != address(0), "No ERC20Token address defined."); require(address(_ensRegistry) != address(0), "No ENS address defined."); require(address(_resolver) != address(0), "No Resolver address defined."); require(_ensNode != bytes32(0), "No ENS node defined."); token = _token; ensRegistry = _ensRegistry; resolver = _resolver; ensNode = _ensNode; usernameMinLength = _usernameMinLength; reservedUsernamesMerkleRoot = _reservedUsernamesMerkleRoot; parentRegistry = _parentRegistry; setState(RegistrarState.Inactive); } /** * @notice Registers `_label` username to `ensNode` setting msg.sender as owner. * Terms of name registration: * - SNT is deposited, not spent; the amount is locked up for 1 year. * - After 1 year, the user can release the name and receive their deposit back (at any time). * - User deposits are completely protected. The contract controller cannot access them. * - User&#39;s address(es) will be publicly associated with the ENS name. * - User must authorise the contract to transfer `price` `token.name()` on their behalf. * - Usernames registered with less then `usernameMinLength` characters can be slashed. * - Usernames contained in the merkle tree of root `reservedUsernamesMerkleRoot` can be slashed. * - Usernames starting with `0x` and bigger then 12 characters can be slashed. * - If terms of the contract change—e.g. Status makes contract upgrades—the user has the right to release the username and get their deposit back. * @param _label Choosen unowned username hash. * @param _account Optional address to set at public resolver. * @param _pubkeyA Optional pubkey part A to set at public resolver. * @param _pubkeyB Optional pubkey part B to set at public resolver. */ function register( bytes32 _label, address _account, bytes32 _pubkeyA, bytes32 _pubkeyB ) external returns(bytes32 namehash) { return registerUser(msg.sender, _label, _account, _pubkeyA, _pubkeyB); } /** * @notice Release username and retrieve locked fee, needs to be called * after `releasePeriod` from creation time by ENS registry owner of domain * or anytime by account owner when domain migrated to a new registry. * @param _label Username hash. */ function release( bytes32 _label ) external { bytes32 namehash = keccak256(abi.encodePacked(ensNode, _label)); Account memory account = accounts[_label]; require(account.creationTime > 0, "Username not registered."); if (state == RegistrarState.Active) { require(msg.sender == ensRegistry.owner(namehash), "Not owner of ENS node."); require(block.timestamp > account.creationTime + releaseDelay, "Release period not reached."); } else { require(msg.sender == account.owner, "Not the former account owner."); } delete accounts[_label]; if (account.balance > 0) { reserveAmount -= account.balance; require(token.transfer(msg.sender, account.balance), "Transfer failed"); } if (state == RegistrarState.Active) { ensRegistry.setSubnodeOwner(ensNode, _label, address(this)); ensRegistry.setResolver(namehash, address(0)); ensRegistry.setOwner(namehash, address(0)); } else { address newOwner = ensRegistry.owner(ensNode); //Low level call, case dropUsername not implemented or failing, proceed release. //Invert (!) to supress warning, return of this call have no use. !newOwner.call.gas(80000)( abi.encodeWithSignature( "dropUsername(bytes32)", _label ) ); } emit UsernameOwner(namehash, address(0)); } /** * @notice update account owner, should be called by new ens node owner * to update this contract registry, otherwise former owner can release * if domain is moved to a new registry. * @param _label Username hash. **/ function updateAccountOwner( bytes32 _label ) external { bytes32 namehash = keccak256(abi.encodePacked(ensNode, _label)); require(msg.sender == ensRegistry.owner(namehash), "Caller not owner of ENS node."); require(accounts[_label].creationTime > 0, "Username not registered."); require(ensRegistry.owner(ensNode) == address(this), "Registry not owner of registry."); accounts[_label].owner = msg.sender; emit UsernameOwner(namehash, msg.sender); } /** * @notice secretly reserve the slashing reward to `msg.sender` * @param _secret keccak256(abi.encodePacked(namehash, creationTime, reserveSecret)) */ function reserveSlash(bytes32 _secret) external { require(reservedSlashers[_secret].blockNumber == 0, "Already Reserved"); reservedSlashers[_secret] = SlashReserve(msg.sender, block.number); } /** * @notice Slash username smaller then `usernameMinLength`. * @param _username Raw value of offending username. */ function slashSmallUsername( string _username, uint256 _reserveSecret ) external { bytes memory username = bytes(_username); require(username.length < usernameMinLength, "Not a small username."); slashUsername(username, _reserveSecret); } /** * @notice Slash username starting with "0x" and with length greater than 12. * @param _username Raw value of offending username. */ function slashAddressLikeUsername( string _username, uint256 _reserveSecret ) external { bytes memory username = bytes(_username); require(username.length > 12, "Too small to look like an address."); require(username[0] == byte("0"), "First character need to be 0"); require(username[1] == byte("x"), "Second character need to be x"); for(uint i = 2; i < 7; i++){ byte b = username[i]; require((b >= 48 && b <= 57) || (b >= 97 && b <= 102), "Does not look like an address"); } slashUsername(username, _reserveSecret); } /** * @notice Slash username that is exactly a reserved name. * @param _username Raw value of offending username. * @param _proof Merkle proof that name is listed on merkle tree. */ function slashReservedUsername( string _username, bytes32[] _proof, uint256 _reserveSecret ) external { bytes memory username = bytes(_username); require( MerkleProof.verifyProof( _proof, reservedUsernamesMerkleRoot, keccak256(username) ), "Invalid Proof." ); slashUsername(username, _reserveSecret); } /** * @notice Slash username that contains a non alphanumeric character. * @param _username Raw value of offending username. * @param _offendingPos Position of non alphanumeric character. */ function slashInvalidUsername( string _username, uint256 _offendingPos, uint256 _reserveSecret ) external { bytes memory username = bytes(_username); require(username.length > _offendingPos, "Invalid position."); byte b = username[_offendingPos]; require(!((b >= 48 && b <= 57) || (b >= 97 && b <= 122)), "Not invalid character."); slashUsername(username, _reserveSecret); } /** * @notice Clear resolver and ownership of unowned subdomians. * @param _labels Sequence to erase. */ function eraseNode( bytes32[] _labels ) external { uint len = _labels.length; require(len != 0, "Nothing to erase"); bytes32 label = _labels[len - 1]; bytes32 subnode = keccak256(abi.encodePacked(ensNode, label)); require(ensRegistry.owner(subnode) == address(0), "First slash/release top level subdomain"); ensRegistry.setSubnodeOwner(ensNode, label, address(this)); if(len > 1) { eraseNodeHierarchy(len - 2, _labels, subnode); } ensRegistry.setResolver(subnode, 0); ensRegistry.setOwner(subnode, 0); } /** * @notice Migrate account to new registry, opt-in to new contract. * @param _label Username hash. **/ function moveAccount( bytes32 _label, UsernameRegistrar _newRegistry ) external { require(state == RegistrarState.Moved, "Wrong contract state"); require(msg.sender == accounts[_label].owner, "Callable only by account owner."); require(ensRegistry.owner(ensNode) == address(_newRegistry), "Wrong update"); Account memory account = accounts[_label]; delete accounts[_label]; token.approve(_newRegistry, account.balance); _newRegistry.migrateUsername( _label, account.balance, account.creationTime, account.owner ); } /** * @notice Activate registration. * @param _price The price of registration. */ function activate( uint256 _price ) external onlyController { require(state == RegistrarState.Inactive, "Registry state is not Inactive"); require(ensRegistry.owner(ensNode) == address(this), "Registry does not own registry"); price = _price; setState(RegistrarState.Active); emit RegistryPrice(_price); } /** * @notice Updates Public Resolver for resolving users. * @param _resolver New PublicResolver. */ function setResolver( address _resolver ) external onlyController { resolver = PublicResolver(_resolver); } /** * @notice Updates registration price. * @param _price New registration price. */ function updateRegistryPrice( uint256 _price ) external onlyController { require(state == RegistrarState.Active, "Registry not owned"); price = _price; emit RegistryPrice(_price); } /** * @notice Transfer ownership of ensNode to `_newRegistry`. * Usernames registered are not affected, but they would be able to instantly release. * @param _newRegistry New UsernameRegistrar for hodling `ensNode` node. */ function moveRegistry( UsernameRegistrar _newRegistry ) external onlyController { require(_newRegistry != this, "Cannot move to self."); require(ensRegistry.owner(ensNode) == address(this), "Registry not owned anymore."); setState(RegistrarState.Moved); ensRegistry.setOwner(ensNode, _newRegistry); _newRegistry.migrateRegistry(price); emit RegistryMoved(_newRegistry); } /** * @notice Opt-out migration of username from `parentRegistry()`. * Clear ENS resolver and subnode owner. * @param _label Username hash. */ function dropUsername( bytes32 _label ) external onlyParentRegistry { require(accounts[_label].creationTime == 0, "Already migrated"); bytes32 namehash = keccak256(abi.encodePacked(ensNode, _label)); ensRegistry.setSubnodeOwner(ensNode, _label, address(this)); ensRegistry.setResolver(namehash, address(0)); ensRegistry.setOwner(namehash, address(0)); } /** * @notice Withdraw not reserved tokens * @param _token Address of ERC20 withdrawing excess, or address(0) if want ETH. * @param _beneficiary Address to send the funds. **/ function withdrawExcessBalance( address _token, address _beneficiary ) external onlyController { require(_beneficiary != address(0), "Cannot burn token"); if (_token == address(0)) { _beneficiary.transfer(address(this).balance); } else { ERC20Token excessToken = ERC20Token(_token); uint256 amount = excessToken.balanceOf(address(this)); if(_token == address(token)){ require(amount > reserveAmount, "Is not excess"); amount -= reserveAmount; } else { require(amount > 0, "No balance"); } excessToken.transfer(_beneficiary, amount); } } /** * @notice Withdraw ens nodes not belonging to this contract. * @param _domainHash Ens node namehash. * @param _beneficiary New owner of ens node. **/ function withdrawWrongNode( bytes32 _domainHash, address _beneficiary ) external onlyController { require(_beneficiary != address(0), "Cannot burn node"); require(_domainHash != ensNode, "Cannot withdraw main node"); require(ensRegistry.owner(_domainHash) == address(this), "Not owner of this node"); ensRegistry.setOwner(_domainHash, _beneficiary); } /** * @notice Gets registration price. * @return Registration price. **/ function getPrice() external view returns(uint256 registryPrice) { return price; } /** * @notice reads amount tokens locked in username * @param _label Username hash. * @return Locked username balance. **/ function getAccountBalance(bytes32 _label) external view returns(uint256 accountBalance) { accountBalance = accounts[_label].balance; } /** * @notice reads username account owner at this contract, * which can release or migrate in case of upgrade. * @param _label Username hash. * @return Username account owner. **/ function getAccountOwner(bytes32 _label) external view returns(address owner) { owner = accounts[_label].owner; } /** * @notice reads when the account was registered * @param _label Username hash. * @return Registration time. **/ function getCreationTime(bytes32 _label) external view returns(uint256 creationTime) { creationTime = accounts[_label].creationTime; } /** * @notice calculate time where username can be released * @param _label Username hash. * @return Exact time when username can be released. **/ function getExpirationTime(bytes32 _label) external view returns(uint256 releaseTime) { uint256 creationTime = accounts[_label].creationTime; if (creationTime > 0){ releaseTime = creationTime + releaseDelay; } } /** * @notice calculate reward part an account could payout on slash * @param _label Username hash. * @return Part of reward **/ function getSlashRewardPart(bytes32 _label) external view returns(uint256 partReward) { uint256 balance = accounts[_label].balance; if (balance > 0) { partReward = balance / 3; } } /** * @notice Support for "approveAndCall". Callable only by `token()`. * @param _from Who approved. * @param _amount Amount being approved, need to be equal `getPrice()`. * @param _token Token being approved, need to be equal `token()`. * @param _data Abi encoded data with selector of `register(bytes32,address,bytes32,bytes32)`. */ function receiveApproval( address _from, uint256 _amount, address _token, bytes _data ) public { require(_amount == price, "Wrong value"); require(_token == address(token), "Wrong token"); require(_token == address(msg.sender), "Wrong call"); require(_data.length <= 132, "Wrong data length"); bytes4 sig; bytes32 label; address account; bytes32 pubkeyA; bytes32 pubkeyB; (sig, label, account, pubkeyA, pubkeyB) = abiDecodeRegister(_data); require( sig == bytes4(0xb82fedbb), //bytes4(keccak256("register(bytes32,address,bytes32,bytes32)")) "Wrong method selector" ); registerUser(_from, label, account, pubkeyA, pubkeyB); } /** * @notice Continues migration of username to new registry. * @param _label Username hash. * @param _tokenBalance Amount being transfered from `parentRegistry()`. * @param _creationTime Time user registrated in `parentRegistry()` is preserved. * @param _accountOwner Account owner which migrated the account. **/ function migrateUsername( bytes32 _label, uint256 _tokenBalance, uint256 _creationTime, address _accountOwner ) external onlyParentRegistry { if (_tokenBalance > 0) { require( token.transferFrom( parentRegistry, address(this), _tokenBalance ), "Error moving funds from old registar." ); reserveAmount += _tokenBalance; } accounts[_label] = Account(_tokenBalance, _creationTime, _accountOwner); } /** * @dev callable only by parent registry to continue migration * of registry and activate registration. * @param _price The price of registration. **/ function migrateRegistry( uint256 _price ) external onlyParentRegistry { require(state == RegistrarState.Inactive, "Not Inactive"); require(ensRegistry.owner(ensNode) == address(this), "ENS registry owner not transfered."); price = _price; setState(RegistrarState.Active); emit RegistryPrice(_price); } /** * @notice Registers `_label` username to `ensNode` setting msg.sender as owner. * @param _owner Address registering the user and paying registry price. * @param _label Choosen unowned username hash. * @param _account Optional address to set at public resolver. * @param _pubkeyA Optional pubkey part A to set at public resolver. * @param _pubkeyB Optional pubkey part B to set at public resolver. */ function registerUser( address _owner, bytes32 _label, address _account, bytes32 _pubkeyA, bytes32 _pubkeyB ) internal returns(bytes32 namehash) { require(state == RegistrarState.Active, "Registry unavailable."); namehash = keccak256(abi.encodePacked(ensNode, _label)); require(ensRegistry.owner(namehash) == address(0), "ENS node already owned."); require(accounts[_label].creationTime == 0, "Username already registered."); accounts[_label] = Account(price, block.timestamp, _owner); if(price > 0) { require(token.allowance(_owner, address(this)) >= price, "Unallowed to spend."); require( token.transferFrom( _owner, address(this), price ), "Transfer failed" ); reserveAmount += price; } bool resolvePubkey = _pubkeyA != 0 || _pubkeyB != 0; bool resolveAccount = _account != address(0); if (resolvePubkey || resolveAccount) { //set to self the ownership to setup initial resolver ensRegistry.setSubnodeOwner(ensNode, _label, address(this)); ensRegistry.setResolver(namehash, resolver); //default resolver if (resolveAccount) { resolver.setAddr(namehash, _account); } if (resolvePubkey) { resolver.setPubkey(namehash, _pubkeyA, _pubkeyB); } ensRegistry.setOwner(namehash, _owner); } else { //transfer ownership of subdone directly to registrant ensRegistry.setSubnodeOwner(ensNode, _label, _owner); } emit UsernameOwner(namehash, _owner); } /** * @dev Removes account hash of `_username` and send account.balance to msg.sender. * @param _username Username being slashed. */ function slashUsername( bytes _username, uint256 _reserveSecret ) internal { bytes32 label = keccak256(_username); bytes32 namehash = keccak256(abi.encodePacked(ensNode, label)); uint256 amountToTransfer = 0; uint256 creationTime = accounts[label].creationTime; address owner = ensRegistry.owner(namehash); if(creationTime == 0) { require( owner != address(0) || ensRegistry.resolver(namehash) != address(0), "Nothing to slash." ); } else { assert(creationTime != block.timestamp); amountToTransfer = accounts[label].balance; delete accounts[label]; } ensRegistry.setSubnodeOwner(ensNode, label, address(this)); ensRegistry.setResolver(namehash, address(0)); ensRegistry.setOwner(namehash, address(0)); if (amountToTransfer > 0) { reserveAmount -= amountToTransfer; uint256 partialDeposit = amountToTransfer / 3; amountToTransfer = partialDeposit * 2; // reserve 1/3 to network (controller) bytes32 secret = keccak256(abi.encodePacked(namehash, creationTime, _reserveSecret)); SlashReserve memory reserve = reservedSlashers[secret]; require(reserve.reserver != address(0), "Not reserved."); require(reserve.blockNumber < block.number, "Cannot reveal in same block"); delete reservedSlashers[secret]; require(token.transfer(reserve.reserver, amountToTransfer), "Error in transfer."); } emit UsernameOwner(namehash, address(0)); } function setState(RegistrarState _state) private { state = _state; emit RegistryState(_state); } /** * @notice recursively erase all _labels in _subnode * @param _idx recursive position of _labels to erase * @param _labels list of subnode labes * @param _subnode subnode being erased */ function eraseNodeHierarchy( uint _idx, bytes32[] _labels, bytes32 _subnode ) private { // Take ownership of the node ensRegistry.setSubnodeOwner(_subnode, _labels[_idx], address(this)); bytes32 subnode = keccak256(abi.encodePacked(_subnode, _labels[_idx])); // Recurse if there are more labels if (_idx > 0) { eraseNodeHierarchy(_idx - 1, _labels, subnode); } // Erase the resolver and owner records ensRegistry.setResolver(subnode, 0); ensRegistry.setOwner(subnode, 0); } /** * @dev Decodes abi encoded data with selector for "register(bytes32,address,bytes32,bytes32)". * @param _data Abi encoded data. * @return Decoded registry call. */ function abiDecodeRegister( bytes _data ) private pure returns( bytes4 sig, bytes32 label, address account, bytes32 pubkeyA, bytes32 pubkeyB ) { assembly { sig := mload(add(_data, add(0x20, 0))) label := mload(add(_data, 36)) account := mload(add(_data, 68)) pubkeyA := mload(add(_data, 100)) pubkeyB := mload(add(_data, 132)) } } }
Logged when the owner of a node assigns a new owner to a subnode. Logged when the owner of a node transfers ownership to a new account. Logged when the resolver for a node changes. Logged when the TTL of a node changes
interface ENS { event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); event Transfer(bytes32 indexed node, address owner); event NewResolver(bytes32 indexed node, address resolver); event NewTTL(bytes32 indexed node, uint64 ttl); function setSubnodeOwner(bytes32 node, bytes32 label, address owner) public; function setResolver(bytes32 node, address resolver) public; function setOwner(bytes32 node, address owner) public; function setTTL(bytes32 node, uint64 ttl) public; function owner(bytes32 node) public view returns (address); function resolver(bytes32 node) public view returns (address); function ttl(bytes32 node) public view returns (uint64); }
10,895,103
[ 1, 19862, 1347, 326, 3410, 434, 279, 756, 22698, 279, 394, 3410, 358, 279, 28300, 18, 1827, 2423, 1347, 326, 3410, 434, 279, 756, 29375, 23178, 358, 279, 394, 2236, 18, 1827, 2423, 1347, 326, 5039, 364, 279, 756, 3478, 18, 1827, 2423, 1347, 326, 14076, 434, 279, 756, 3478, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 512, 3156, 288, 203, 203, 225, 871, 1166, 5541, 12, 3890, 1578, 8808, 756, 16, 1731, 1578, 8808, 1433, 16, 1758, 3410, 1769, 203, 203, 225, 871, 12279, 12, 3890, 1578, 8808, 756, 16, 1758, 3410, 1769, 203, 203, 225, 871, 1166, 4301, 12, 3890, 1578, 8808, 756, 16, 1758, 5039, 1769, 203, 203, 225, 871, 1166, 11409, 12, 3890, 1578, 8808, 756, 16, 2254, 1105, 6337, 1769, 203, 203, 203, 225, 445, 19942, 2159, 5541, 12, 3890, 1578, 756, 16, 1731, 1578, 1433, 16, 1758, 3410, 13, 1071, 31, 203, 225, 445, 444, 4301, 12, 3890, 1578, 756, 16, 1758, 5039, 13, 1071, 31, 203, 225, 445, 31309, 12, 3890, 1578, 756, 16, 1758, 3410, 13, 1071, 31, 203, 225, 445, 444, 11409, 12, 3890, 1578, 756, 16, 2254, 1105, 6337, 13, 1071, 31, 203, 225, 445, 3410, 12, 3890, 1578, 756, 13, 1071, 1476, 1135, 261, 2867, 1769, 203, 225, 445, 5039, 12, 3890, 1578, 756, 13, 1071, 1476, 1135, 261, 2867, 1769, 203, 225, 445, 6337, 12, 3890, 1578, 756, 13, 1071, 1476, 1135, 261, 11890, 1105, 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 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.6; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/IHologramAccumulator.sol"; /// @title HologramAccumulator - counts the behavior. /// @author Shumpei Koike - <[email protected]> contract TestHologramAccumulator is IHologramAccumulator { using Address for address; uint256 public constant DENOMINATOR = 1000; mapping(address => uint256) private _weighted; mapping(address => uint256) private _accumulate; /// Events event Accumulate(address caller, address account, uint256 weight); event AccumulateBatch(address caller, address[2] accounts, uint256 weight); event AccumulateBatch(address caller, address[3] accounts, uint256 weight); event Undermine(address caller, address account, uint256 weight); event UndermineBatch(address caller, address[2] accounts, uint256 weight); event UndermineBatch(address caller, address[3] accounts, uint256 weight); event ChangeCoefficient(address accessor, uint256 coefficient); event Accept(address accessor); /// @dev Counts a positive behavior. /// @param account address who behaves positively function accumulateSmall(address account) public override { _accumulate[account]++; emit Accumulate(msg.sender, account, _weighted[msg.sender]); } /// @dev Counts a positive behavior. /// @param account address who behaves positively function accumulateMedium(address account) public override { _accumulate[account] += 2; emit Accumulate(msg.sender, account, _weighted[msg.sender]); } /// @dev Counts a positive behavior. /// @param account address who behaves positively function accumulateLarge(address account) public override { _accumulate[account] += 3; emit Accumulate(msg.sender, account, _weighted[msg.sender]); } /// @dev Counts a positive behavior. /// @param accounts a set of addresses who behave positively function accumulateBatch2Small(address[2] memory accounts) public override { for (uint256 i = 0; i < accounts.length; i++) { _accumulate[accounts[i]]++; } emit AccumulateBatch(msg.sender, accounts, _weighted[msg.sender]); } /// @dev Counts a positive behavior. /// @param accounts a set of addresses who behave positively function accumulateBatch2Medium(address[2] memory accounts) public override { for (uint256 i = 0; i < accounts.length; i++) { _accumulate[accounts[i]] += 2; } emit AccumulateBatch(msg.sender, accounts, _weighted[msg.sender]); } /// @dev Counts a positive behavior. /// @param accounts a set of addresses who behave positively function accumulateBatch2Large(address[2] memory accounts) public override { for (uint256 i = 0; i < accounts.length; i++) { _accumulate[accounts[i]] += 3; } emit AccumulateBatch(msg.sender, accounts, _weighted[msg.sender]); } /// @dev Counts a positive behavior. /// @param accounts a set of addresses who behave positively function accumulateBatch3Small(address[3] memory accounts) public override { for (uint256 i = 0; i < accounts.length; i++) { _accumulate[accounts[i]]++; } emit AccumulateBatch(msg.sender, accounts, _weighted[msg.sender]); } /// @dev Counts a positive behavior. /// @param accounts a set of addresses who behave positively function accumulateBatch3Medium(address[3] memory accounts) public override { for (uint256 i = 0; i < accounts.length; i++) { _accumulate[accounts[i]] += 2; } emit AccumulateBatch(msg.sender, accounts, _weighted[msg.sender]); } /// @dev Counts a positive behavior. /// @param accounts a set of addresses who behave positively function accumulateBatch3Large(address[3] memory accounts) public override { for (uint256 i = 0; i < accounts.length; i++) { _accumulate[accounts[i]] += 3; } emit AccumulateBatch(msg.sender, accounts, _weighted[msg.sender]); } /// @dev Counts a nagative behavior. /// @param account address who behaves negatively function undermineSmall(address account) public override { _accumulate[account] > 0 ? _accumulate[account]-- : _accumulate[account] = 0; emit Undermine(msg.sender, account, _weighted[msg.sender]); } /// @dev Counts a nagative behavior. /// @param account address who behaves negatively function undermineMedium(address account) public override { _accumulate[account] > 1 ? _accumulate[account] -= 2 : _accumulate[account] = 0; emit Undermine(msg.sender, account, _weighted[msg.sender]); } /// @dev Counts a nagative behavior. /// @param account address who behaves negatively function undermineLarge(address account) public override { _accumulate[account] > 2 ? _accumulate[account] -= 3 : _accumulate[account] = 0; emit Undermine(msg.sender, account, _weighted[msg.sender]); } /// @dev Counts a nagative behavior. /// @param accounts a set of addresses who behave negatively function undermineBatch2Small(address[2] memory accounts) public override { for (uint256 i = 0; i < accounts.length; i++) { _accumulate[accounts[i]] > 0 ? _accumulate[accounts[i]]-- : _accumulate[accounts[i]] = 0; } emit UndermineBatch(msg.sender, accounts, _weighted[msg.sender]); } /// @dev Counts a nagative behavior. /// @param accounts a set of addresses who behave negatively function undermineBatch2Medium(address[2] memory accounts) public override { for (uint256 i = 0; i < accounts.length; i++) { _accumulate[accounts[i]] > 1 ? _accumulate[accounts[i]] -= 2 : _accumulate[accounts[i]] = 0; } emit UndermineBatch(msg.sender, accounts, _weighted[msg.sender]); } /// @dev Counts a nagative behavior. /// @param accounts a set of addresses who behave negatively function undermineBatch2Large(address[2] memory accounts) public override { for (uint256 i = 0; i < accounts.length; i++) { _accumulate[accounts[i]] > 2 ? _accumulate[accounts[i]] -= 3 : _accumulate[accounts[i]] = 0; } emit UndermineBatch(msg.sender, accounts, _weighted[msg.sender]); } /// @dev Counts a nagative behavior. /// @param accounts a set of addresses who behave negatively function undermineBatch3Small(address[3] memory accounts) public override { for (uint256 i = 0; i < accounts.length; i++) { _accumulate[accounts[i]] > 0 ? _accumulate[accounts[i]]-- : _accumulate[accounts[i]] = 0; } emit UndermineBatch(msg.sender, accounts, _weighted[msg.sender]); } /// @dev Counts a nagative behavior. /// @param accounts a set of addresses who behave negatively function undermineBatch3Medium(address[3] memory accounts) public override { for (uint256 i = 0; i < accounts.length; i++) { _accumulate[accounts[i]] > 1 ? _accumulate[accounts[i]] -= 2 : _accumulate[accounts[i]] = 0; } emit UndermineBatch(msg.sender, accounts, _weighted[msg.sender]); } /// @dev Counts a nagative behavior. /// @param accounts a set of addresses who behave negatively function undermineBatch3Large(address[3] memory accounts) public override { for (uint256 i = 0; i < accounts.length; i++) { _accumulate[accounts[i]] > 2 ? _accumulate[accounts[i]] -= 3 : _accumulate[accounts[i]] = 0; } emit UndermineBatch(msg.sender, accounts, _weighted[msg.sender]); } }
@dev Counts a positive behavior. @param accounts a set of addresses who behave positively
function accumulateBatch2Large(address[2] memory accounts) public override { for (uint256 i = 0; i < accounts.length; i++) { _accumulate[accounts[i]] += 3; } emit AccumulateBatch(msg.sender, accounts, _weighted[msg.sender]); }
12,551,670
[ 1, 9211, 279, 6895, 6885, 18, 225, 9484, 279, 444, 434, 6138, 10354, 31085, 949, 305, 4492, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 202, 915, 21757, 4497, 22, 20020, 12, 2867, 63, 22, 65, 3778, 9484, 13, 1071, 3849, 288, 203, 202, 202, 1884, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 9484, 18, 2469, 31, 277, 27245, 288, 203, 1082, 202, 67, 8981, 31284, 63, 13739, 63, 77, 13563, 1011, 890, 31, 203, 202, 202, 97, 203, 202, 202, 18356, 15980, 31284, 4497, 12, 3576, 18, 15330, 16, 9484, 16, 389, 30890, 63, 3576, 18, 15330, 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 ]
./full_match/1/0xa20aaf0e02Cb599e860E2EEcCf458968EdB766C4/sources/src/lender/coordinator.sol
flag which indicates if the coordinator is currently in a submission period
bool public submissionPeriod;
17,192,636
[ 1, 6420, 1492, 8527, 309, 326, 24794, 353, 4551, 316, 279, 8515, 3879, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1426, 1071, 8515, 5027, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0xc64C4B475C4ee0b30A4E0D3F875A4541e6d480a1/sources/stakingContract.sol
get total rewards collected by user
function getTotalRewardCollectedByUser(uint256 _poolId, address userAddress) view public returns (uint256 _totalRewardCollected) { return userRewardInfo[_poolId][userAddress].totalWithdrawn; }
5,125,853
[ 1, 588, 2078, 283, 6397, 12230, 635, 729, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12831, 17631, 1060, 10808, 18696, 1299, 12, 11890, 5034, 389, 6011, 548, 16, 1758, 729, 1887, 13, 1476, 1071, 1135, 261, 11890, 5034, 389, 4963, 17631, 1060, 10808, 329, 13, 7010, 565, 288, 203, 3639, 327, 729, 17631, 1060, 966, 63, 67, 6011, 548, 6362, 1355, 1887, 8009, 4963, 1190, 9446, 82, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/8453/0x19A4f00039Cde3ffbe29b23417FcfB9101Ae174b/sources/NFT.sol
A mapping to store the tokens owned by a particular address
contract NFT is ERC721URIStorage { using Counters for Counters.Counter; Counters.Counter private _tokenIds; address public owner; uint256 public cost; mapping(address => uint256[]) private _tokensOfOwner; constructor( string memory _name, string memory _symbol, uint256 _cost ) ERC721(_name, _symbol) { owner = msg.sender; cost = _cost; } function mint(string memory tokenURI) public payable { require(msg.value >= cost, "Payment less than cost"); _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(msg.sender, newItemId); _setTokenURI(newItemId, tokenURI); _tokensOfOwner[msg.sender].push(newItemId); } function totalSupply() public view returns (uint256) { return _tokenIds.current(); } function tokensOfOwner(address _owner) public view returns(uint256[] memory) { return _tokensOfOwner[_owner]; } function setCost(uint256 newCost) public { require(msg.sender == owner, "Only owner can change cost"); cost = newCost; } function burn(uint256 tokenId) public { require(_isApprovedOrOwner(msg.sender, tokenId), "Caller is not owner nor approved"); _burn(tokenId); } function withdraw() public { require(msg.sender == owner, "Only owner can withdraw"); payable(owner).transfer(address(this).balance); } }
16,690,103
[ 1, 37, 2874, 358, 1707, 326, 2430, 16199, 635, 279, 6826, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 423, 4464, 353, 4232, 39, 27, 5340, 3098, 3245, 288, 203, 565, 1450, 9354, 87, 364, 9354, 87, 18, 4789, 31, 203, 565, 9354, 87, 18, 4789, 3238, 389, 2316, 2673, 31, 203, 203, 565, 1758, 1071, 3410, 31, 203, 565, 2254, 5034, 1071, 6991, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 63, 5717, 3238, 389, 7860, 951, 5541, 31, 203, 203, 565, 3885, 12, 203, 3639, 533, 3778, 389, 529, 16, 203, 3639, 533, 3778, 389, 7175, 16, 203, 3639, 2254, 5034, 389, 12398, 203, 203, 565, 262, 4232, 39, 27, 5340, 24899, 529, 16, 389, 7175, 13, 288, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 3639, 6991, 273, 389, 12398, 31, 203, 565, 289, 203, 203, 565, 445, 312, 474, 12, 1080, 3778, 1147, 3098, 13, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 6991, 16, 315, 6032, 5242, 2353, 6991, 8863, 203, 3639, 389, 2316, 2673, 18, 15016, 5621, 203, 3639, 2254, 5034, 394, 17673, 273, 389, 2316, 2673, 18, 2972, 5621, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 394, 17673, 1769, 203, 3639, 389, 542, 1345, 3098, 12, 2704, 17673, 16, 1147, 3098, 1769, 203, 540, 203, 3639, 389, 7860, 951, 5541, 63, 3576, 18, 15330, 8009, 6206, 12, 2704, 17673, 1769, 203, 565, 289, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 2316, 2673, 18, 2972, 5621, 203, 565, 289, 203, 565, 445, 2430, 2 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import {ICollybus} from "./ICollybus.sol"; import {IRelayer} from "./IRelayer.sol"; contract StaticRelayer is IRelayer { /// @notice Emitted during executeWithRevert() if the Collybus was already updated error StaticRelayer__executeWithRevert_collybusAlreadyUpdated( IRelayer.RelayerType relayerType ); /// ======== Events ======== /// event UpdatedCollybus( bytes32 tokenId, uint256 rate, IRelayer.RelayerType relayerType ); /// ======== Storage ======== /// address public immutable collybus; IRelayer.RelayerType public immutable relayerType; bytes32 public immutable encodedTokenId; uint256 public immutable value; // Flag used to ensure that the value is pushed to Collybus only once bool private _updatedCollybus; /// @param collybusAddress_ Address of the collybus /// @param type_ Relayer type, DiscountRate or SpotPrice /// @param encodedTokenId_ Encoded token Id that will be used to push the value to Collybus /// uint256 for discount rate, address for spot price /// @param value_ The value that will be pushed to Collybus constructor( address collybusAddress_, IRelayer.RelayerType type_, bytes32 encodedTokenId_, uint256 value_ ) { collybus = collybusAddress_; relayerType = type_; encodedTokenId = encodedTokenId_; value = value_; _updatedCollybus = false; } /// @notice Pushes the hardcoded value to Collybus for the hardcoded token id /// @dev The execute will exit early after the first update function execute() public override(IRelayer) returns (bool) { if (_updatedCollybus) return false; _updatedCollybus = true; if (relayerType == IRelayer.RelayerType.DiscountRate) { ICollybus(collybus).updateDiscountRate( uint256(encodedTokenId), value ); } else if (relayerType == IRelayer.RelayerType.SpotPrice) { ICollybus(collybus).updateSpot( address(uint160(uint256(encodedTokenId))), value ); } emit UpdatedCollybus(encodedTokenId, value, relayerType); return true; } /// @notice The function will call `execute()` and will revert if _updatedCollybus is true function executeWithRevert() public override(IRelayer) { if (!execute()) { revert StaticRelayer__executeWithRevert_collybusAlreadyUpdated( relayerType ); } } }
Flag used to ensure that the value is pushed to Collybus only once
contract StaticRelayer is IRelayer { error StaticRelayer__executeWithRevert_collybusAlreadyUpdated( IRelayer.RelayerType relayerType ); event UpdatedCollybus( bytes32 tokenId, uint256 rate, IRelayer.RelayerType relayerType ); address public immutable collybus; IRelayer.RelayerType public immutable relayerType; bytes32 public immutable encodedTokenId; uint256 public immutable value; bool private _updatedCollybus; constructor( address collybusAddress_, IRelayer.RelayerType type_, bytes32 encodedTokenId_, uint256 value_ pragma solidity ^0.8.0; import {ICollybus} from "./ICollybus.sol"; import {IRelayer} from "./IRelayer.sol"; ) { collybus = collybusAddress_; relayerType = type_; encodedTokenId = encodedTokenId_; value = value_; _updatedCollybus = false; } function execute() public override(IRelayer) returns (bool) { if (_updatedCollybus) return false; _updatedCollybus = true; if (relayerType == IRelayer.RelayerType.DiscountRate) { ICollybus(collybus).updateDiscountRate( uint256(encodedTokenId), value ); ICollybus(collybus).updateSpot( address(uint160(uint256(encodedTokenId))), value ); } emit UpdatedCollybus(encodedTokenId, value, relayerType); return true; } function execute() public override(IRelayer) returns (bool) { if (_updatedCollybus) return false; _updatedCollybus = true; if (relayerType == IRelayer.RelayerType.DiscountRate) { ICollybus(collybus).updateDiscountRate( uint256(encodedTokenId), value ); ICollybus(collybus).updateSpot( address(uint160(uint256(encodedTokenId))), value ); } emit UpdatedCollybus(encodedTokenId, value, relayerType); return true; } } else if (relayerType == IRelayer.RelayerType.SpotPrice) { function executeWithRevert() public override(IRelayer) { if (!execute()) { revert StaticRelayer__executeWithRevert_collybusAlreadyUpdated( relayerType ); } } function executeWithRevert() public override(IRelayer) { if (!execute()) { revert StaticRelayer__executeWithRevert_collybusAlreadyUpdated( relayerType ); } } }
14,089,994
[ 1, 4678, 1399, 358, 3387, 716, 326, 460, 353, 18543, 358, 1558, 715, 9274, 1338, 3647, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 10901, 1971, 1773, 353, 467, 1971, 1773, 288, 203, 565, 555, 10901, 1971, 1773, 972, 8837, 1190, 426, 1097, 67, 1293, 715, 9274, 9430, 7381, 12, 203, 3639, 467, 1971, 1773, 18, 1971, 1773, 559, 1279, 1773, 559, 203, 565, 11272, 203, 203, 203, 565, 871, 19301, 914, 715, 9274, 12, 203, 3639, 1731, 1578, 1147, 548, 16, 203, 3639, 2254, 5034, 4993, 16, 203, 3639, 467, 1971, 1773, 18, 1971, 1773, 559, 1279, 1773, 559, 203, 565, 11272, 203, 203, 203, 565, 1758, 1071, 11732, 645, 715, 9274, 31, 203, 565, 467, 1971, 1773, 18, 1971, 1773, 559, 1071, 11732, 1279, 1773, 559, 31, 203, 565, 1731, 1578, 1071, 11732, 3749, 1345, 548, 31, 203, 565, 2254, 5034, 1071, 11732, 460, 31, 203, 203, 565, 1426, 3238, 389, 7007, 914, 715, 9274, 31, 203, 203, 565, 3885, 12, 203, 3639, 1758, 645, 715, 9274, 1887, 67, 16, 203, 3639, 467, 1971, 1773, 18, 1971, 1773, 559, 618, 67, 16, 203, 3639, 1731, 1578, 3749, 1345, 548, 67, 16, 203, 3639, 2254, 5034, 460, 67, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 5666, 288, 45, 914, 715, 9274, 97, 628, 25165, 45, 914, 715, 9274, 18, 18281, 14432, 203, 5666, 288, 45, 1971, 1773, 97, 628, 25165, 45, 1971, 1773, 18, 18281, 14432, 203, 565, 262, 288, 203, 3639, 645, 715, 9274, 273, 645, 715, 9274, 1887, 67, 31, 203, 3639, 1279, 1773, 559, 273, 618, 67, 31, 203, 3639, 3749, 1345, 548, 273, 3749, 1345, 548, 2 ]
// SPDX-License-Identifier: Apache License 2.0 pragma solidity >=0.6.0 <0.8.0; pragma experimental ABIEncoderV2; import "./Context.sol"; import "./SafeMath.sol"; import "./Address.sol"; import "./ReentrancyGuard.sol"; import "./mimc7.sol"; import "./IERC165.sol"; import "./IERC721.sol"; import "./IERC721TokenReceiver.sol"; contract SiddhiToken is IERC721, ReentrancyGuard{ string public name = "Siddhi NFT Token"; string public symbol = "SIDDHI"; uint256 private _totalTokens = 0; mapping(uint256 => address) private tokenToOwner; mapping(address => uint256) private tokensByOwner; mapping(address => mapping(address => bool)) private authOperators; mapping(uint256 => address) private approvedAddresses; mapping(uint256 => Ticket) private tickets; struct Ticket { string name; uint256 adn; uint256 points; bytes data; } constructor() { _totalTokens++; tokensByOwner[address(this)]++; tickets[_totalTokens] = Ticket( "GOLD TOKEN", _totalTokens, 10000, "KILLER" ); tokenToOwner[_totalTokens] = address(this); } function isContract(address addr) private view returns (bool) { uint256 size; assembly { size := extcodesize(addr) } return size > 0; } function balanceOf(address _owner) external view override returns (uint256) { require(_owner != address(0)); return tokensByOwner[_owner]; } function ownerOf(uint256 _tokenId) external view override returns (address) { address _tokenOwner = tokenToOwner[_tokenId]; require(_tokenOwner != address(0)); return _tokenOwner; } function _transfer( address _from, address _to, uint256 _tokenId ) private { require( msg.sender == tokenToOwner[_tokenId] || authOperators[tokenToOwner[_tokenId]][msg.sender] || msg.sender == approvedAddresses[_tokenId] ); approvedAddresses[_tokenId] = address(0); require(_from == tokenToOwner[_tokenId]); require(_to != address(0)); // Require NFT to be a valid ID require(_tokenId > 0 && _tokenId <= _totalTokens); // Transafer (overflow issue to solve with safeMath) tokensByOwner[_to]++; tokensByOwner[_from]--; tokenToOwner[_tokenId] = _to; emit Transfer(_from, _to, _tokenId); } function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes memory data ) external payable override { _transfer(_from, _to, _tokenId); if (isContract(_to)) { require( IERC721TokenReceiver(_to).onERC721Received( msg.sender, _from, _tokenId, data ) == this.onERC721Received(msg.sender, _from, _tokenId, data) ); } } function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external payable override { this.safeTransferFrom(_from, _to, _tokenId, ""); } function transferFrom( address _from, address _to, uint256 _tokenId ) external payable override { _transfer(_from, _to, _tokenId); } function approve(address _approved, uint256 _tokenId) external payable override { require( msg.sender == tokenToOwner[_tokenId] || authOperators[tokenToOwner[_tokenId]][msg.sender] ); approvedAddresses[_tokenId] = _approved; emit Approval(msg.sender, _approved, _tokenId); } function setApprovalForAll(address _operator, bool _approved) external override { authOperators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } function getApproved(uint256 _tokenId) external view override returns (address) { return approvedAddresses[_tokenId]; } function isApprovedForAll(address _owner, address _operator) external view override returns (bool) { return authOperators[_owner][_operator] || false; } function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes memory _data ) external pure returns (bytes4) { return bytes4( keccak256( abi.encodePacked( "onERC721Received(", _operator, _from, _tokenId, _data, ")" ) ) ); } }
Require NFT to be a valid ID Transafer (overflow issue to solve with safeMath)
function _transfer( address _from, address _to, uint256 _tokenId ) private { require( msg.sender == tokenToOwner[_tokenId] || authOperators[tokenToOwner[_tokenId]][msg.sender] || msg.sender == approvedAddresses[_tokenId] ); approvedAddresses[_tokenId] = address(0); require(_from == tokenToOwner[_tokenId]); require(_to != address(0)); require(_tokenId > 0 && _tokenId <= _totalTokens); tokensByOwner[_to]++; tokensByOwner[_from]--; tokenToOwner[_tokenId] = _to; emit Transfer(_from, _to, _tokenId); }
14,098,810
[ 1, 8115, 423, 4464, 358, 506, 279, 923, 1599, 2604, 69, 586, 261, 11512, 5672, 358, 12439, 598, 4183, 10477, 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 ]
[ 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, 13866, 12, 203, 3639, 1758, 389, 2080, 16, 203, 3639, 1758, 389, 869, 16, 203, 3639, 2254, 5034, 389, 2316, 548, 203, 565, 262, 3238, 288, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 15330, 422, 1147, 774, 5541, 63, 67, 2316, 548, 65, 747, 203, 7734, 1357, 24473, 63, 2316, 774, 5541, 63, 67, 2316, 548, 65, 6362, 3576, 18, 15330, 65, 747, 203, 7734, 1234, 18, 15330, 422, 20412, 7148, 63, 67, 2316, 548, 65, 203, 3639, 11272, 203, 3639, 20412, 7148, 63, 67, 2316, 548, 65, 273, 1758, 12, 20, 1769, 203, 203, 3639, 2583, 24899, 2080, 422, 1147, 774, 5541, 63, 67, 2316, 548, 19226, 203, 3639, 2583, 24899, 869, 480, 1758, 12, 20, 10019, 203, 203, 3639, 2583, 24899, 2316, 548, 405, 374, 597, 389, 2316, 548, 1648, 389, 4963, 5157, 1769, 203, 203, 3639, 2430, 858, 5541, 63, 67, 869, 3737, 15, 31, 203, 3639, 2430, 858, 5541, 63, 67, 2080, 65, 413, 31, 203, 3639, 1147, 774, 5541, 63, 67, 2316, 548, 65, 273, 389, 869, 31, 203, 203, 3639, 3626, 12279, 24899, 2080, 16, 389, 869, 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 ]
pragma solidity ^0.5.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // // [ msg.sender ] // | | // | | // \_/ // +---------------+ ________________________________ // | OneSplitAudit | _______________________________ \ // +---------------+ \ \ // | | ______________ | | (staticcall) // | | / ____________ \ | | // | | (call) / / \ \ | | // | | / / | | | | // \_/ | | \_/ \_/ // +--------------+ | | +----------------------+ // | OneSplitWrap | | | | OneSplitViewWrap | // +--------------+ | | +----------------------+ // | | | | | | // | | (delegatecall) | | (staticcall) | | (staticcall) // \_/ | | \_/ // +--------------+ | | +------------------+ // | OneSplit | | | | OneSplitView | // +--------------+ | | +------------------+ // | | / / // \ \________________/ / // \__________________/ // contract IOneSplitConsts { // flags = FLAG_DISABLE_UNISWAP + FLAG_DISABLE_KYBER + ... uint256 internal constant FLAG_DISABLE_UNISWAP = 0x01; uint256 internal constant FLAG_DISABLE_KYBER = 0x02; uint256 internal constant FLAG_DISABLE_BANCOR = 0x04; uint256 internal constant FLAG_DISABLE_OASIS = 0x08; uint256 internal constant FLAG_DISABLE_COMPOUND = 0x10; uint256 internal constant FLAG_DISABLE_FULCRUM = 0x20; uint256 internal constant FLAG_DISABLE_CHAI = 0x40; uint256 internal constant FLAG_DISABLE_AAVE = 0x80; uint256 internal constant FLAG_DISABLE_SMART_TOKEN = 0x100; uint256 internal constant FLAG_ENABLE_MULTI_PATH_ETH = 0x200; // Turned off by default uint256 internal constant FLAG_DISABLE_BDAI = 0x400; uint256 internal constant FLAG_DISABLE_IEARN = 0x800; uint256 internal constant FLAG_DISABLE_CURVE_COMPOUND = 0x1000; uint256 internal constant FLAG_DISABLE_CURVE_USDT = 0x2000; uint256 internal constant FLAG_DISABLE_CURVE_Y = 0x4000; uint256 internal constant FLAG_DISABLE_CURVE_BINANCE = 0x8000; uint256 internal constant FLAG_ENABLE_MULTI_PATH_DAI = 0x10000; // Turned off by default uint256 internal constant FLAG_ENABLE_MULTI_PATH_USDC = 0x20000; // Turned off by default uint256 internal constant FLAG_DISABLE_CURVE_SYNTHETIX = 0x40000; uint256 internal constant FLAG_DISABLE_WETH = 0x80000; uint256 internal constant FLAG_DISABLE_UNISWAP_COMPOUND = 0x100000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH uint256 internal constant FLAG_DISABLE_UNISWAP_CHAI = 0x200000; // Works only when ETH<>DAI or FLAG_ENABLE_MULTI_PATH_ETH uint256 internal constant FLAG_DISABLE_UNISWAP_AAVE = 0x400000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH uint256 internal constant FLAG_DISABLE_IDLE = 0x800000; uint256 internal constant FLAG_DISABLE_MOONISWAP = 0x1000000; uint256 internal constant FLAG_DISABLE_UNISWAP_V2 = 0x2000000; uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ETH = 0x4000000; uint256 internal constant FLAG_DISABLE_UNISWAP_V2_DAI = 0x8000000; uint256 internal constant FLAG_DISABLE_UNISWAP_V2_USDC = 0x10000000; uint256 internal constant FLAG_DISABLE_ALL_SPLIT_SOURCES = 0x20000000; uint256 internal constant FLAG_DISABLE_ALL_WRAP_SOURCES = 0x40000000; uint256 internal constant FLAG_DISABLE_CURVE_PAX = 0x80000000; uint256 internal constant FLAG_DISABLE_CURVE_RENBTC = 0x100000000; uint256 internal constant FLAG_DISABLE_CURVE_TBTC = 0x200000000; uint256 internal constant FLAG_ENABLE_MULTI_PATH_USDT = 0x400000000; // Turned off by default uint256 internal constant FLAG_ENABLE_MULTI_PATH_WBTC = 0x800000000; // Turned off by default uint256 internal constant FLAG_ENABLE_MULTI_PATH_TBTC = 0x1000000000; // Turned off by default uint256 internal constant FLAG_ENABLE_MULTI_PATH_RENBTC = 0x2000000000; // Turned off by default uint256 internal constant FLAG_DISABLE_DFORCE_SWAP = 0x4000000000; uint256 internal constant FLAG_DISABLE_SHELL = 0x8000000000; uint256 internal constant FLAG_ENABLE_CHI_BURN = 0x10000000000; uint256 internal constant FLAG_DISABLE_MSTABLE_MUSD = 0x20000000000; uint256 internal constant FLAG_DISABLE_CURVE_SBTC = 0x40000000000; uint256 internal constant FLAG_DISABLE_DMM = 0x80000000000; uint256 internal constant FLAG_DISABLE_UNISWAP_ALL = 0x100000000000; uint256 internal constant FLAG_DISABLE_CURVE_ALL = 0x200000000000; uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ALL = 0x400000000000; uint256 internal constant FLAG_DISABLE_SPLIT_RECALCULATION = 0x800000000000; uint256 internal constant FLAG_DISABLE_BALANCER_ALL = 0x1000000000000; uint256 internal constant FLAG_DISABLE_BALANCER_1 = 0x2000000000000; uint256 internal constant FLAG_DISABLE_BALANCER_2 = 0x4000000000000; uint256 internal constant FLAG_DISABLE_BALANCER_3 = 0x8000000000000; uint256 internal constant FLAG_ENABLE_KYBER_UNISWAP_RESERVE = 0x1000000000000; // Turned off by default uint256 internal constant FLAG_ENABLE_KYBER_OASIS_RESERVE = 0x2000000000000; // Turned off by default uint256 internal constant FLAG_ENABLE_KYBER_BANCOR_RESERVE = 0x4000000000000; // Turned off by default } contract IOneSplit is IOneSplitConsts { function getExpectedReturn( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) public view returns( uint256 returnAmount, uint256[] memory distribution ); function getExpectedReturnWithGas( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags, // See constants in IOneSplit.sol uint256 destTokenEthPriceTimesGasPrice ) public view returns( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ); function swap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 minReturn, uint256[] memory distribution, uint256 flags ) public payable returns(uint256 returnAmount); }
Turned off by default
uint256 internal constant FLAG_ENABLE_KYBER_UNISWAP_RESERVE = 0x1000000000000;
12,884,494
[ 1, 15858, 329, 3397, 635, 805, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 2713, 5381, 10972, 67, 29377, 67, 47, 61, 6271, 67, 2124, 5127, 59, 2203, 67, 862, 2123, 3412, 273, 374, 92, 21, 12648, 2787, 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 ]
./full_match/5/0x12141BF31f4368B335a52C2db360fF5F211b3DA9/sources/project_/contracts/Interfaces/ILUSDToken.sol
--- Events --- --- Functions ---
interface ILUSDToken is IERC20, IERC2612 { event TroveManagerAddressChanged(address _troveManagerAddress); event StabilityPoolAddressChanged(address _newStabilityPoolAddress); event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress); event LUSDTokenBalanceUpdated(address _user, uint _amount); function mint(address _account, uint256 _amount) external; function burn(address _account, uint256 _amount) external; function sendToPool(address _sender, address poolAddress, uint256 _amount) external; function returnFromPool(address poolAddress, address user, uint256 _amount ) external; }
1,951,332
[ 1, 6062, 9043, 9948, 9948, 15486, 9948, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 48, 3378, 40, 1345, 353, 467, 654, 39, 3462, 16, 467, 654, 39, 5558, 2138, 288, 7010, 377, 203, 203, 565, 871, 399, 303, 537, 1318, 1887, 5033, 12, 2867, 389, 88, 303, 537, 1318, 1887, 1769, 203, 565, 871, 934, 2967, 2864, 1887, 5033, 12, 2867, 389, 2704, 510, 2967, 2864, 1887, 1769, 203, 565, 871, 605, 15318, 264, 9343, 1887, 5033, 12, 2867, 389, 2704, 38, 15318, 264, 9343, 1887, 1769, 203, 203, 565, 871, 511, 3378, 40, 1345, 13937, 7381, 12, 2867, 389, 1355, 16, 2254, 389, 8949, 1769, 203, 203, 203, 565, 445, 312, 474, 12, 2867, 389, 4631, 16, 2254, 5034, 389, 8949, 13, 3903, 31, 203, 203, 565, 445, 18305, 12, 2867, 389, 4631, 16, 2254, 5034, 389, 8949, 13, 3903, 31, 203, 203, 565, 445, 29091, 2864, 12, 2867, 389, 15330, 16, 225, 1758, 2845, 1887, 16, 2254, 5034, 389, 8949, 13, 3903, 31, 203, 203, 565, 445, 327, 1265, 2864, 12, 2867, 2845, 1887, 16, 1758, 729, 16, 2254, 5034, 389, 8949, 262, 3903, 31, 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 ]
./partial_match/1/0xe612636BF13650B0C9d46d58f94e973809f252ed/sources/Staker.sol
/ This ensure if user is adding more funds to stake, they cannot attack and decrease the staking period to say 1 seconds for early withdrawl. They can increase however. edge case, topping up after their stake expired, they should be able to use a smaller stake length
Auto staking function. function stake( address fundAddress, uint256 amount, uint256 stakeLength, bool autoRenewStake ) public invictusWhitelisted timePeriodCheck(stakeLength) fundExists(fundAddress) { require( stakeLength >= userCommittedStakingPeriod[fundAddress][msg.sender], "cannot decrease staking length" ); ERC20PresetMinterPauserUpgradeSafe(fundAddress).transferFrom( msg.sender, address(this), amount ); userAmountStaked[fundAddress][msg .sender] = userAmountStaked[fundAddress][msg.sender].add(amount); userCommittedStakingPeriod[fundAddress][msg.sender] = stakeLength; userEligibleWithdrawlTime[fundAddress][msg.sender] = block .timestamp .add(stakeLength); userStakeRenew[fundAddress][msg.sender] = autoRenewStake; emit StakeAdded( fundAddress, msg.sender, amount, stakeLength, userEligibleWithdrawlTime[fundAddress][msg.sender], autoRenewStake ); }
3,669,768
[ 1, 19, 1220, 3387, 309, 729, 353, 6534, 1898, 284, 19156, 358, 384, 911, 16, 2898, 2780, 13843, 471, 20467, 326, 384, 6159, 3879, 358, 12532, 404, 3974, 364, 11646, 598, 9446, 80, 18, 16448, 848, 10929, 14025, 18, 3591, 648, 16, 1760, 1382, 731, 1839, 3675, 384, 911, 7708, 16, 2898, 1410, 506, 7752, 358, 999, 279, 10648, 384, 911, 769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 8064, 384, 6159, 445, 18, 7010, 565, 445, 384, 911, 12, 203, 3639, 1758, 284, 1074, 1887, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 2254, 5034, 384, 911, 1782, 16, 203, 3639, 1426, 3656, 24058, 510, 911, 203, 565, 262, 203, 3639, 1071, 203, 3639, 316, 11946, 407, 18927, 329, 203, 3639, 19470, 1564, 12, 334, 911, 1782, 13, 203, 3639, 284, 1074, 4002, 12, 74, 1074, 1887, 13, 203, 565, 288, 203, 3639, 2583, 12, 203, 5411, 384, 911, 1782, 1545, 729, 27813, 510, 6159, 5027, 63, 74, 1074, 1887, 6362, 3576, 18, 15330, 6487, 203, 5411, 315, 12892, 20467, 384, 6159, 769, 6, 203, 3639, 11272, 203, 203, 3639, 4232, 39, 3462, 18385, 49, 2761, 16507, 1355, 10784, 9890, 12, 74, 1074, 1887, 2934, 13866, 1265, 12, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 3844, 203, 3639, 11272, 203, 203, 3639, 729, 6275, 510, 9477, 63, 74, 1074, 1887, 6362, 3576, 203, 5411, 263, 15330, 65, 273, 729, 6275, 510, 9477, 63, 74, 1074, 1887, 6362, 3576, 18, 15330, 8009, 1289, 12, 8949, 1769, 203, 3639, 729, 27813, 510, 6159, 5027, 63, 74, 1074, 1887, 6362, 3576, 18, 15330, 65, 273, 384, 911, 1782, 31, 203, 3639, 729, 4958, 16057, 1190, 9446, 80, 950, 63, 74, 1074, 1887, 6362, 3576, 18, 15330, 65, 273, 1203, 203, 5411, 263, 5508, 203, 5411, 263, 1289, 12, 334, 911, 1782, 1769, 203, 3639, 729, 510, 911, 24058, 63, 74, 1074, 1887, 6362, 3576, 18, 15330, 2 ]
pragma solidity ^0.4.25; contract AcceptsExchange { Exchange public tokenContract; constructor(address _tokenContract) public { tokenContract = Exchange(_tokenContract); } modifier onlyTokenContract { require(msg.sender == address(tokenContract)); _; } /** * @dev Standard ERC677 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint256 _value, bytes _data) external returns (bool); } contract Exchange { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends(true) > 0); _; } modifier notContract() { require (msg.sender == tx.origin); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later) // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } uint ACTIVATION_TIME = 1547996400; // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier antiEarlyWhale(uint256 _amountOfEthereum){ if (now >= ACTIVATION_TIME) { onlyAmbassadors = false; } // are we still in the vulnerable phase? // if so, enact anti early whale protocol if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){ require( // is the customer in the ambassador list? ambassadors_[msg.sender] == true && // does the customer purchase exceed the max ambassador quota? (ambassadorAccumulatedQuota_[msg.sender] + _amountOfEthereum) <= ambassadorMaxPurchase_ ); // updated the accumulated quota ambassadorAccumulatedQuota_[msg.sender] = SafeMath.add(ambassadorAccumulatedQuota_[msg.sender], _amountOfEthereum); // execute _; } else { // in case the ether count drops low, the ambassador phase won't reinitiate onlyAmbassadors = false; _; } } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy, bool isReinvest, uint timestamp, uint256 price ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned, uint timestamp, uint256 price ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn, uint256 estimateTokens, bool isTransfer ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "EXCHANGE"; string public symbol = "DICE"; uint8 constant public decimals = 18; uint8 constant internal dividendFee_ = 20; // 20% dividend fee on each buy and sell uint8 constant internal fundFee_ = 5; // 5% to dice game uint256 constant internal tokenPriceInitial_ = 0.00000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.000000001 ether; uint256 constant internal magnitude = 2**64; // Address to send the 5% Fee address public giveEthFundAddress = 0x0; bool public finalizedEthFundAddress = false; uint256 public totalEthFundReceived; // total ETH charity received from this contract uint256 public totalEthFundCollected; // total ETH charity collected in this contract // proof of stake (defaults at 250 tokens) uint256 public stakingRequirement = 25e18; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 4 ether; uint256 constant internal ambassadorQuota_ = 4 ether; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; // administrator list (see above on what they can do) mapping(address => bool) public administrators; // when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid) bool public onlyAmbassadors = true; // To whitelist game contracts on the platform mapping(address => bool) public canAcceptTokens_; // contracts, which can accept the exchanges tokens /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ constructor() public { // add administrators here administrators[0xB477ACeb6262b12a3c7b2445027a072f95C75Bd3] = true; // add the ambassadors here ambassadors_[0xB477ACeb6262b12a3c7b2445027a072f95C75Bd3] = true; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) */ function buy(address _referredBy) public payable returns(uint256) { require(tx.gasprice <= 0.05 szabo); purchaseTokens(msg.value, _referredBy, false); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { require(tx.gasprice <= 0.05 szabo); purchaseTokens(msg.value, 0x0, false); } function updateFundAddress(address _newAddress) onlyAdministrator() public { require(finalizedEthFundAddress == false); giveEthFundAddress = _newAddress; } function finalizeFundAddress(address _finalAddress) onlyAdministrator() public { require(finalizedEthFundAddress == false); giveEthFundAddress = _finalAddress; finalizedEthFundAddress = true; } /** * Sends fund to dice smart contract * No Reentrancy attack as address is finalized to dice smart contract */ function payFund() payable public { uint256 ethToPay = SafeMath.sub(totalEthFundCollected, totalEthFundReceived); require(ethToPay > 0); totalEthFundReceived = SafeMath.add(totalEthFundReceived, ethToPay); if(!giveEthFundAddress.call.value(ethToPay)()) { revert(); } } /** * Converts all of caller's dividends to tokens. */ function reinvest() onlyStronghands() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0, true); // fire event emit onReinvestment(_customerAddress, _dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); // lambo delivery service withdraw(false); } /** * Withdraws all of the callers earnings. */ function withdraw(bool _isTransfer) onlyStronghands() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code uint256 _estimateTokens = calculateTokensReceived(_dividends); // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event emit onWithdraw(_customerAddress, _dividends, _estimateTokens, _isTransfer); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); // Take out dividends and then _fundPayout uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout); // Add ethereum to send to fund totalEthFundCollected = SafeMath.add(totalEthFundCollected, _fundPayout); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire event emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice()); } /** * Transfer tokens from the caller to a new holder. * REMEMBER THIS IS 0% TRANSFER FEE */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens // also disables transfers until ambassador phase is over // ( we dont want whale premines ) require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(true); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens); // fire event emit Transfer(_customerAddress, _toAddress, _amountOfTokens); // ERC20 return true; } /** * Transfer token to a specified address and forward the data to recipient * ERC-677 standard * https://github.com/ethereum/EIPs/issues/677 * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _data Transaction metadata. */ function transferAndCall(address _to, uint256 _value, bytes _data) external returns (bool) { require(_to != address(0)); require(canAcceptTokens_[_to] == true); // security check that contract approved by the exchange require(transfer(_to, _value)); // do a normal token transfer to the contract if (isContract(_to)) { AcceptsExchange receiver = AcceptsExchange(_to); require(receiver.tokenFallback(msg.sender, _value, _data)); } return true; } /** * Additional check that the game address we are sending tokens to is a contract * assemble the given address bytecode. If bytecode exists then the _addr is a contract. */ function isContract(address _addr) private constant returns (bool is_contract) { // retrieve the size of the code on target address, this needs assembly uint length; assembly { length := extcodesize(_addr) } return length > 0; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * Add or remove game contract, which can accept tokens */ function setCanAcceptTokens(address _address, bool _value) onlyAdministrator() public { canAcceptTokens_[_address] = _value; } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return address(this).balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); uint256 _taxedEthereum = SafeMath.add(SafeMath.add(_ethereum, _dividends), _fundPayout); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereumToSpend, fundFee_), 100); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereumToSpend, _dividends), _fundPayout); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout); return _taxedEthereum; } /** * Function for the frontend to show ether waiting to be send to fund in contract */ function etherToSendFund() public view returns(uint256) { return SafeMath.sub(totalEthFundCollected, totalEthFundReceived); } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy, bool _isReinvest) antiEarlyWhale(_incomingEthereum) internal returns(uint256) { // data setup uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, dividendFee_), 100); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_incomingEthereum, fundFee_), 100); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_incomingEthereum, _undividedDividends), _fundPayout); totalEthFundCollected = SafeMath.add(totalEthFundCollected, _fundPayout); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; // no point in continuing execution if OP is a poor russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equation. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != msg.sender && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can't give people infinite ethereum if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[msg.sender] = SafeMath.add(tokenBalanceLedger_[msg.sender], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; //really i know you think you do but you don't int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[msg.sender] += _updatedPayouts; // fire event emit onTokenPurchase(msg.sender, _incomingEthereum, _amountOfTokens, _referredBy, _isReinvest, now, buyPrice()); return _amountOfTokens; } /** * Calculate Token price based on an amount of incoming ethereum * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
data setup no point in continuing execution if OP is a poor russian hacker prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world (or hackers) and yes we know that the safemath function automatically rules out the "greater then" equation. is the user referred by a masternode? is this a referred purchase? no cheating! does the referrer have at least X whole tokens? i.e is the referrer a godly chad masternode wealth redistribution no ref purchase add the referral bonus back to the global dividends cake we can't give people infinite ethereum add tokens to the pool take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder calculate the amount of tokens the customer receives over his purchase add tokens to the pool
function purchaseTokens(uint256 _incomingEthereum, address _referredBy, bool _isReinvest) antiEarlyWhale(_incomingEthereum) internal returns(uint256) { uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, dividendFee_), 100); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_incomingEthereum, fundFee_), 100); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_incomingEthereum, _undividedDividends), _fundPayout); totalEthFundCollected = SafeMath.add(totalEthFundCollected, _fundPayout); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); if( _referredBy != 0x0000000000000000000000000000000000000000 && _referredBy != msg.sender && tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } if(tokenSupply_ > 0){ tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); tokenSupply_ = _amountOfTokens; } payoutsTo_[msg.sender] += _updatedPayouts; return _amountOfTokens; }
9,892,067
[ 1, 892, 3875, 1158, 1634, 316, 29702, 4588, 309, 7247, 353, 279, 8275, 280, 436, 5567, 2779, 11769, 264, 17793, 9391, 316, 326, 648, 716, 326, 2395, 23083, 28578, 4447, 6478, 2542, 3832, 1399, 635, 3614, 476, 316, 326, 9117, 261, 280, 11769, 414, 13, 471, 12465, 732, 5055, 716, 326, 11029, 351, 421, 445, 6635, 2931, 596, 326, 315, 11556, 2045, 1508, 6, 15778, 18, 353, 326, 729, 29230, 635, 279, 4171, 2159, 35, 353, 333, 279, 29230, 23701, 35, 1158, 19315, 1776, 5, 1552, 326, 14502, 1240, 622, 4520, 1139, 7339, 2430, 35, 277, 18, 73, 353, 326, 14502, 279, 314, 369, 715, 462, 361, 4171, 2159, 732, 4162, 5813, 4027, 1158, 1278, 23701, 527, 326, 1278, 29084, 324, 22889, 1473, 358, 326, 2552, 3739, 350, 5839, 276, 911, 732, 848, 1404, 8492, 16951, 14853, 13750, 822, 379, 527, 2430, 358, 326, 2845, 4862, 326, 3844, 434, 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, 23701, 5157, 12, 11890, 5034, 389, 31033, 41, 18664, 379, 16, 1758, 389, 266, 4193, 858, 16, 1426, 389, 291, 426, 5768, 395, 13, 203, 3639, 30959, 41, 20279, 2888, 5349, 24899, 31033, 41, 18664, 379, 13, 203, 3639, 2713, 203, 3639, 1135, 12, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2254, 5034, 389, 1074, 427, 13898, 7244, 350, 5839, 273, 14060, 10477, 18, 2892, 12, 9890, 10477, 18, 16411, 24899, 31033, 41, 18664, 379, 16, 31945, 14667, 67, 3631, 2130, 1769, 203, 3639, 2254, 5034, 389, 1734, 29084, 38, 22889, 273, 14060, 10477, 18, 2892, 24899, 1074, 427, 13898, 7244, 350, 5839, 16, 890, 1769, 203, 3639, 2254, 5034, 389, 74, 1074, 52, 2012, 273, 14060, 10477, 18, 2892, 12, 9890, 10477, 18, 16411, 24899, 31033, 41, 18664, 379, 16, 284, 1074, 14667, 67, 3631, 2130, 1769, 203, 3639, 2254, 5034, 389, 2892, 350, 5839, 273, 14060, 10477, 18, 1717, 24899, 1074, 427, 13898, 7244, 350, 5839, 16, 389, 1734, 29084, 38, 22889, 1769, 203, 3639, 2254, 5034, 389, 8066, 329, 41, 18664, 379, 273, 14060, 10477, 18, 1717, 12, 9890, 10477, 18, 1717, 24899, 31033, 41, 18664, 379, 16, 389, 1074, 427, 13898, 7244, 350, 5839, 3631, 389, 74, 1074, 52, 2012, 1769, 203, 3639, 2078, 41, 451, 42, 1074, 10808, 329, 273, 14060, 10477, 18, 1289, 12, 4963, 41, 451, 42, 1074, 10808, 329, 16, 389, 74, 1074, 52, 2012, 1769, 203, 203, 3639, 2254, 5034, 389, 8949, 951, 5157, 273, 13750, 822, 379, 774, 5157, 67, 24899, 2 ]
./partial_match/4/0x1799D9F854e4b6BF9C65C8D05cc239d7097b0461/sources/LendingPool.sol
* @dev Checks if the min and max numbers are within the acceptable tolerance @param self The Value this function was called on @param tolerancePercentage Acceptable tolerance percentage as a whole number The percentage should be entered with 2 decimal places. e.g. 2.5% should be entered as 250. @return boolean/
function isWithinTolerance(Values storage self, uint256 tolerancePercentage) internal view returns (bool) { if (isEmpty(self)) { return false; } uint256 average = getAverage(self); uint256 toleranceAmount = average.percent(tolerancePercentage); uint256 minTolerance = average.sub(toleranceAmount); if (self.min < minTolerance) { return false; } uint256 maxTolerance = average.add(toleranceAmount); if (self.max > maxTolerance) { return false; } return true; }
8,542,498
[ 1, 4081, 309, 326, 1131, 471, 943, 5600, 854, 3470, 326, 14206, 10673, 225, 365, 1021, 1445, 333, 445, 1703, 2566, 603, 225, 10673, 16397, 8662, 429, 10673, 11622, 487, 279, 7339, 1300, 1021, 11622, 1410, 506, 16219, 598, 576, 6970, 12576, 18, 425, 18, 75, 18, 576, 18, 25, 9, 1410, 506, 16219, 487, 16927, 18, 327, 1250, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 353, 18949, 22678, 12, 1972, 2502, 365, 16, 2254, 5034, 10673, 16397, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 309, 261, 291, 1921, 12, 2890, 3719, 288, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 3639, 2254, 5034, 8164, 273, 4506, 5682, 12, 2890, 1769, 203, 3639, 2254, 5034, 10673, 6275, 273, 8164, 18, 8849, 12, 25456, 16397, 1769, 203, 203, 3639, 2254, 5034, 1131, 22678, 273, 8164, 18, 1717, 12, 25456, 6275, 1769, 203, 3639, 309, 261, 2890, 18, 1154, 411, 1131, 22678, 13, 288, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 943, 22678, 273, 8164, 18, 1289, 12, 25456, 6275, 1769, 203, 3639, 309, 261, 2890, 18, 1896, 405, 943, 22678, 13, 288, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/421613/0x3b40C31DdAc6f1Ef4959c31177794A330F0C2BA8/sources/contracts/facets/KaijuFacetWithPayments.sol
* @inheritdoc IPaymentsReceiver @dev TODO: Implement/
) external onlySpellcasterPayments { emit PaymentReceived( _payor, _paymentERC20, _paymentAmount, _paymentAmountInPricedToken, _priceType, _pricedERC20 ); if (_priceType == PriceType.STATIC) { revert LibMeta.PaymentTypeNotAccepted('STATIC'); revert LibMeta.PaymentTypeNotAccepted('PRICED_IN_ERC20'); revert LibMeta.PaymentTypeNotAccepted('PRICED_IN_GAS_TOKEN'); } if (_paymentERC20 == getMagicTokenAddress()) { _acceptMagicPaymentPricedInUSD( _payor, _paymentAmount, _paymentAmountInPricedToken ); _acceptArbPaymentPricedInUSD( _payor, _paymentAmount, _paymentAmountInPricedToken ); revert LibMeta.PaymentTypeNotAccepted('UNSUPPORTED_TOKEN'); } }
11,567,681
[ 1, 36, 10093, 2971, 528, 1346, 12952, 225, 2660, 30, 10886, 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, 262, 3903, 1338, 3389, 1165, 23748, 23725, 288, 203, 3639, 3626, 12022, 8872, 12, 203, 5411, 389, 10239, 280, 16, 203, 5411, 389, 9261, 654, 39, 3462, 16, 203, 5411, 389, 9261, 6275, 16, 203, 5411, 389, 9261, 6275, 382, 5147, 72, 1345, 16, 203, 5411, 389, 8694, 559, 16, 203, 5411, 389, 8694, 72, 654, 39, 3462, 203, 3639, 11272, 203, 203, 3639, 309, 261, 67, 8694, 559, 422, 20137, 559, 18, 22741, 13, 288, 203, 5411, 15226, 10560, 2781, 18, 6032, 559, 1248, 18047, 2668, 22741, 8284, 203, 5411, 15226, 10560, 2781, 18, 6032, 559, 1248, 18047, 2668, 7698, 23552, 67, 706, 67, 654, 39, 3462, 8284, 203, 5411, 15226, 10560, 2781, 18, 6032, 559, 1248, 18047, 2668, 7698, 23552, 67, 706, 67, 43, 3033, 67, 8412, 8284, 203, 3639, 289, 203, 203, 3639, 309, 261, 67, 9261, 654, 39, 3462, 422, 2108, 346, 335, 1345, 1887, 10756, 288, 203, 5411, 389, 9436, 19289, 6032, 5147, 72, 382, 3378, 40, 12, 203, 7734, 389, 10239, 280, 16, 203, 7734, 389, 9261, 6275, 16, 203, 7734, 389, 9261, 6275, 382, 5147, 72, 1345, 203, 5411, 11272, 203, 5411, 389, 9436, 686, 70, 6032, 5147, 72, 382, 3378, 40, 12, 203, 7734, 389, 10239, 280, 16, 203, 7734, 389, 9261, 6275, 16, 203, 7734, 389, 9261, 6275, 382, 5147, 72, 1345, 203, 5411, 11272, 203, 5411, 15226, 10560, 2781, 18, 6032, 559, 1248, 18047, 2668, 2124, 21134, 67, 8412, 8284, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100 ]
//created by Quanli Technology (Hong Kong) Limited; www.quan-li.com pragma solidity ^0.4.24; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract TokenERC20 { address public owner; // current owner of the contract uint256 public feesA = 10; address public addressA = 0x82914CFc37c46fbbb830150cF2330B80DAADa2D5; function founder() private { // contract&#39;s constructor function owner = msg.sender; } function change_owner (address newOwner) public{ require(owner == msg.sender); owner = newOwner; emit Changeownerlog(newOwner); } function setfees (uint256 _value1) public { require(owner == msg.sender); if (_value1>0){ feesA = _value1; emit Setfeeslog(_value1); }else { } } function setaddress (address _address1) public { require(owner == msg.sender); addressA = _address1; emit Setfeeaddrlog(_address1); } // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); event Fee1(address indexed from, address indexed to, uint256 value); // Reissue event Reissuelog(uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); //setfees event Setfeeslog(uint256 fee1); //setfeeaddress event Setfeeaddrlog(address); //changeowner event Changeownerlog(address); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes owner = msg.sender; // Set contract owner } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender&#39;s allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } function transfer(address _to, uint256 _value) public { uint256 fees1 = (feesA *_value)/10000; _value -= (fees1); _transfer(msg.sender, _to, _value); emit Transfer(msg.sender, _to, _value); _transfer(msg.sender, addressA, fees1); emit Fee1(msg.sender, addressA, fees1); } function Reissue(uint256 _value) public { require(owner == msg.sender); balanceOf[msg.sender] += _value; // Add to the sender totalSupply += _value; // Updates totalSupply emit Reissuelog(_value); } }
current owner of the contract
address public owner;
10,703,603
[ 1, 2972, 3410, 434, 326, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 377, 1758, 1071, 3410, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/84531/0x878d7F08c5EE4a39b961513bD708324354d11e22/sources/contracts/prop.sol
GEB_STABILITY_FEE_TREASURY GEB_STABILITY_FEE_TREASURY
Setter public constant stabilityFeeTreasury = Setter(0x83533fdd3285f48204215E9CF38C785371258E76);
11,500,949
[ 1, 7113, 38, 67, 882, 22879, 67, 8090, 41, 67, 56, 862, 3033, 1099, 61, 18701, 17788, 38, 67, 882, 22879, 67, 8090, 41, 67, 56, 862, 3033, 1099, 61, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 1000, 387, 1071, 5381, 384, 2967, 14667, 56, 266, 345, 22498, 273, 1000, 387, 12, 20, 92, 28, 4763, 3707, 74, 449, 1578, 7140, 74, 8875, 21573, 22, 3600, 41, 29, 8955, 7414, 39, 27, 7140, 6418, 2138, 8204, 41, 6669, 1769, 1377, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xF708005ceE17b2c5Fe1a01591E32ad6183A12EaE/sources/@yield-protocol/vault-v2/contracts/interfaces/DataTypes.sol
Current debt for a given underlying, across all series
uint128 sum;
2,802,741
[ 1, 3935, 18202, 88, 364, 279, 864, 6808, 16, 10279, 777, 4166, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 10392, 2142, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier:UNLICENSED pragma solidity ^0.8.0; contract VolanoCoin { //Create a variable to hold the total supply of 10000. uint256 public totalSupply; //Initialise an address variable called owner address owner; //create a modifier which only allows an owner to execute certain functions modifier onlyOwner() { if (msg.sender == owner) { _; } } event SupplyChange(uint256); //Create a variable to hold the total supply of 10000. //Create aconstructor and within the constructor, store the owner’s address. constructor() { totalSupply = 10000; owner = msg.sender; } //Make a public function that returns the total supply. function AllTotalSupply() public view returns (uint256) { // supply = _supply; return totalSupply; } //Make a function that can increase the total supply. Inside the function, add 1000 tokensto the current total supply. //Make your increase total supply function public, but add your modifier so that only theowner can execute it. function increaseSupply(uint256 _amount) public onlyOwner { totalSupply = totalSupply + _amount; emit SupplyChange(totalSupply); } }
Create a variable to hold the total supply of 10000.Create aconstructor and within the constructor, store the owner’s address.
constructor() { totalSupply = 10000; owner = msg.sender; }
7,288,029
[ 1, 1684, 279, 2190, 358, 6887, 326, 2078, 14467, 434, 12619, 18, 1684, 279, 12316, 471, 3470, 326, 3885, 16, 1707, 326, 3410, 163, 227, 252, 87, 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 ]
[ 1, 1, 1, 1, 1, 1, 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, 3885, 1435, 288, 203, 3639, 2078, 3088, 1283, 273, 12619, 31, 203, 3639, 3410, 273, 1234, 18, 15330, 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, -100, -100, -100, -100 ]
./partial_match/1/0xA53de764935d71968c7B5d311E6E76Ba22109a11/sources/DharmaTradeReserveV17ImplementationStaging.sol
* @notice Internal trade function. If token is _TRADE_FOR_USDC_AND_RETAIN_FLAG, trade for USDC and retain the full output amount by replacing the recipient ("to" input) on the swapETHForExactTokens call./ Set swap target token. Establish path from Ether to token. Trade Ether for quoted token amount and send to appropriate recipient.
) internal returns (uint256 totalEtherSold) { address tokenReceived = ( tokenReceivedOrUSDCFlag == _TRADE_FOR_USDC_AND_RETAIN_FLAG ? address(_USDC) : tokenReceivedOrUSDCFlag ); (address[] memory path, uint256[] memory amounts) = _createPathAndAmounts( _WETH, tokenReceived, false ); amounts = _UNISWAP_ROUTER.swapETHForExactTokens.value(etherAmount)( quotedTokenAmount, path, fromReserves || tokenReceivedOrUSDCFlag == _TRADE_FOR_USDC_AND_RETAIN_FLAG ? address(this) : msg.sender, deadline ); totalEtherSold = amounts[0]; }
9,400,991
[ 1, 3061, 18542, 445, 18, 971, 1147, 353, 389, 20060, 1639, 67, 7473, 67, 3378, 5528, 67, 4307, 67, 10238, 6964, 67, 9651, 16, 18542, 364, 11836, 5528, 471, 15096, 326, 1983, 876, 3844, 635, 13993, 326, 8027, 7566, 869, 6, 810, 13, 603, 326, 7720, 1584, 44, 1290, 14332, 5157, 745, 18, 19, 1000, 7720, 1018, 1147, 18, 17787, 23385, 589, 628, 512, 1136, 358, 1147, 18, 2197, 323, 512, 1136, 364, 9298, 1147, 3844, 471, 1366, 358, 5505, 8027, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 262, 2713, 1135, 261, 11890, 5034, 2078, 41, 1136, 55, 1673, 13, 288, 203, 565, 1758, 1147, 8872, 273, 261, 203, 1377, 1147, 8872, 1162, 3378, 5528, 4678, 422, 389, 20060, 1639, 67, 7473, 67, 3378, 5528, 67, 4307, 67, 10238, 6964, 67, 9651, 203, 3639, 692, 1758, 24899, 3378, 5528, 13, 203, 3639, 294, 1147, 8872, 1162, 3378, 5528, 4678, 203, 565, 11272, 203, 203, 565, 261, 2867, 8526, 3778, 589, 16, 2254, 5034, 8526, 3778, 30980, 13, 273, 389, 2640, 743, 1876, 6275, 87, 12, 203, 1377, 389, 59, 1584, 44, 16, 1147, 8872, 16, 629, 203, 565, 11272, 203, 203, 565, 30980, 273, 389, 2124, 5127, 59, 2203, 67, 1457, 1693, 654, 18, 22270, 1584, 44, 1290, 14332, 5157, 18, 1132, 12, 2437, 6275, 21433, 203, 1377, 9298, 1345, 6275, 16, 203, 1377, 589, 16, 203, 1377, 628, 607, 264, 3324, 747, 1147, 8872, 1162, 3378, 5528, 4678, 422, 389, 20060, 1639, 67, 7473, 67, 3378, 5528, 67, 4307, 67, 10238, 6964, 67, 9651, 203, 3639, 692, 1758, 12, 2211, 13, 203, 3639, 294, 1234, 18, 15330, 16, 203, 1377, 14096, 203, 565, 11272, 203, 565, 2078, 41, 1136, 55, 1673, 273, 30980, 63, 20, 15533, 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 ]
pragma solidity 0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer( address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve( address _spender, uint256 _value ) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval( address _spender, uint _addedValue ) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval( address _spender, uint _subtractedValue ) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } contract RepublicToken is PausableToken, BurnableToken { string public constant name = "Republic Token"; string public constant symbol = "REN"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 1000000000 * 10**uint256(decimals); /// @notice The RepublicToken Constructor. constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } function transferTokens(address beneficiary, uint256 amount) public onlyOwner returns (bool) { /* solium-disable error-reason */ require(amount > 0); balances[owner] = balances[owner].sub(amount); balances[beneficiary] = balances[beneficiary].add(amount); emit Transfer(owner, beneficiary, amount); return true; } } /** * @notice LinkedList is a library for a circular double linked list. */ library LinkedList { /* * @notice A permanent NULL node (0x0) in the circular double linked list. * NULL.next is the head, and NULL.previous is the tail. */ address public constant NULL = 0x0; /** * @notice A node points to the node before it, and the node after it. If * node.previous = NULL, then the node is the head of the list. If * node.next = NULL, then the node is the tail of the list. */ struct Node { bool inList; address previous; address next; } /** * @notice LinkedList uses a mapping from address to nodes. Each address * uniquely identifies a node, and in this way they are used like pointers. */ struct List { mapping (address => Node) list; } /** * @notice Insert a new node before an existing node. * * @param self The list being used. * @param target The existing node in the list. * @param newNode The next node to insert before the target. */ function insertBefore(List storage self, address target, address newNode) internal { require(!isInList(self, newNode), "already in list"); require(isInList(self, target) || target == NULL, "not in list"); // It is expected that this value is sometimes NULL. address prev = self.list[target].previous; self.list[newNode].next = target; self.list[newNode].previous = prev; self.list[target].previous = newNode; self.list[prev].next = newNode; self.list[newNode].inList = true; } /** * @notice Insert a new node after an existing node. * * @param self The list being used. * @param target The existing node in the list. * @param newNode The next node to insert after the target. */ function insertAfter(List storage self, address target, address newNode) internal { require(!isInList(self, newNode), "already in list"); require(isInList(self, target) || target == NULL, "not in list"); // It is expected that this value is sometimes NULL. address n = self.list[target].next; self.list[newNode].previous = target; self.list[newNode].next = n; self.list[target].next = newNode; self.list[n].previous = newNode; self.list[newNode].inList = true; } /** * @notice Remove a node from the list, and fix the previous and next * pointers that are pointing to the removed node. Removing anode that is not * in the list will do nothing. * * @param self The list being using. * @param node The node in the list to be removed. */ function remove(List storage self, address node) internal { require(isInList(self, node), "not in list"); if (node == NULL) { return; } address p = self.list[node].previous; address n = self.list[node].next; self.list[p].next = n; self.list[n].previous = p; // Deleting the node should set this value to false, but we set it here for // explicitness. self.list[node].inList = false; delete self.list[node]; } /** * @notice Insert a node at the beginning of the list. * * @param self The list being used. * @param node The node to insert at the beginning of the list. */ function prepend(List storage self, address node) internal { // isInList(node) is checked in insertBefore insertBefore(self, begin(self), node); } /** * @notice Insert a node at the end of the list. * * @param self The list being used. * @param node The node to insert at the end of the list. */ function append(List storage self, address node) internal { // isInList(node) is checked in insertBefore insertAfter(self, end(self), node); } function swap(List storage self, address left, address right) internal { // isInList(left) and isInList(right) are checked in remove address previousRight = self.list[right].previous; remove(self, right); insertAfter(self, left, right); remove(self, left); insertAfter(self, previousRight, left); } function isInList(List storage self, address node) internal view returns (bool) { return self.list[node].inList; } /** * @notice Get the node at the beginning of a double linked list. * * @param self The list being used. * * @return A address identifying the node at the beginning of the double * linked list. */ function begin(List storage self) internal view returns (address) { return self.list[NULL].next; } /** * @notice Get the node at the end of a double linked list. * * @param self The list being used. * * @return A address identifying the node at the end of the double linked * list. */ function end(List storage self) internal view returns (address) { return self.list[NULL].previous; } function next(List storage self, address node) internal view returns (address) { require(isInList(self, node), "not in list"); return self.list[node].next; } function previous(List storage self, address node) internal view returns (address) { require(isInList(self, node), "not in list"); return self.list[node].previous; } } /// @notice This contract stores data and funds for the DarknodeRegistry /// contract. The data / fund logic and storage have been separated to improve /// upgradability. contract DarknodeRegistryStore is Ownable { string public VERSION; // Passed in as a constructor parameter. /// @notice Darknodes are stored in the darknode struct. The owner is the /// address that registered the darknode, the bond is the amount of REN that /// was transferred during registration, and the public key is the /// encryption key that should be used when sending sensitive information to /// the darknode. struct Darknode { // The owner of a Darknode is the address that called the register // function. The owner is the only address that is allowed to // deregister the Darknode, unless the Darknode is slashed for // malicious behavior. address owner; // The bond is the amount of REN submitted as a bond by the Darknode. // This amount is reduced when the Darknode is slashed for malicious // behavior. uint256 bond; // The block number at which the Darknode is considered registered. uint256 registeredAt; // The block number at which the Darknode is considered deregistered. uint256 deregisteredAt; // The public key used by this Darknode for encrypting sensitive data // off chain. It is assumed that the Darknode has access to the // respective private key, and that there is an agreement on the format // of the public key. bytes publicKey; } /// Registry data. mapping(address => Darknode) private darknodeRegistry; LinkedList.List private darknodes; // RepublicToken. RepublicToken public ren; /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _ren The address of the RepublicToken contract. constructor( string _VERSION, RepublicToken _ren ) public { VERSION = _VERSION; ren = _ren; } /// @notice Instantiates a darknode and appends it to the darknodes /// linked-list. /// /// @param _darknodeID The darknode's ID. /// @param _darknodeOwner The darknode's owner's address /// @param _bond The darknode's bond value /// @param _publicKey The darknode's public key /// @param _registeredAt The time stamp when the darknode is registered. /// @param _deregisteredAt The time stamp when the darknode is deregistered. function appendDarknode( address _darknodeID, address _darknodeOwner, uint256 _bond, bytes _publicKey, uint256 _registeredAt, uint256 _deregisteredAt ) external onlyOwner { Darknode memory darknode = Darknode({ owner: _darknodeOwner, bond: _bond, publicKey: _publicKey, registeredAt: _registeredAt, deregisteredAt: _deregisteredAt }); darknodeRegistry[_darknodeID] = darknode; LinkedList.append(darknodes, _darknodeID); } /// @notice Returns the address of the first darknode in the store function begin() external view onlyOwner returns(address) { return LinkedList.begin(darknodes); } /// @notice Returns the address of the next darknode in the store after the /// given address. function next(address darknodeID) external view onlyOwner returns(address) { return LinkedList.next(darknodes, darknodeID); } /// @notice Removes a darknode from the store and transfers its bond to the /// owner of this contract. function removeDarknode(address darknodeID) external onlyOwner { uint256 bond = darknodeRegistry[darknodeID].bond; delete darknodeRegistry[darknodeID]; LinkedList.remove(darknodes, darknodeID); require(ren.transfer(owner, bond), "bond transfer failed"); } /// @notice Updates the bond of the darknode. If the bond is being /// decreased, the difference is sent to the owner of this contract. function updateDarknodeBond(address darknodeID, uint256 bond) external onlyOwner { uint256 previousBond = darknodeRegistry[darknodeID].bond; darknodeRegistry[darknodeID].bond = bond; if (previousBond > bond) { require(ren.transfer(owner, previousBond - bond), "cannot transfer bond"); } } /// @notice Updates the deregistration timestamp of a darknode. function updateDarknodeDeregisteredAt(address darknodeID, uint256 deregisteredAt) external onlyOwner { darknodeRegistry[darknodeID].deregisteredAt = deregisteredAt; } /// @notice Returns the owner of a given darknode. function darknodeOwner(address darknodeID) external view onlyOwner returns (address) { return darknodeRegistry[darknodeID].owner; } /// @notice Returns the bond of a given darknode. function darknodeBond(address darknodeID) external view onlyOwner returns (uint256) { return darknodeRegistry[darknodeID].bond; } /// @notice Returns the registration time of a given darknode. function darknodeRegisteredAt(address darknodeID) external view onlyOwner returns (uint256) { return darknodeRegistry[darknodeID].registeredAt; } /// @notice Returns the deregistration time of a given darknode. function darknodeDeregisteredAt(address darknodeID) external view onlyOwner returns (uint256) { return darknodeRegistry[darknodeID].deregisteredAt; } /// @notice Returns the encryption public key of a given darknode. function darknodePublicKey(address darknodeID) external view onlyOwner returns (bytes) { return darknodeRegistry[darknodeID].publicKey; } } /// @notice DarknodeRegistry is responsible for the registration and /// deregistration of Darknodes. contract DarknodeRegistry is Ownable { string public VERSION; // Passed in as a constructor parameter. /// @notice Darknode pods are shuffled after a fixed number of blocks. /// An Epoch stores an epoch hash used as an (insecure) RNG seed, and the /// blocknumber which restricts when the next epoch can be called. struct Epoch { uint256 epochhash; uint256 blocknumber; } uint256 public numDarknodes; uint256 public numDarknodesNextEpoch; uint256 public numDarknodesPreviousEpoch; /// Variables used to parameterize behavior. uint256 public minimumBond; uint256 public minimumPodSize; uint256 public minimumEpochInterval; address public slasher; /// When one of the above variables is modified, it is only updated when the /// next epoch is called. These variables store the values for the next epoch. uint256 public nextMinimumBond; uint256 public nextMinimumPodSize; uint256 public nextMinimumEpochInterval; address public nextSlasher; /// The current and previous epoch Epoch public currentEpoch; Epoch public previousEpoch; /// Republic ERC20 token contract used to transfer bonds. RepublicToken public ren; /// Darknode Registry Store is the storage contract for darknodes. DarknodeRegistryStore public store; /// @notice Emitted when a darknode is registered. /// @param _darknodeID The darknode ID that was registered. /// @param _bond The amount of REN that was transferred as bond. event LogDarknodeRegistered(address _darknodeID, uint256 _bond); /// @notice Emitted when a darknode is deregistered. /// @param _darknodeID The darknode ID that was deregistered. event LogDarknodeDeregistered(address _darknodeID); /// @notice Emitted when a refund has been made. /// @param _owner The address that was refunded. /// @param _amount The amount of REN that was refunded. event LogDarknodeOwnerRefunded(address _owner, uint256 _amount); /// @notice Emitted when a new epoch has begun. event LogNewEpoch(); /// @notice Emitted when a constructor parameter has been updated. event LogMinimumBondUpdated(uint256 previousMinimumBond, uint256 nextMinimumBond); event LogMinimumPodSizeUpdated(uint256 previousMinimumPodSize, uint256 nextMinimumPodSize); event LogMinimumEpochIntervalUpdated(uint256 previousMinimumEpochInterval, uint256 nextMinimumEpochInterval); event LogSlasherUpdated(address previousSlasher, address nextSlasher); /// @notice Only allow the owner that registered the darknode to pass. modifier onlyDarknodeOwner(address _darknodeID) { require(store.darknodeOwner(_darknodeID) == msg.sender, "must be darknode owner"); _; } /// @notice Only allow unregistered darknodes. modifier onlyRefunded(address _darknodeID) { require(isRefunded(_darknodeID), "must be refunded or never registered"); _; } /// @notice Only allow refundable darknodes. modifier onlyRefundable(address _darknodeID) { require(isRefundable(_darknodeID), "must be deregistered for at least one epoch"); _; } /// @notice Only allowed registered nodes without a pending deregistration to /// deregister modifier onlyDeregisterable(address _darknodeID) { require(isDeregisterable(_darknodeID), "must be deregisterable"); _; } /// @notice Only allow the Slasher contract. modifier onlySlasher() { require(slasher == msg.sender, "must be slasher"); _; } /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _renAddress The address of the RepublicToken contract. /// @param _storeAddress The address of the DarknodeRegistryStore contract. /// @param _minimumBond The minimum bond amount that can be submitted by a /// Darknode. /// @param _minimumPodSize The minimum size of a Darknode pod. /// @param _minimumEpochInterval The minimum number of blocks between /// epochs. constructor( string _VERSION, RepublicToken _renAddress, DarknodeRegistryStore _storeAddress, uint256 _minimumBond, uint256 _minimumPodSize, uint256 _minimumEpochInterval ) public { VERSION = _VERSION; store = _storeAddress; ren = _renAddress; minimumBond = _minimumBond; nextMinimumBond = minimumBond; minimumPodSize = _minimumPodSize; nextMinimumPodSize = minimumPodSize; minimumEpochInterval = _minimumEpochInterval; nextMinimumEpochInterval = minimumEpochInterval; currentEpoch = Epoch({ epochhash: uint256(blockhash(block.number - 1)), blocknumber: block.number }); numDarknodes = 0; numDarknodesNextEpoch = 0; numDarknodesPreviousEpoch = 0; } /// @notice Register a darknode and transfer the bond to this contract. The /// caller must provide a public encryption key for the darknode as well as /// a bond in REN. The bond must be provided as an ERC20 allowance. The dark /// node will remain pending registration until the next epoch. Only after /// this period can the darknode be deregistered. The caller of this method /// will be stored as the owner of the darknode. /// /// @param _darknodeID The darknode ID that will be registered. /// @param _publicKey The public key of the darknode. It is stored to allow /// other darknodes and traders to encrypt messages to the trader. /// @param _bond The bond that will be paid. It must be greater than, or /// equal to, the minimum bond. function register(address _darknodeID, bytes _publicKey, uint256 _bond) external onlyRefunded(_darknodeID) { // REN allowance require(_bond >= minimumBond, "insufficient bond"); // require(ren.allowance(msg.sender, address(this)) >= _bond); require(ren.transferFrom(msg.sender, address(this), _bond), "bond transfer failed"); ren.transfer(address(store), _bond); // Flag this darknode for registration store.appendDarknode( _darknodeID, msg.sender, _bond, _publicKey, currentEpoch.blocknumber + minimumEpochInterval, 0 ); numDarknodesNextEpoch += 1; // Emit an event. emit LogDarknodeRegistered(_darknodeID, _bond); } /// @notice Deregister a darknode. The darknode will not be deregistered /// until the end of the epoch. After another epoch, the bond can be /// refunded by calling the refund method. /// @param _darknodeID The darknode ID that will be deregistered. The caller /// of this method store.darknodeRegisteredAt(_darknodeID) must be // the owner of this darknode. function deregister(address _darknodeID) external onlyDeregisterable(_darknodeID) onlyDarknodeOwner(_darknodeID) { // Flag the darknode for deregistration store.updateDarknodeDeregisteredAt(_darknodeID, currentEpoch.blocknumber + minimumEpochInterval); numDarknodesNextEpoch -= 1; // Emit an event emit LogDarknodeDeregistered(_darknodeID); } /// @notice Progress the epoch if it is possible to do so. This captures /// the current timestamp and current blockhash and overrides the current /// epoch. function epoch() external { if (previousEpoch.blocknumber == 0) { // The first epoch must be called by the owner of the contract require(msg.sender == owner, "not authorized (first epochs)"); } // Require that the epoch interval has passed require(block.number >= currentEpoch.blocknumber + minimumEpochInterval, "epoch interval has not passed"); uint256 epochhash = uint256(blockhash(block.number - 1)); // Update the epoch hash and timestamp previousEpoch = currentEpoch; currentEpoch = Epoch({ epochhash: epochhash, blocknumber: block.number }); // Update the registry information numDarknodesPreviousEpoch = numDarknodes; numDarknodes = numDarknodesNextEpoch; // If any update functions have been called, update the values now if (nextMinimumBond != minimumBond) { minimumBond = nextMinimumBond; emit LogMinimumBondUpdated(minimumBond, nextMinimumBond); } if (nextMinimumPodSize != minimumPodSize) { minimumPodSize = nextMinimumPodSize; emit LogMinimumPodSizeUpdated(minimumPodSize, nextMinimumPodSize); } if (nextMinimumEpochInterval != minimumEpochInterval) { minimumEpochInterval = nextMinimumEpochInterval; emit LogMinimumEpochIntervalUpdated(minimumEpochInterval, nextMinimumEpochInterval); } if (nextSlasher != slasher) { slasher = nextSlasher; emit LogSlasherUpdated(slasher, nextSlasher); } // Emit an event emit LogNewEpoch(); } /// @notice Allows the contract owner to transfer ownership of the /// DarknodeRegistryStore. /// @param _newOwner The address to transfer the ownership to. function transferStoreOwnership(address _newOwner) external onlyOwner { store.transferOwnership(_newOwner); } /// @notice Allows the contract owner to update the minimum bond. /// @param _nextMinimumBond The minimum bond amount that can be submitted by /// a darknode. function updateMinimumBond(uint256 _nextMinimumBond) external onlyOwner { // Will be updated next epoch nextMinimumBond = _nextMinimumBond; } /// @notice Allows the contract owner to update the minimum pod size. /// @param _nextMinimumPodSize The minimum size of a pod. function updateMinimumPodSize(uint256 _nextMinimumPodSize) external onlyOwner { // Will be updated next epoch nextMinimumPodSize = _nextMinimumPodSize; } /// @notice Allows the contract owner to update the minimum epoch interval. /// @param _nextMinimumEpochInterval The minimum number of blocks between epochs. function updateMinimumEpochInterval(uint256 _nextMinimumEpochInterval) external onlyOwner { // Will be updated next epoch nextMinimumEpochInterval = _nextMinimumEpochInterval; } /// @notice Allow the contract owner to update the DarknodeSlasher contract /// address. /// @param _slasher The new slasher address. function updateSlasher(address _slasher) external onlyOwner { nextSlasher = _slasher; } /// @notice Allow the DarknodeSlasher contract to slash half of a darknode's /// bond and deregister it. The bond is distributed as follows: /// 1/2 is kept by the guilty prover /// 1/8 is rewarded to the first challenger /// 1/8 is rewarded to the second challenger /// 1/4 becomes unassigned /// @param _prover The guilty prover whose bond is being slashed /// @param _challenger1 The first of the two darknodes who submitted the challenge /// @param _challenger2 The second of the two darknodes who submitted the challenge function slash(address _prover, address _challenger1, address _challenger2) external onlySlasher { uint256 penalty = store.darknodeBond(_prover) / 2; uint256 reward = penalty / 4; // Slash the bond of the failed prover in half store.updateDarknodeBond(_prover, penalty); // If the darknode has not been deregistered then deregister it if (isDeregisterable(_prover)) { store.updateDarknodeDeregisteredAt(_prover, currentEpoch.blocknumber + minimumEpochInterval); numDarknodesNextEpoch -= 1; emit LogDarknodeDeregistered(_prover); } // Reward the challengers with less than the penalty so that it is not // worth challenging yourself ren.transfer(store.darknodeOwner(_challenger1), reward); ren.transfer(store.darknodeOwner(_challenger2), reward); } /// @notice Refund the bond of a deregistered darknode. This will make the /// darknode available for registration again. Anyone can call this function /// but the bond will always be refunded to the darknode owner. /// /// @param _darknodeID The darknode ID that will be refunded. The caller /// of this method must be the owner of this darknode. function refund(address _darknodeID) external onlyRefundable(_darknodeID) { address darknodeOwner = store.darknodeOwner(_darknodeID); // Remember the bond amount uint256 amount = store.darknodeBond(_darknodeID); // Erase the darknode from the registry store.removeDarknode(_darknodeID); // Refund the owner by transferring REN ren.transfer(darknodeOwner, amount); // Emit an event. emit LogDarknodeOwnerRefunded(darknodeOwner, amount); } /// @notice Retrieves the address of the account that registered a darknode. /// @param _darknodeID The ID of the darknode to retrieve the owner for. function getDarknodeOwner(address _darknodeID) external view returns (address) { return store.darknodeOwner(_darknodeID); } /// @notice Retrieves the bond amount of a darknode in 10^-18 REN. /// @param _darknodeID The ID of the darknode to retrieve the bond for. function getDarknodeBond(address _darknodeID) external view returns (uint256) { return store.darknodeBond(_darknodeID); } /// @notice Retrieves the encryption public key of the darknode. /// @param _darknodeID The ID of the darknode to retrieve the public key for. function getDarknodePublicKey(address _darknodeID) external view returns (bytes) { return store.darknodePublicKey(_darknodeID); } /// @notice Retrieves a list of darknodes which are registered for the /// current epoch. /// @param _start A darknode ID used as an offset for the list. If _start is /// 0x0, the first dark node will be used. _start won't be /// included it is not registered for the epoch. /// @param _count The number of darknodes to retrieve starting from _start. /// If _count is 0, all of the darknodes from _start are /// retrieved. If _count is more than the remaining number of /// registered darknodes, the rest of the list will contain /// 0x0s. function getDarknodes(address _start, uint256 _count) external view returns (address[]) { uint256 count = _count; if (count == 0) { count = numDarknodes; } return getDarknodesFromEpochs(_start, count, false); } /// @notice Retrieves a list of darknodes which were registered for the /// previous epoch. See `getDarknodes` for the parameter documentation. function getPreviousDarknodes(address _start, uint256 _count) external view returns (address[]) { uint256 count = _count; if (count == 0) { count = numDarknodesPreviousEpoch; } return getDarknodesFromEpochs(_start, count, true); } /// @notice Returns whether a darknode is scheduled to become registered /// at next epoch. /// @param _darknodeID The ID of the darknode to return function isPendingRegistration(address _darknodeID) external view returns (bool) { uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID); return registeredAt != 0 && registeredAt > currentEpoch.blocknumber; } /// @notice Returns if a darknode is in the pending deregistered state. In /// this state a darknode is still considered registered. function isPendingDeregistration(address _darknodeID) external view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return deregisteredAt != 0 && deregisteredAt > currentEpoch.blocknumber; } /// @notice Returns if a darknode is in the deregistered state. function isDeregistered(address _darknodeID) public view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return deregisteredAt != 0 && deregisteredAt <= currentEpoch.blocknumber; } /// @notice Returns if a darknode can be deregistered. This is true if the /// darknodes is in the registered state and has not attempted to /// deregister yet. function isDeregisterable(address _darknodeID) public view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); // The Darknode is currently in the registered state and has not been // transitioned to the pending deregistration, or deregistered, state return isRegistered(_darknodeID) && deregisteredAt == 0; } /// @notice Returns if a darknode is in the refunded state. This is true /// for darknodes that have never been registered, or darknodes that have /// been deregistered and refunded. function isRefunded(address _darknodeID) public view returns (bool) { uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID); uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return registeredAt == 0 && deregisteredAt == 0; } /// @notice Returns if a darknode is refundable. This is true for darknodes /// that have been in the deregistered state for one full epoch. function isRefundable(address _darknodeID) public view returns (bool) { return isDeregistered(_darknodeID) && store.darknodeDeregisteredAt(_darknodeID) <= previousEpoch.blocknumber; } /// @notice Returns if a darknode is in the registered state. function isRegistered(address _darknodeID) public view returns (bool) { return isRegisteredInEpoch(_darknodeID, currentEpoch); } /// @notice Returns if a darknode was in the registered state last epoch. function isRegisteredInPreviousEpoch(address _darknodeID) public view returns (bool) { return isRegisteredInEpoch(_darknodeID, previousEpoch); } /// @notice Returns if a darknode was in the registered state for a given /// epoch. /// @param _darknodeID The ID of the darknode /// @param _epoch One of currentEpoch, previousEpoch function isRegisteredInEpoch(address _darknodeID, Epoch _epoch) private view returns (bool) { uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID); uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); bool registered = registeredAt != 0 && registeredAt <= _epoch.blocknumber; bool notDeregistered = deregisteredAt == 0 || deregisteredAt > _epoch.blocknumber; // The Darknode has been registered and has not yet been deregistered, // although it might be pending deregistration return registered && notDeregistered; } /// @notice Returns a list of darknodes registered for either the current /// or the previous epoch. See `getDarknodes` for documentation on the /// parameters `_start` and `_count`. /// @param _usePreviousEpoch If true, use the previous epoch, otherwise use /// the current epoch. function getDarknodesFromEpochs(address _start, uint256 _count, bool _usePreviousEpoch) private view returns (address[]) { uint256 count = _count; if (count == 0) { count = numDarknodes; } address[] memory nodes = new address[](count); // Begin with the first node in the list uint256 n = 0; address next = _start; if (next == 0x0) { next = store.begin(); } // Iterate until all registered Darknodes have been collected while (n < count) { if (next == 0x0) { break; } // Only include Darknodes that are currently registered bool includeNext; if (_usePreviousEpoch) { includeNext = isRegisteredInPreviousEpoch(next); } else { includeNext = isRegistered(next); } if (!includeNext) { next = store.next(next); continue; } nodes[n] = next; next = store.next(next); n += 1; } return nodes; } } /** * @title Math * @dev Assorted math operations */ library Math { function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } /// @notice Implements safeTransfer, safeTransferFrom and /// safeApprove for CompatibleERC20. /// /// See https://github.com/ethereum/solidity/issues/4116 /// /// This library allows interacting with ERC20 tokens that implement any of /// these interfaces: /// /// (1) transfer returns true on success, false on failure /// (2) transfer returns true on success, reverts on failure /// (3) transfer returns nothing on success, reverts on failure /// /// Additionally, safeTransferFromWithFees will return the final token /// value received after accounting for token fees. library CompatibleERC20Functions { using SafeMath for uint256; /// @notice Calls transfer on the token and reverts if the call fails. function safeTransfer(address token, address to, uint256 amount) internal { CompatibleERC20(token).transfer(to, amount); require(previousReturnValue(), "transfer failed"); } /// @notice Calls transferFrom on the token and reverts if the call fails. function safeTransferFrom(address token, address from, address to, uint256 amount) internal { CompatibleERC20(token).transferFrom(from, to, amount); require(previousReturnValue(), "transferFrom failed"); } /// @notice Calls approve on the token and reverts if the call fails. function safeApprove(address token, address spender, uint256 amount) internal { CompatibleERC20(token).approve(spender, amount); require(previousReturnValue(), "approve failed"); } /// @notice Calls transferFrom on the token, reverts if the call fails and /// returns the value transferred after fees. function safeTransferFromWithFees(address token, address from, address to, uint256 amount) internal returns (uint256) { uint256 balancesBefore = CompatibleERC20(token).balanceOf(to); CompatibleERC20(token).transferFrom(from, to, amount); require(previousReturnValue(), "transferFrom failed"); uint256 balancesAfter = CompatibleERC20(token).balanceOf(to); return Math.min256(amount, balancesAfter.sub(balancesBefore)); } /// @notice Checks the return value of the previous function. Returns true /// if the previous function returned 32 non-zero bytes or returned zero /// bytes. function previousReturnValue() private pure returns (bool) { uint256 returnData = 0; assembly { /* solium-disable-line security/no-inline-assembly */ // Switch on the number of bytes returned by the previous call switch returndatasize // 0 bytes: ERC20 of type (3), did not throw case 0 { returnData := 1 } // 32 bytes: ERC20 of types (1) or (2) case 32 { // Copy the return data into scratch space returndatacopy(0x0, 0x0, 32) // Load the return data into returnData returnData := mload(0x0) } // Other return size: return false default { } } return returnData != 0; } } /// @notice ERC20 interface which doesn't specify the return type for transfer, /// transferFrom and approve. interface CompatibleERC20 { // Modified to not return boolean function transfer(address to, uint256 value) external; function transferFrom(address from, address to, uint256 value) external; function approve(address spender, uint256 value) external; // Not modifier function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /// @notice The DarknodeRewardVault contract is responsible for holding fees /// for darknodes for settling orders. Fees can be withdrawn to the address of /// the darknode's operator. Fees can be in ETH or in ERC20 tokens. /// Docs: https://github.com/republicprotocol/republic-sol/blob/master/docs/02-darknode-reward-vault.md contract DarknodeRewardVault is Ownable { using SafeMath for uint256; using CompatibleERC20Functions for CompatibleERC20; string public VERSION; // Passed in as a constructor parameter. /// @notice The special address for Ether. address constant public ETHEREUM = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; DarknodeRegistry public darknodeRegistry; mapping(address => mapping(address => uint256)) public darknodeBalances; event LogDarknodeRegistryUpdated(DarknodeRegistry previousDarknodeRegistry, DarknodeRegistry nextDarknodeRegistry); /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _darknodeRegistry The DarknodeRegistry contract that is used by /// the vault to lookup Darknode owners. constructor(string _VERSION, DarknodeRegistry _darknodeRegistry) public { VERSION = _VERSION; darknodeRegistry = _darknodeRegistry; } function updateDarknodeRegistry(DarknodeRegistry _newDarknodeRegistry) public onlyOwner { emit LogDarknodeRegistryUpdated(darknodeRegistry, _newDarknodeRegistry); darknodeRegistry = _newDarknodeRegistry; } /// @notice Deposit fees into the vault for a Darknode. The Darknode /// registration is not checked (to reduce gas fees); the caller must be /// careful not to call this function for a Darknode that is not registered /// otherwise any fees deposited to that Darknode can be withdrawn by a /// malicious adversary (by registering the Darknode before the honest /// party and claiming ownership). /// /// @param _darknode The address of the Darknode that will receive the /// fees. /// @param _token The address of the ERC20 token being used to pay the fee. /// A special address is used for Ether. /// @param _value The amount of fees in the smallest unit of the token. function deposit(address _darknode, ERC20 _token, uint256 _value) public payable { uint256 receivedValue = _value; if (address(_token) == ETHEREUM) { require(msg.value == _value, "mismatched ether value"); } else { require(msg.value == 0, "unexpected ether value"); receivedValue = CompatibleERC20(_token).safeTransferFromWithFees(msg.sender, address(this), _value); } darknodeBalances[_darknode][_token] = darknodeBalances[_darknode][_token].add(receivedValue); } /// @notice Withdraw fees earned by a Darknode. The fees will be sent to /// the owner of the Darknode. If a Darknode is not registered the fees /// cannot be withdrawn. /// /// @param _darknode The address of the Darknode whose fees are being /// withdrawn. The owner of this Darknode will receive the fees. /// @param _token The address of the ERC20 token to withdraw. function withdraw(address _darknode, ERC20 _token) public { address darknodeOwner = darknodeRegistry.getDarknodeOwner(address(_darknode)); require(darknodeOwner != 0x0, "invalid darknode owner"); uint256 value = darknodeBalances[_darknode][_token]; darknodeBalances[_darknode][_token] = 0; if (address(_token) == ETHEREUM) { darknodeOwner.transfer(value); } else { CompatibleERC20(_token).safeTransfer(darknodeOwner, value); } } } /// @notice The BrokerVerifier interface defines the functions that a settlement /// layer's broker verifier contract must implement. interface BrokerVerifier { /// @notice The function signature that will be called when a trader opens /// an order. /// /// @param _trader The trader requesting the withdrawal. /// @param _signature The 65-byte signature from the broker. /// @param _orderID The 32-byte order ID. function verifyOpenSignature( address _trader, bytes _signature, bytes32 _orderID ) external returns (bool); } /// @notice The Settlement interface defines the functions that a settlement /// layer must implement. /// Docs: https://github.com/republicprotocol/republic-sol/blob/nightly/docs/05-settlement.md interface Settlement { function submitOrder( bytes _details, uint64 _settlementID, uint64 _tokens, uint256 _price, uint256 _volume, uint256 _minimumVolume ) external; function submissionGasPriceLimit() external view returns (uint256); function settle( bytes32 _buyID, bytes32 _sellID ) external; /// @notice orderStatus should return the status of the order, which should /// be: /// 0 - Order not seen before /// 1 - Order details submitted /// >1 - Order settled, or settlement no longer possible function orderStatus(bytes32 _orderID) external view returns (uint8); } /// @notice SettlementRegistry allows a Settlement layer to register the /// contracts used for match settlement and for broker signature verification. contract SettlementRegistry is Ownable { string public VERSION; // Passed in as a constructor parameter. struct SettlementDetails { bool registered; Settlement settlementContract; BrokerVerifier brokerVerifierContract; } // Settlement IDs are 64-bit unsigned numbers mapping(uint64 => SettlementDetails) public settlementDetails; // Events event LogSettlementRegistered(uint64 settlementID, Settlement settlementContract, BrokerVerifier brokerVerifierContract); event LogSettlementUpdated(uint64 settlementID, Settlement settlementContract, BrokerVerifier brokerVerifierContract); event LogSettlementDeregistered(uint64 settlementID); /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. constructor(string _VERSION) public { VERSION = _VERSION; } /// @notice Returns the settlement contract of a settlement layer. function settlementRegistration(uint64 _settlementID) external view returns (bool) { return settlementDetails[_settlementID].registered; } /// @notice Returns the settlement contract of a settlement layer. function settlementContract(uint64 _settlementID) external view returns (Settlement) { return settlementDetails[_settlementID].settlementContract; } /// @notice Returns the broker verifier contract of a settlement layer. function brokerVerifierContract(uint64 _settlementID) external view returns (BrokerVerifier) { return settlementDetails[_settlementID].brokerVerifierContract; } /// @param _settlementID A unique 64-bit settlement identifier. /// @param _settlementContract The address to use for settling matches. /// @param _brokerVerifierContract The decimals to use for verifying /// broker signatures. function registerSettlement(uint64 _settlementID, Settlement _settlementContract, BrokerVerifier _brokerVerifierContract) public onlyOwner { bool alreadyRegistered = settlementDetails[_settlementID].registered; settlementDetails[_settlementID] = SettlementDetails({ registered: true, settlementContract: _settlementContract, brokerVerifierContract: _brokerVerifierContract }); if (alreadyRegistered) { emit LogSettlementUpdated(_settlementID, _settlementContract, _brokerVerifierContract); } else { emit LogSettlementRegistered(_settlementID, _settlementContract, _brokerVerifierContract); } } /// @notice Deregisteres a settlement layer, clearing the details. /// @param _settlementID The unique 64-bit settlement identifier. function deregisterSettlement(uint64 _settlementID) external onlyOwner { require(settlementDetails[_settlementID].registered, "not registered"); delete settlementDetails[_settlementID]; emit LogSettlementDeregistered(_settlementID); } } /** * @title Eliptic curve signature operations * @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d * TODO Remove this library once solidity supports passing a signature to ecrecover. * See https://github.com/ethereum/solidity/issues/864 */ library ECRecovery { /** * @dev Recover signer address from a message by using their signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param sig bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes sig) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Check the signature length if (sig.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { // solium-disable-next-line arg-overflow return ecrecover(hash, v, r, s); } } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * and hash the result */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", hash) ); } } library Utils { /** * @notice Converts a number to its string/bytes representation * * @param _v the uint to convert */ function uintToBytes(uint256 _v) internal pure returns (bytes) { uint256 v = _v; if (v == 0) { return "0"; } uint256 digits = 0; uint256 v2 = v; while (v2 > 0) { v2 /= 10; digits += 1; } bytes memory result = new bytes(digits); for (uint256 i = 0; i < digits; i++) { result[digits - i - 1] = bytes1((v % 10) + 48); v /= 10; } return result; } /** * @notice Retrieves the address from a signature * * @param _hash the message that was signed (any length of bytes) * @param _signature the signature (65 bytes) */ function addr(bytes _hash, bytes _signature) internal pure returns (address) { bytes memory prefix = "\x19Ethereum Signed Message:\n"; bytes memory encoded = abi.encodePacked(prefix, uintToBytes(_hash.length), _hash); bytes32 prefixedHash = keccak256(encoded); return ECRecovery.recover(prefixedHash, _signature); } } /// @notice The Orderbook contract stores the state and priority of orders and /// allows the Darknodes to easily reach consensus. Eventually, this contract /// will only store a subset of order states, such as cancellation, to improve /// the throughput of orders. contract Orderbook is Ownable { string public VERSION; // Passed in as a constructor parameter. /// @notice OrderState enumerates the possible states of an order. All /// orders default to the Undefined state. enum OrderState {Undefined, Open, Confirmed, Canceled} /// @notice Order stores a subset of the public data associated with an order. struct Order { OrderState state; // State of the order address trader; // Trader that owns the order address confirmer; // Darknode that confirmed the order in a match uint64 settlementID; // The settlement that signed the order opening uint256 priority; // Logical time priority of this order uint256 blockNumber; // Block number of the most recent state change bytes32 matchedOrder; // Order confirmed in a match with this order } DarknodeRegistry public darknodeRegistry; SettlementRegistry public settlementRegistry; bytes32[] private orderbook; // Order details are exposed through directly accessing this mapping, or // through the getter functions below for each of the order's fields. mapping(bytes32 => Order) public orders; event LogFeeUpdated(uint256 previousFee, uint256 nextFee); event LogDarknodeRegistryUpdated(DarknodeRegistry previousDarknodeRegistry, DarknodeRegistry nextDarknodeRegistry); /// @notice Only allow registered dark nodes. modifier onlyDarknode(address _sender) { require(darknodeRegistry.isRegistered(address(_sender)), "must be registered darknode"); _; } /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _darknodeRegistry The address of the DarknodeRegistry contract. /// @param _settlementRegistry The address of the SettlementRegistry /// contract. constructor( string _VERSION, DarknodeRegistry _darknodeRegistry, SettlementRegistry _settlementRegistry ) public { VERSION = _VERSION; darknodeRegistry = _darknodeRegistry; settlementRegistry = _settlementRegistry; } /// @notice Allows the owner to update the address of the DarknodeRegistry /// contract. function updateDarknodeRegistry(DarknodeRegistry _newDarknodeRegistry) external onlyOwner { emit LogDarknodeRegistryUpdated(darknodeRegistry, _newDarknodeRegistry); darknodeRegistry = _newDarknodeRegistry; } /// @notice Open an order in the orderbook. The order must be in the /// Undefined state. /// /// @param _signature Signature of the message that defines the trader. The /// message is "Republic Protocol: open: {orderId}". /// @param _orderID The hash of the order. function openOrder(uint64 _settlementID, bytes _signature, bytes32 _orderID) external { require(orders[_orderID].state == OrderState.Undefined, "invalid order status"); address trader = msg.sender; // Verify the order signature require(settlementRegistry.settlementRegistration(_settlementID), "settlement not registered"); BrokerVerifier brokerVerifier = settlementRegistry.brokerVerifierContract(_settlementID); require(brokerVerifier.verifyOpenSignature(trader, _signature, _orderID), "invalid broker signature"); orders[_orderID] = Order({ state: OrderState.Open, trader: trader, confirmer: 0x0, settlementID: _settlementID, priority: orderbook.length + 1, blockNumber: block.number, matchedOrder: 0x0 }); orderbook.push(_orderID); } /// @notice Confirm an order match between orders. The confirmer must be a /// registered Darknode and the orders must be in the Open state. A /// malicious confirmation by a Darknode will result in a bond slash of the /// Darknode. /// /// @param _orderID The hash of the order. /// @param _matchedOrderID The hashes of the matching order. function confirmOrder(bytes32 _orderID, bytes32 _matchedOrderID) external onlyDarknode(msg.sender) { require(orders[_orderID].state == OrderState.Open, "invalid order status"); require(orders[_matchedOrderID].state == OrderState.Open, "invalid order status"); orders[_orderID].state = OrderState.Confirmed; orders[_orderID].confirmer = msg.sender; orders[_orderID].matchedOrder = _matchedOrderID; orders[_orderID].blockNumber = block.number; orders[_matchedOrderID].state = OrderState.Confirmed; orders[_matchedOrderID].confirmer = msg.sender; orders[_matchedOrderID].matchedOrder = _orderID; orders[_matchedOrderID].blockNumber = block.number; } /// @notice Cancel an open order in the orderbook. An order can be cancelled /// by the trader who opened the order, or by the broker verifier contract. /// This allows the settlement layer to implement their own logic for /// cancelling orders without trader interaction (e.g. to ban a trader from /// a specific darkpool, or to use multiple order-matching platforms) /// /// @param _orderID The hash of the order. function cancelOrder(bytes32 _orderID) external { require(orders[_orderID].state == OrderState.Open, "invalid order state"); // Require the msg.sender to be the trader or the broker verifier address brokerVerifier = address(settlementRegistry.brokerVerifierContract(orders[_orderID].settlementID)); require(msg.sender == orders[_orderID].trader || msg.sender == brokerVerifier, "not authorized"); orders[_orderID].state = OrderState.Canceled; orders[_orderID].blockNumber = block.number; } /// @notice returns status of the given orderID. function orderState(bytes32 _orderID) external view returns (OrderState) { return orders[_orderID].state; } /// @notice returns a list of matched orders to the given orderID. function orderMatch(bytes32 _orderID) external view returns (bytes32) { return orders[_orderID].matchedOrder; } /// @notice returns the priority of the given orderID. /// The priority is the index of the order in the orderbook. function orderPriority(bytes32 _orderID) external view returns (uint256) { return orders[_orderID].priority; } /// @notice returns the trader of the given orderID. /// Trader is the one who signs the message and does the actual trading. function orderTrader(bytes32 _orderID) external view returns (address) { return orders[_orderID].trader; } /// @notice returns the darknode address which confirms the given orderID. function orderConfirmer(bytes32 _orderID) external view returns (address) { return orders[_orderID].confirmer; } /// @notice returns the block number when the order being last modified. function orderBlockNumber(bytes32 _orderID) external view returns (uint256) { return orders[_orderID].blockNumber; } /// @notice returns the block depth of the orderId function orderDepth(bytes32 _orderID) external view returns (uint256) { if (orders[_orderID].blockNumber == 0) { return 0; } return (block.number - orders[_orderID].blockNumber); } /// @notice returns the number of orders in the orderbook function ordersCount() external view returns (uint256) { return orderbook.length; } /// @notice returns order details of the orders starting from the offset. function getOrders(uint256 _offset, uint256 _limit) external view returns (bytes32[], address[], uint8[]) { if (_offset >= orderbook.length) { return; } // If the provided limit is more than the number of orders after the offset, // decrease the limit uint256 limit = _limit; if (_offset + limit > orderbook.length) { limit = orderbook.length - _offset; } bytes32[] memory orderIDs = new bytes32[](limit); address[] memory traderAddresses = new address[](limit); uint8[] memory states = new uint8[](limit); for (uint256 i = 0; i < limit; i++) { bytes32 order = orderbook[i + _offset]; orderIDs[i] = order; traderAddresses[i] = orders[order].trader; states[i] = uint8(orders[order].state); } return (orderIDs, traderAddresses, states); } } /// @notice A library for calculating and verifying order match details library SettlementUtils { struct OrderDetails { uint64 settlementID; uint64 tokens; uint256 price; uint256 volume; uint256 minimumVolume; } /// @notice Calculates the ID of the order. /// @param details Order details that are not required for settlement /// execution. They are combined as a single byte array. /// @param order The order details required for settlement execution. function hashOrder(bytes details, OrderDetails memory order) internal pure returns (bytes32) { return keccak256( abi.encodePacked( details, order.settlementID, order.tokens, order.price, order.volume, order.minimumVolume ) ); } /// @notice Verifies that two orders match when considering the tokens, /// price, volumes / minimum volumes and settlement IDs. verifyMatchDetails is used /// my the DarknodeSlasher to verify challenges. Settlement layers may also /// use this function. /// @dev When verifying two orders for settlement, you should also: /// 1) verify the orders have been confirmed together /// 2) verify the orders' traders are distinct /// @param _buy The buy order details. /// @param _sell The sell order details. function verifyMatchDetails(OrderDetails memory _buy, OrderDetails memory _sell) internal pure returns (bool) { // Buy and sell tokens should match if (!verifyTokens(_buy.tokens, _sell.tokens)) { return false; } // Buy price should be greater than sell price if (_buy.price < _sell.price) { return false; } // // Buy volume should be greater than sell minimum volume if (_buy.volume < _sell.minimumVolume) { return false; } // Sell volume should be greater than buy minimum volume if (_sell.volume < _buy.minimumVolume) { return false; } // Require that the orders were submitted to the same settlement layer if (_buy.settlementID != _sell.settlementID) { return false; } return true; } /// @notice Verifies that two token requirements can be matched and that the /// tokens are formatted correctly. /// @param _buyTokens The buy token details. /// @param _sellToken The sell token details. function verifyTokens(uint64 _buyTokens, uint64 _sellToken) internal pure returns (bool) { return (( uint32(_buyTokens) == uint32(_sellToken >> 32)) && ( uint32(_sellToken) == uint32(_buyTokens >> 32)) && ( uint32(_buyTokens >> 32) <= uint32(_buyTokens)) ); } } /// @notice RenExTokens is a registry of tokens that can be traded on RenEx. contract RenExTokens is Ownable { string public VERSION; // Passed in as a constructor parameter. struct TokenDetails { address addr; uint8 decimals; bool registered; } // Storage mapping(uint32 => TokenDetails) public tokens; mapping(uint32 => bool) private detailsSubmitted; // Events event LogTokenRegistered(uint32 tokenCode, address tokenAddress, uint8 tokenDecimals); event LogTokenDeregistered(uint32 tokenCode); /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. constructor(string _VERSION) public { VERSION = _VERSION; } /// @notice Allows the owner to register and the details for a token. /// Once details have been submitted, they cannot be overwritten. /// To re-register the same token with different details (e.g. if the address /// has changed), a different token identifier should be used and the /// previous token identifier should be deregistered. /// If a token is not Ethereum-based, the address will be set to 0x0. /// /// @param _tokenCode A unique 32-bit token identifier. /// @param _tokenAddress The address of the token. /// @param _tokenDecimals The decimals to use for the token. function registerToken(uint32 _tokenCode, address _tokenAddress, uint8 _tokenDecimals) public onlyOwner { require(!tokens[_tokenCode].registered, "already registered"); // If a token is being re-registered, the same details must be provided. if (detailsSubmitted[_tokenCode]) { require(tokens[_tokenCode].addr == _tokenAddress, "different address"); require(tokens[_tokenCode].decimals == _tokenDecimals, "different decimals"); } else { detailsSubmitted[_tokenCode] = true; } tokens[_tokenCode] = TokenDetails({ addr: _tokenAddress, decimals: _tokenDecimals, registered: true }); emit LogTokenRegistered(_tokenCode, _tokenAddress, _tokenDecimals); } /// @notice Sets a token as being deregistered. The details are still stored /// to prevent the token from being re-registered with different details. /// /// @param _tokenCode The unique 32-bit token identifier. function deregisterToken(uint32 _tokenCode) external onlyOwner { require(tokens[_tokenCode].registered, "not registered"); tokens[_tokenCode].registered = false; emit LogTokenDeregistered(_tokenCode); } } /// @notice RenExSettlement implements the Settlement interface. It implements /// the on-chain settlement for the RenEx settlement layer, and the fee payment /// for the RenExAtomic settlement layer. contract RenExSettlement is Ownable { using SafeMath for uint256; string public VERSION; // Passed in as a constructor parameter. // This contract handles the settlements with ID 1 and 2. uint32 constant public RENEX_SETTLEMENT_ID = 1; uint32 constant public RENEX_ATOMIC_SETTLEMENT_ID = 2; // Fees in RenEx are 0.2%. To represent this as integers, it is broken into // a numerator and denominator. uint256 constant public DARKNODE_FEES_NUMERATOR = 2; uint256 constant public DARKNODE_FEES_DENOMINATOR = 1000; // Constants used in the price / volume inputs. int16 constant private PRICE_OFFSET = 12; int16 constant private VOLUME_OFFSET = 12; // Constructor parameters, updatable by the owner Orderbook public orderbookContract; RenExTokens public renExTokensContract; RenExBalances public renExBalancesContract; address public slasherAddress; uint256 public submissionGasPriceLimit; enum OrderStatus {None, Submitted, Settled, Slashed} struct TokenPair { RenExTokens.TokenDetails priorityToken; RenExTokens.TokenDetails secondaryToken; } // A uint256 tuple representing a value and an associated fee struct ValueWithFees { uint256 value; uint256 fees; } // A uint256 tuple representing a fraction struct Fraction { uint256 numerator; uint256 denominator; } // We use left and right because the tokens do not always represent the // priority and secondary tokens. struct SettlementDetails { uint256 leftVolume; uint256 rightVolume; uint256 leftTokenFee; uint256 rightTokenFee; address leftTokenAddress; address rightTokenAddress; } // Events event LogOrderbookUpdated(Orderbook previousOrderbook, Orderbook nextOrderbook); event LogRenExTokensUpdated(RenExTokens previousRenExTokens, RenExTokens nextRenExTokens); event LogRenExBalancesUpdated(RenExBalances previousRenExBalances, RenExBalances nextRenExBalances); event LogSubmissionGasPriceLimitUpdated(uint256 previousSubmissionGasPriceLimit, uint256 nextSubmissionGasPriceLimit); event LogSlasherUpdated(address previousSlasher, address nextSlasher); // Order Storage mapping(bytes32 => SettlementUtils.OrderDetails) public orderDetails; mapping(bytes32 => address) public orderSubmitter; mapping(bytes32 => OrderStatus) public orderStatus; // Match storage (match details are indexed by [buyID][sellID]) mapping(bytes32 => mapping(bytes32 => uint256)) public matchTimestamp; /// @notice Prevents a function from being called with a gas price higher /// than the specified limit. /// /// @param _gasPriceLimit The gas price upper-limit in Wei. modifier withGasPriceLimit(uint256 _gasPriceLimit) { require(tx.gasprice <= _gasPriceLimit, "gas price too high"); _; } /// @notice Restricts a function to only being called by the slasher /// address. modifier onlySlasher() { require(msg.sender == slasherAddress, "unauthorized"); _; } /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _orderbookContract The address of the Orderbook contract. /// @param _renExBalancesContract The address of the RenExBalances /// contract. /// @param _renExTokensContract The address of the RenExTokens contract. constructor( string _VERSION, Orderbook _orderbookContract, RenExTokens _renExTokensContract, RenExBalances _renExBalancesContract, address _slasherAddress, uint256 _submissionGasPriceLimit ) public { VERSION = _VERSION; orderbookContract = _orderbookContract; renExTokensContract = _renExTokensContract; renExBalancesContract = _renExBalancesContract; slasherAddress = _slasherAddress; submissionGasPriceLimit = _submissionGasPriceLimit; } /// @notice The owner of the contract can update the Orderbook address. /// @param _newOrderbookContract The address of the new Orderbook contract. function updateOrderbook(Orderbook _newOrderbookContract) external onlyOwner { emit LogOrderbookUpdated(orderbookContract, _newOrderbookContract); orderbookContract = _newOrderbookContract; } /// @notice The owner of the contract can update the RenExTokens address. /// @param _newRenExTokensContract The address of the new RenExTokens /// contract. function updateRenExTokens(RenExTokens _newRenExTokensContract) external onlyOwner { emit LogRenExTokensUpdated(renExTokensContract, _newRenExTokensContract); renExTokensContract = _newRenExTokensContract; } /// @notice The owner of the contract can update the RenExBalances address. /// @param _newRenExBalancesContract The address of the new RenExBalances /// contract. function updateRenExBalances(RenExBalances _newRenExBalancesContract) external onlyOwner { emit LogRenExBalancesUpdated(renExBalancesContract, _newRenExBalancesContract); renExBalancesContract = _newRenExBalancesContract; } /// @notice The owner of the contract can update the order submission gas /// price limit. /// @param _newSubmissionGasPriceLimit The new gas price limit. function updateSubmissionGasPriceLimit(uint256 _newSubmissionGasPriceLimit) external onlyOwner { emit LogSubmissionGasPriceLimitUpdated(submissionGasPriceLimit, _newSubmissionGasPriceLimit); submissionGasPriceLimit = _newSubmissionGasPriceLimit; } /// @notice The owner of the contract can update the slasher address. /// @param _newSlasherAddress The new slasher address. function updateSlasher(address _newSlasherAddress) external onlyOwner { emit LogSlasherUpdated(slasherAddress, _newSlasherAddress); slasherAddress = _newSlasherAddress; } /// @notice Stores the details of an order. /// /// @param _prefix The miscellaneous details of the order required for /// calculating the order id. /// @param _settlementID The settlement identifier. /// @param _tokens The encoding of the token pair (buy token is encoded as /// the first 32 bytes and sell token is encoded as the last 32 /// bytes). /// @param _price The price of the order. Interpreted as the cost for 1 /// standard unit of the non-priority token, in 1e12 (i.e. /// PRICE_OFFSET) units of the priority token). /// @param _volume The volume of the order. Interpreted as the maximum /// number of 1e-12 (i.e. VOLUME_OFFSET) units of the non-priority /// token that can be traded by this order. /// @param _minimumVolume The minimum volume the trader is willing to /// accept. Encoded the same as the volume. function submitOrder( bytes _prefix, uint64 _settlementID, uint64 _tokens, uint256 _price, uint256 _volume, uint256 _minimumVolume ) external withGasPriceLimit(submissionGasPriceLimit) { SettlementUtils.OrderDetails memory order = SettlementUtils.OrderDetails({ settlementID: _settlementID, tokens: _tokens, price: _price, volume: _volume, minimumVolume: _minimumVolume }); bytes32 orderID = SettlementUtils.hashOrder(_prefix, order); require(orderStatus[orderID] == OrderStatus.None, "order already submitted"); require(orderbookContract.orderState(orderID) == Orderbook.OrderState.Confirmed, "unconfirmed order"); orderSubmitter[orderID] = msg.sender; orderStatus[orderID] = OrderStatus.Submitted; orderDetails[orderID] = order; } /// @notice Settles two orders that are matched. `submitOrder` must have been /// called for each order before this function is called. /// /// @param _buyID The 32 byte ID of the buy order. /// @param _sellID The 32 byte ID of the sell order. function settle(bytes32 _buyID, bytes32 _sellID) external { require(orderStatus[_buyID] == OrderStatus.Submitted, "invalid buy status"); require(orderStatus[_sellID] == OrderStatus.Submitted, "invalid sell status"); // Check the settlement ID (only have to check for one, since // `verifyMatchDetails` checks that they are the same) require( orderDetails[_buyID].settlementID == RENEX_ATOMIC_SETTLEMENT_ID || orderDetails[_buyID].settlementID == RENEX_SETTLEMENT_ID, "invalid settlement id" ); // Verify that the two order details are compatible. require(SettlementUtils.verifyMatchDetails(orderDetails[_buyID], orderDetails[_sellID]), "incompatible orders"); // Verify that the two orders have been confirmed to one another. require(orderbookContract.orderMatch(_buyID) == _sellID, "unconfirmed orders"); // Retrieve token details. TokenPair memory tokens = getTokenDetails(orderDetails[_buyID].tokens); // Require that the tokens have been registered. require(tokens.priorityToken.registered, "unregistered priority token"); require(tokens.secondaryToken.registered, "unregistered secondary token"); address buyer = orderbookContract.orderTrader(_buyID); address seller = orderbookContract.orderTrader(_sellID); require(buyer != seller, "orders from same trader"); execute(_buyID, _sellID, buyer, seller, tokens); /* solium-disable-next-line security/no-block-members */ matchTimestamp[_buyID][_sellID] = now; // Store that the orders have been settled. orderStatus[_buyID] = OrderStatus.Settled; orderStatus[_sellID] = OrderStatus.Settled; } /// @notice Slashes the bond of a guilty trader. This is called when an /// atomic swap is not executed successfully. /// To open an atomic order, a trader must have a balance equivalent to /// 0.6% of the trade in the Ethereum-based token. 0.2% is always paid in /// darknode fees when the order is matched. If the remaining amount is /// is slashed, it is distributed as follows: /// 1) 0.2% goes to the other trader, covering their fee /// 2) 0.2% goes to the slasher address /// Only one order in a match can be slashed. /// /// @param _guiltyOrderID The 32 byte ID of the order of the guilty trader. function slash(bytes32 _guiltyOrderID) external onlySlasher { require(orderDetails[_guiltyOrderID].settlementID == RENEX_ATOMIC_SETTLEMENT_ID, "slashing non-atomic trade"); bytes32 innocentOrderID = orderbookContract.orderMatch(_guiltyOrderID); require(orderStatus[_guiltyOrderID] == OrderStatus.Settled, "invalid order status"); require(orderStatus[innocentOrderID] == OrderStatus.Settled, "invalid order status"); orderStatus[_guiltyOrderID] = OrderStatus.Slashed; (bytes32 buyID, bytes32 sellID) = isBuyOrder(_guiltyOrderID) ? (_guiltyOrderID, innocentOrderID) : (innocentOrderID, _guiltyOrderID); TokenPair memory tokens = getTokenDetails(orderDetails[buyID].tokens); SettlementDetails memory settlementDetails = calculateAtomicFees(buyID, sellID, tokens); // Transfer the fee amount to the other trader renExBalancesContract.transferBalanceWithFee( orderbookContract.orderTrader(_guiltyOrderID), orderbookContract.orderTrader(innocentOrderID), settlementDetails.leftTokenAddress, settlementDetails.leftTokenFee, 0, 0x0 ); // Transfer the fee amount to the slasher renExBalancesContract.transferBalanceWithFee( orderbookContract.orderTrader(_guiltyOrderID), slasherAddress, settlementDetails.leftTokenAddress, settlementDetails.leftTokenFee, 0, 0x0 ); } /// @notice Retrieves the settlement details of an order. /// For atomic swaps, it returns the full volumes, not the settled fees. /// /// @param _orderID The order to lookup the details of. Can be the ID of a /// buy or a sell order. /// @return [ /// a boolean representing whether or not the order has been settled, /// a boolean representing whether or not the order is a buy /// the 32-byte order ID of the matched order /// the volume of the priority token, /// the volume of the secondary token, /// the fee paid in the priority token, /// the fee paid in the secondary token, /// the token code of the priority token, /// the token code of the secondary token /// ] function getMatchDetails(bytes32 _orderID) external view returns ( bool settled, bool orderIsBuy, bytes32 matchedID, uint256 priorityVolume, uint256 secondaryVolume, uint256 priorityFee, uint256 secondaryFee, uint32 priorityToken, uint32 secondaryToken ) { matchedID = orderbookContract.orderMatch(_orderID); orderIsBuy = isBuyOrder(_orderID); (bytes32 buyID, bytes32 sellID) = orderIsBuy ? (_orderID, matchedID) : (matchedID, _orderID); SettlementDetails memory settlementDetails = calculateSettlementDetails( buyID, sellID, getTokenDetails(orderDetails[buyID].tokens) ); return ( orderStatus[_orderID] == OrderStatus.Settled || orderStatus[_orderID] == OrderStatus.Slashed, orderIsBuy, matchedID, settlementDetails.leftVolume, settlementDetails.rightVolume, settlementDetails.leftTokenFee, settlementDetails.rightTokenFee, uint32(orderDetails[buyID].tokens >> 32), uint32(orderDetails[buyID].tokens) ); } /// @notice Exposes the hashOrder function for computing a hash of an /// order's details. An order hash is used as its ID. See `submitOrder` /// for the parameter descriptions. /// /// @return The 32-byte hash of the order. function hashOrder( bytes _prefix, uint64 _settlementID, uint64 _tokens, uint256 _price, uint256 _volume, uint256 _minimumVolume ) external pure returns (bytes32) { return SettlementUtils.hashOrder(_prefix, SettlementUtils.OrderDetails({ settlementID: _settlementID, tokens: _tokens, price: _price, volume: _volume, minimumVolume: _minimumVolume })); } /// @notice Called by `settle`, executes the settlement for a RenEx order /// or distributes the fees for a RenExAtomic swap. /// /// @param _buyID The 32 byte ID of the buy order. /// @param _sellID The 32 byte ID of the sell order. /// @param _buyer The address of the buy trader. /// @param _seller The address of the sell trader. /// @param _tokens The details of the priority and secondary tokens. function execute( bytes32 _buyID, bytes32 _sellID, address _buyer, address _seller, TokenPair memory _tokens ) private { // Calculate the fees for atomic swaps, and the settlement details // otherwise. SettlementDetails memory settlementDetails = (orderDetails[_buyID].settlementID == RENEX_ATOMIC_SETTLEMENT_ID) ? settlementDetails = calculateAtomicFees(_buyID, _sellID, _tokens) : settlementDetails = calculateSettlementDetails(_buyID, _sellID, _tokens); // Transfer priority token value renExBalancesContract.transferBalanceWithFee( _buyer, _seller, settlementDetails.leftTokenAddress, settlementDetails.leftVolume, settlementDetails.leftTokenFee, orderSubmitter[_buyID] ); // Transfer secondary token value renExBalancesContract.transferBalanceWithFee( _seller, _buyer, settlementDetails.rightTokenAddress, settlementDetails.rightVolume, settlementDetails.rightTokenFee, orderSubmitter[_sellID] ); } /// @notice Calculates the details required to execute two matched orders. /// /// @param _buyID The 32 byte ID of the buy order. /// @param _sellID The 32 byte ID of the sell order. /// @param _tokens The details of the priority and secondary tokens. /// @return A struct containing the settlement details. function calculateSettlementDetails( bytes32 _buyID, bytes32 _sellID, TokenPair memory _tokens ) private view returns (SettlementDetails memory) { // Calculate the mid-price (using numerator and denominator to not loose // precision). Fraction memory midPrice = Fraction(orderDetails[_buyID].price + orderDetails[_sellID].price, 2); // Calculate the lower of the two max volumes of each trader uint256 commonVolume = Math.min256(orderDetails[_buyID].volume, orderDetails[_sellID].volume); uint256 priorityTokenVolume = joinFraction( commonVolume.mul(midPrice.numerator), midPrice.denominator, int16(_tokens.priorityToken.decimals) - PRICE_OFFSET - VOLUME_OFFSET ); uint256 secondaryTokenVolume = joinFraction( commonVolume, 1, int16(_tokens.secondaryToken.decimals) - VOLUME_OFFSET ); // Calculate darknode fees ValueWithFees memory priorityVwF = subtractDarknodeFee(priorityTokenVolume); ValueWithFees memory secondaryVwF = subtractDarknodeFee(secondaryTokenVolume); return SettlementDetails({ leftVolume: priorityVwF.value, rightVolume: secondaryVwF.value, leftTokenFee: priorityVwF.fees, rightTokenFee: secondaryVwF.fees, leftTokenAddress: _tokens.priorityToken.addr, rightTokenAddress: _tokens.secondaryToken.addr }); } /// @notice Calculates the fees to be transferred for an atomic swap. /// /// @param _buyID The 32 byte ID of the buy order. /// @param _sellID The 32 byte ID of the sell order. /// @param _tokens The details of the priority and secondary tokens. /// @return A struct containing the fee details. function calculateAtomicFees( bytes32 _buyID, bytes32 _sellID, TokenPair memory _tokens ) private view returns (SettlementDetails memory) { // Calculate the mid-price (using numerator and denominator to not loose // precision). Fraction memory midPrice = Fraction(orderDetails[_buyID].price + orderDetails[_sellID].price, 2); // Calculate the lower of the two max volumes of each trader uint256 commonVolume = Math.min256(orderDetails[_buyID].volume, orderDetails[_sellID].volume); if (isEthereumBased(_tokens.secondaryToken.addr)) { uint256 secondaryTokenVolume = joinFraction( commonVolume, 1, int16(_tokens.secondaryToken.decimals) - VOLUME_OFFSET ); // Calculate darknode fees ValueWithFees memory secondaryVwF = subtractDarknodeFee(secondaryTokenVolume); return SettlementDetails({ leftVolume: 0, rightVolume: 0, leftTokenFee: secondaryVwF.fees, rightTokenFee: secondaryVwF.fees, leftTokenAddress: _tokens.secondaryToken.addr, rightTokenAddress: _tokens.secondaryToken.addr }); } else if (isEthereumBased(_tokens.priorityToken.addr)) { uint256 priorityTokenVolume = joinFraction( commonVolume.mul(midPrice.numerator), midPrice.denominator, int16(_tokens.priorityToken.decimals) - PRICE_OFFSET - VOLUME_OFFSET ); // Calculate darknode fees ValueWithFees memory priorityVwF = subtractDarknodeFee(priorityTokenVolume); return SettlementDetails({ leftVolume: 0, rightVolume: 0, leftTokenFee: priorityVwF.fees, rightTokenFee: priorityVwF.fees, leftTokenAddress: _tokens.priorityToken.addr, rightTokenAddress: _tokens.priorityToken.addr }); } else { // Currently, at least one token must be Ethereum-based. // This will be implemented in the future. revert("non-eth atomic swaps are not supported"); } } /// @notice Order parity is set by the order tokens are listed. This returns /// whether an order is a buy or a sell. /// @return true if _orderID is a buy order. function isBuyOrder(bytes32 _orderID) private view returns (bool) { uint64 tokens = orderDetails[_orderID].tokens; uint32 firstToken = uint32(tokens >> 32); uint32 secondaryToken = uint32(tokens); return (firstToken < secondaryToken); } /// @return (value - fee, fee) where fee is 0.2% of value function subtractDarknodeFee(uint256 _value) private pure returns (ValueWithFees memory) { uint256 newValue = (_value * (DARKNODE_FEES_DENOMINATOR - DARKNODE_FEES_NUMERATOR)) / DARKNODE_FEES_DENOMINATOR; return ValueWithFees(newValue, _value - newValue); } /// @notice Gets the order details of the priority and secondary token from /// the RenExTokens contract and returns them as a single struct. /// /// @param _tokens The 64-bit combined token identifiers. /// @return A TokenPair struct containing two TokenDetails structs. function getTokenDetails(uint64 _tokens) private view returns (TokenPair memory) { ( address priorityAddress, uint8 priorityDecimals, bool priorityRegistered ) = renExTokensContract.tokens(uint32(_tokens >> 32)); ( address secondaryAddress, uint8 secondaryDecimals, bool secondaryRegistered ) = renExTokensContract.tokens(uint32(_tokens)); return TokenPair({ priorityToken: RenExTokens.TokenDetails(priorityAddress, priorityDecimals, priorityRegistered), secondaryToken: RenExTokens.TokenDetails(secondaryAddress, secondaryDecimals, secondaryRegistered) }); } /// @return true if _tokenAddress is 0x0, representing a token that is not /// on Ethereum function isEthereumBased(address _tokenAddress) private pure returns (bool) { return (_tokenAddress != address(0x0)); } /// @notice Computes (_numerator / _denominator) * 10 ** _scale function joinFraction(uint256 _numerator, uint256 _denominator, int16 _scale) private pure returns (uint256) { if (_scale >= 0) { // Check that (10**_scale) doesn't overflow assert(_scale <= 77); // log10(2**256) = 77.06 return _numerator.mul(10 ** uint256(_scale)) / _denominator; } else { /// @dev If _scale is less than -77, 10**-_scale would overflow. // For now, -_scale > -24 (when a token has 0 decimals and // VOLUME_OFFSET and PRICE_OFFSET are each 12). It is unlikely these // will be increased to add to more than 77. // assert((-_scale) <= 77); // log10(2**256) = 77.06 return (_numerator / _denominator) / 10 ** uint256(-_scale); } } } /// @notice RenExBrokerVerifier implements the BrokerVerifier contract, /// verifying broker signatures for order opening and fund withdrawal. contract RenExBrokerVerifier is Ownable { string public VERSION; // Passed in as a constructor parameter. // Events event LogBalancesContractUpdated(address previousBalancesContract, address nextBalancesContract); event LogBrokerRegistered(address broker); event LogBrokerDeregistered(address broker); // Storage mapping(address => bool) public brokers; mapping(address => uint256) public traderNonces; address public balancesContract; modifier onlyBalancesContract() { require(msg.sender == balancesContract, "not authorized"); _; } /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. constructor(string _VERSION) public { VERSION = _VERSION; } /// @notice Allows the owner of the contract to update the address of the /// RenExBalances contract. /// /// @param _balancesContract The address of the new balances contract function updateBalancesContract(address _balancesContract) external onlyOwner { emit LogBalancesContractUpdated(balancesContract, _balancesContract); balancesContract = _balancesContract; } /// @notice Approved an address to sign order-opening and withdrawals. /// @param _broker The address of the broker. function registerBroker(address _broker) external onlyOwner { require(!brokers[_broker], "already registered"); brokers[_broker] = true; emit LogBrokerRegistered(_broker); } /// @notice Reverts the a broker's registration. /// @param _broker The address of the broker. function deregisterBroker(address _broker) external onlyOwner { require(brokers[_broker], "not registered"); brokers[_broker] = false; emit LogBrokerDeregistered(_broker); } /// @notice Verifies a broker's signature for an order opening. /// The data signed by the broker is a prefixed message and the order ID. /// /// @param _trader The trader requesting the withdrawal. /// @param _signature The 65-byte signature from the broker. /// @param _orderID The 32-byte order ID. /// @return True if the signature is valid, false otherwise. function verifyOpenSignature( address _trader, bytes _signature, bytes32 _orderID ) external view returns (bool) { bytes memory data = abi.encodePacked("Republic Protocol: open: ", _trader, _orderID); address signer = Utils.addr(data, _signature); return (brokers[signer] == true); } /// @notice Verifies a broker's signature for a trader withdrawal. /// The data signed by the broker is a prefixed message, the trader address /// and a 256-bit trader nonce, which is incremented every time a valid /// signature is checked. /// /// @param _trader The trader requesting the withdrawal. /// @param _signature 65-byte signature from the broker. /// @return True if the signature is valid, false otherwise. function verifyWithdrawSignature( address _trader, bytes _signature ) external onlyBalancesContract returns (bool) { bytes memory data = abi.encodePacked("Republic Protocol: withdraw: ", _trader, traderNonces[_trader]); address signer = Utils.addr(data, _signature); if (brokers[signer]) { traderNonces[_trader] += 1; return true; } return false; } } /// @notice RenExBalances is responsible for holding RenEx trader funds. contract RenExBalances is Ownable { using SafeMath for uint256; using CompatibleERC20Functions for CompatibleERC20; string public VERSION; // Passed in as a constructor parameter. RenExSettlement public settlementContract; RenExBrokerVerifier public brokerVerifierContract; DarknodeRewardVault public rewardVaultContract; /// @dev Should match the address in the DarknodeRewardVault address constant public ETHEREUM = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // Delay between a trader calling `withdrawSignal` and being able to call // `withdraw` without a broker signature. uint256 constant public SIGNAL_DELAY = 48 hours; // Events event LogBalanceDecreased(address trader, ERC20 token, uint256 value); event LogBalanceIncreased(address trader, ERC20 token, uint256 value); event LogRenExSettlementContractUpdated(address previousRenExSettlementContract, address newRenExSettlementContract); event LogRewardVaultContractUpdated(address previousRewardVaultContract, address newRewardVaultContract); event LogBrokerVerifierContractUpdated(address previousBrokerVerifierContract, address newBrokerVerifierContract); // Storage mapping(address => mapping(address => uint256)) public traderBalances; mapping(address => mapping(address => uint256)) public traderWithdrawalSignals; /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _rewardVaultContract The address of the RewardVault contract. constructor( string _VERSION, DarknodeRewardVault _rewardVaultContract, RenExBrokerVerifier _brokerVerifierContract ) public { VERSION = _VERSION; rewardVaultContract = _rewardVaultContract; brokerVerifierContract = _brokerVerifierContract; } /// @notice Restricts a function to only being called by the RenExSettlement /// contract. modifier onlyRenExSettlementContract() { require(msg.sender == address(settlementContract), "not authorized"); _; } /// @notice Restricts trader withdrawing to be called if a signature from a /// RenEx broker is provided, or if a certain amount of time has passed /// since a trader has called `signalBackupWithdraw`. /// @dev If the trader is withdrawing after calling `signalBackupWithdraw`, /// this will reset the time to zero, writing to storage. modifier withBrokerSignatureOrSignal(address _token, bytes _signature) { address trader = msg.sender; // If a signature has been provided, verify it - otherwise, verify that // the user has signalled the withdraw if (_signature.length > 0) { require (brokerVerifierContract.verifyWithdrawSignature(trader, _signature), "invalid signature"); } else { require(traderWithdrawalSignals[trader][_token] != 0, "not signalled"); /* solium-disable-next-line security/no-block-members */ require((now - traderWithdrawalSignals[trader][_token]) > SIGNAL_DELAY, "signal time remaining"); traderWithdrawalSignals[trader][_token] = 0; } _; } /// @notice Allows the owner of the contract to update the address of the /// RenExSettlement contract. /// /// @param _newSettlementContract the address of the new settlement contract function updateRenExSettlementContract(RenExSettlement _newSettlementContract) external onlyOwner { emit LogRenExSettlementContractUpdated(settlementContract, _newSettlementContract); settlementContract = _newSettlementContract; } /// @notice Allows the owner of the contract to update the address of the /// DarknodeRewardVault contract. /// /// @param _newRewardVaultContract the address of the new reward vault contract function updateRewardVaultContract(DarknodeRewardVault _newRewardVaultContract) external onlyOwner { emit LogRewardVaultContractUpdated(rewardVaultContract, _newRewardVaultContract); rewardVaultContract = _newRewardVaultContract; } /// @notice Allows the owner of the contract to update the address of the /// RenExBrokerVerifier contract. /// /// @param _newBrokerVerifierContract the address of the new broker verifier contract function updateBrokerVerifierContract(RenExBrokerVerifier _newBrokerVerifierContract) external onlyOwner { emit LogBrokerVerifierContractUpdated(brokerVerifierContract, _newBrokerVerifierContract); brokerVerifierContract = _newBrokerVerifierContract; } /// @notice Transfer a token value from one trader to another, transferring /// a fee to the RewardVault. Can only be called by the RenExSettlement /// contract. /// /// @param _traderFrom The address of the trader to decrement the balance of. /// @param _traderTo The address of the trader to increment the balance of. /// @param _token The token's address. /// @param _value The number of tokens to decrement the balance by (in the /// token's smallest unit). /// @param _fee The fee amount to forward on to the RewardVault. /// @param _feePayee The recipient of the fee. function transferBalanceWithFee(address _traderFrom, address _traderTo, address _token, uint256 _value, uint256 _fee, address _feePayee) external onlyRenExSettlementContract { require(traderBalances[_traderFrom][_token] >= _fee, "insufficient funds for fee"); if (address(_token) == ETHEREUM) { rewardVaultContract.deposit.value(_fee)(_feePayee, ERC20(_token), _fee); } else { CompatibleERC20(_token).safeApprove(rewardVaultContract, _fee); rewardVaultContract.deposit(_feePayee, ERC20(_token), _fee); } privateDecrementBalance(_traderFrom, ERC20(_token), _value + _fee); if (_value > 0) { privateIncrementBalance(_traderTo, ERC20(_token), _value); } } /// @notice Deposits ETH or an ERC20 token into the contract. /// /// @param _token The token's address (must be a registered token). /// @param _value The amount to deposit in the token's smallest unit. function deposit(ERC20 _token, uint256 _value) external payable { address trader = msg.sender; uint256 receivedValue = _value; if (address(_token) == ETHEREUM) { require(msg.value == _value, "mismatched value parameter and tx value"); } else { require(msg.value == 0, "unexpected ether transfer"); receivedValue = CompatibleERC20(_token).safeTransferFromWithFees(trader, this, _value); } privateIncrementBalance(trader, _token, receivedValue); } /// @notice Withdraws ETH or an ERC20 token from the contract. A broker /// signature is required to guarantee that the trader has a sufficient /// balance after accounting for open orders. As a trustless backup, /// traders can withdraw 48 hours after calling `signalBackupWithdraw`. /// /// @param _token The token's address. /// @param _value The amount to withdraw in the token's smallest unit. /// @param _signature The broker signature function withdraw(ERC20 _token, uint256 _value, bytes _signature) external withBrokerSignatureOrSignal(_token, _signature) { address trader = msg.sender; privateDecrementBalance(trader, _token, _value); if (address(_token) == ETHEREUM) { trader.transfer(_value); } else { CompatibleERC20(_token).safeTransfer(trader, _value); } } /// @notice A trader can withdraw without needing a broker signature if they /// first call `signalBackupWithdraw` for the token they want to withdraw. /// The trader can only withdraw the particular token once for each call to /// this function. Traders can signal the intent to withdraw multiple /// tokens. /// Once this function is called, brokers will not sign order-opens for the /// trader until the trader has withdrawn, guaranteeing that they won't have /// orders open for the particular token. function signalBackupWithdraw(address _token) external { /* solium-disable-next-line security/no-block-members */ traderWithdrawalSignals[msg.sender][_token] = now; } function privateIncrementBalance(address _trader, ERC20 _token, uint256 _value) private { traderBalances[_trader][_token] = traderBalances[_trader][_token].add(_value); emit LogBalanceIncreased(_trader, _token, _value); } function privateDecrementBalance(address _trader, ERC20 _token, uint256 _value) private { require(traderBalances[_trader][_token] >= _value, "insufficient funds"); traderBalances[_trader][_token] = traderBalances[_trader][_token].sub(_value); emit LogBalanceDecreased(_trader, _token, _value); } }
@notice The Settlement interface defines the functions that a settlement layer must implement. Docs: https://github.com/republicprotocol/republic-sol/blob/nightly/docs/05-settlement.md
interface Settlement { function submitOrder( bytes _details, uint64 _settlementID, uint64 _tokens, uint256 _price, uint256 _volume, uint256 _minimumVolume ) external; function submissionGasPriceLimit() external view returns (uint256); function settle( bytes32 _buyID, bytes32 _sellID ) external; function orderStatus(bytes32 _orderID) external view returns (uint8); } }
1,044,440
[ 1, 1986, 1000, 88, 806, 1560, 11164, 326, 4186, 716, 279, 26319, 806, 3018, 1297, 2348, 18, 3521, 87, 30, 2333, 2207, 6662, 18, 832, 19, 266, 482, 8373, 19, 266, 482, 17, 18281, 19, 10721, 19, 18840, 715, 19, 8532, 19, 6260, 17, 542, 88, 806, 18, 1264, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5831, 1000, 88, 806, 288, 203, 565, 445, 4879, 2448, 12, 203, 3639, 1731, 389, 6395, 16, 203, 3639, 2254, 1105, 389, 542, 88, 806, 734, 16, 203, 3639, 2254, 1105, 389, 7860, 16, 203, 3639, 2254, 5034, 389, 8694, 16, 203, 3639, 2254, 5034, 389, 9491, 16, 203, 3639, 2254, 5034, 389, 15903, 4545, 203, 565, 262, 3903, 31, 203, 203, 565, 445, 8515, 27998, 5147, 3039, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 444, 5929, 12, 203, 3639, 1731, 1578, 389, 70, 9835, 734, 16, 203, 3639, 1731, 1578, 389, 87, 1165, 734, 203, 565, 262, 3903, 31, 203, 203, 565, 445, 1353, 1482, 12, 3890, 1578, 389, 1019, 734, 13, 3903, 1476, 1135, 261, 11890, 28, 1769, 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 ]
./full_match/41/0xfFAb4c8696a356848E75e066a314b474157E4f82/sources/home/ubuntu/wolfswap/pancake-farm/contracts/MasterChef.sol
Withdraw WOLF tokens from STAKING.
function leaveStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(0); uint256 pending = user.amount.mul(pool.accWolfPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeWolfTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accWolfPerShare).div(1e12); syrup.burn(msg.sender, _amount); emit Withdraw(msg.sender, 0, _amount); }
16,372,687
[ 1, 1190, 9446, 678, 1741, 42, 2430, 628, 2347, 14607, 1360, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 8851, 510, 6159, 12, 11890, 5034, 389, 8949, 13, 1071, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 20, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 20, 6362, 3576, 18, 15330, 15533, 203, 3639, 2583, 12, 1355, 18, 8949, 1545, 389, 8949, 16, 315, 1918, 9446, 30, 486, 7494, 8863, 203, 3639, 1089, 2864, 12, 20, 1769, 203, 3639, 2254, 5034, 4634, 273, 729, 18, 8949, 18, 16411, 12, 6011, 18, 8981, 59, 355, 74, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 2934, 1717, 12, 1355, 18, 266, 2913, 758, 23602, 1769, 203, 3639, 309, 12, 9561, 405, 374, 13, 288, 203, 5411, 4183, 59, 355, 74, 5912, 12, 3576, 18, 15330, 16, 4634, 1769, 203, 3639, 289, 203, 3639, 309, 24899, 8949, 405, 374, 13, 288, 203, 5411, 729, 18, 8949, 273, 729, 18, 8949, 18, 1717, 24899, 8949, 1769, 203, 5411, 2845, 18, 9953, 1345, 18, 4626, 5912, 12, 2867, 12, 3576, 18, 15330, 3631, 389, 8949, 1769, 203, 3639, 289, 203, 3639, 729, 18, 266, 2913, 758, 23602, 273, 729, 18, 8949, 18, 16411, 12, 6011, 18, 8981, 59, 355, 74, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 1769, 203, 203, 3639, 1393, 86, 416, 18, 70, 321, 12, 3576, 18, 15330, 16, 389, 8949, 1769, 203, 3639, 3626, 3423, 9446, 12, 3576, 18, 15330, 16, 374, 16, 389, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * Copyright (C) 2017-2018 Hashfuture Inc. All rights reserved. */ pragma solidity ^0.4.24; library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; assert(c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { return a / b; } 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); return c; } } contract ownable { address public owner; function ownable() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } /** * The signature mechanism to enhance the credibility of the token. * The sign process is asychronous. * After the creation of the contract, one who verifies the contract and * is willing to guarantee for it can sign the contract address. */ contract verifiable { struct Signature { uint8 v; bytes32 r; bytes32 s; } /** * signatures * Used to verify that if the contract is protected * By hashworld or other publicly verifiable organizations */ mapping(address => Signature) public signatures; /** * sign Token */ function sign(uint8 v, bytes32 r, bytes32 s) public { signatures[msg.sender] = Signature(v, r, s); } /** * To verify whether a specific signer has signed this contract's address * @param signer address to verify */ function verify(address signer) public constant returns(bool) { bytes32 hash = keccak256(abi.encodePacked(address(this))); Signature storage sig = signatures[signer]; return ecrecover(hash, sig.v, sig.r, sig.s) == signer; } } contract AssetHashToken is ownable, verifiable{ using SafeMath for uint; //Asset Struct struct data { // link URL of the original information for storing data; null means undisclosed string link; // The hash type of the original data, such as SHA-256 string hashType; // Hash value of the agreed content. string hashValue; } data public assetFile; data public legalFile; //The token id uint id; //The validity of the contract bool public isValid; //The splitting status of the asset //Set to true if the asset has been splitted to small tokens bool public isSplitted; // The tradeable status of asset // Leave (together with assetPrice) for auto buy and sell functionality (with Ether). bool public isTradable; /** * The price of asset * if the contract is valid and tradeable, * others can get asset by transfer assetPrice ETH to contract */ uint public assetPrice; uint public pledgePrice; //Some addtional notes string public remark1; string public remark2; // Digital Asset Url string private digitalAsset; mapping (address => uint) pendingWithdrawals; /** * The asset update events */ event TokenUpdateEvent ( uint id, bool isValid, bool isTradable, address owner, uint assetPrice, string assetFileLink, string legalFileLink ); modifier onlyUnsplitted { require(isSplitted == false, "This function can be called only under unsplitted status"); _; } modifier onlyValid { require(isValid == true, "Contract is invaild!"); _; } /** * constructor * @param _id Token id * @param _owner initial owner * @param _assetPrice The price of asset * @param _assetFileUrl The url of asset file * @param _assetFileHashType The hash type of asset file * @param _assetFileHashValue The hash value of asset file * @param _legalFileUrl The url of legal file * @param _legalFileHashType The hash type of legal file * @param _legalFileHashValue The hash value of legal file */ constructor( uint _id, address _owner, uint _assetPrice, uint _pledgePrice, string _assetFileUrl, string _assetFileHashType, string _assetFileHashValue, string _legalFileUrl, string _legalFileHashType, string _legalFileHashValue, string _digitalAsset ) public { id = _id; owner = _owner; assetPrice = _assetPrice; pledgePrice = _pledgePrice; digitalAsset = _digitalAsset; initAssetFile( _assetFileUrl, _assetFileHashType, _assetFileHashValue, _legalFileUrl, _legalFileHashType, _legalFileHashValue); isValid = true; isSplitted = false; isTradable = false; } /** * Initialize asset file and legal file * @param _assetFileUrl The url of asset file * @param _assetFileHashType The hash type of asset file * @param _assetFileHashValue The hash value of asset file * @param _legalFileUrl The url of legal file * @param _legalFileHashType The hash type of legal file * @param _legalFileHashValue The hash value of legal file */ function initAssetFile( string _assetFileUrl, string _assetFileHashType, string _assetFileHashValue, string _legalFileUrl, string _legalFileHashType, string _legalFileHashValue ) internal { assetFile = data( _assetFileUrl, _assetFileHashType, _assetFileHashValue); legalFile = data( _legalFileUrl, _legalFileHashType, _legalFileHashValue); } /** * Get base asset info */ function getAssetBaseInfo() public view onlyValid returns ( uint _id, uint _assetPrice, bool _isTradable, string _remark1, string _remark2 ) { _id = id; _assetPrice = assetPrice; _isTradable = isTradable; _remark1 = remark1; _remark2 = remark2; } /** * set the price of asset * @param newAssetPrice new price of asset * Only can be called by owner */ function setassetPrice(uint newAssetPrice) public onlyOwner onlyValid onlyUnsplitted { assetPrice = newAssetPrice; emit TokenUpdateEvent ( id, isValid, isTradable, owner, assetPrice, assetFile.link, legalFile.link ); } /** * set the tradeable status of asset * @param status status of isTradable * Only can be called by owner */ function setTradeable(bool status) public onlyOwner onlyValid onlyUnsplitted { isTradable = status; emit TokenUpdateEvent ( id, isValid, isTradable, owner, assetPrice, assetFile.link, legalFile.link ); } /** * set the remark1 * @param content new content of remark1 * Only can be called by owner */ function setRemark1(string content) public onlyOwner onlyValid onlyUnsplitted { remark1 = content; } /** * set the remark2 * @param content new content of remark2 * Only can be called by owner */ function setRemark2(string content) public onlyOwner onlyValid onlyUnsplitted { remark2 = content; } /** * get the digitalAsset * Only can be called by owner */ function getDigitalAsset() public view onlyOwner onlyValid onlyUnsplitted returns (string _digitalAsset) { _digitalAsset = digitalAsset; } /** * Modify the link of the asset file * @param url new link * Only can be called by owner */ function setAssetFileLink(string url) public onlyOwner onlyValid onlyUnsplitted { assetFile.link = url; emit TokenUpdateEvent ( id, isValid, isTradable, owner, assetPrice, assetFile.link, legalFile.link ); } /** * Modify the link of the legal file * @param url new link * Only can be called by owner */ function setLegalFileLink(string url) public onlyOwner onlyValid onlyUnsplitted { legalFile.link = url; emit TokenUpdateEvent ( id, isValid, isTradable, owner, assetPrice, assetFile.link, legalFile.link ); } /** * cancel contract * Only can be called by owner */ function cancelContract() public onlyOwner onlyValid onlyUnsplitted { isValid = false; emit TokenUpdateEvent ( id, isValid, isTradable, owner, assetPrice, assetFile.link, legalFile.link ); } /** * overwrite the transferOwnership interface in ownable. * Only can transfer when the token is not splitted into small keys. * After transfer, the token should be set in "no trading" status. */ function transferOwnership(address newowner) public onlyOwner onlyValid onlyUnsplitted { owner = newowner; isTradable = false; // set to false for new owner emit TokenUpdateEvent ( id, isValid, isTradable, owner, assetPrice, assetFile.link, legalFile.link ); } /** * Buy asset */ function buy() public payable onlyValid onlyUnsplitted { require(isTradable == true, "contract is tradeable"); require(msg.value >= assetPrice, "assetPrice not match"); address origin_owner = owner; owner = msg.sender; isTradable = false; // set to false for new owner emit TokenUpdateEvent ( id, isValid, isTradable, owner, assetPrice, assetFile.link, legalFile.link ); uint priviousBalance = pendingWithdrawals[origin_owner]; pendingWithdrawals[origin_owner] = priviousBalance.add(assetPrice); } function withdraw() public { uint amount = pendingWithdrawals[msg.sender]; // Remember to zero the pending refund before sending to prevent re-entrancy attacks pendingWithdrawals[msg.sender] = 0; msg.sender.transfer(amount); } } /** * Standard ERC 20 interface. */ contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract DividableAsset is AssetHashToken, ERC20Interface { using SafeMath for uint; ERC20Interface stableToken; string public name; string public symbol; uint8 public decimals; uint public _totalSupply; address public operator; uint collectPrice; address[] internal allowners; mapping (address => uint) public indexOfowner; mapping (address => uint) public balances; mapping (address => mapping (address => uint)) public allowed; modifier onlySplitted { require(isSplitted == true, "Splitted status required"); _; } modifier onlyOperator { require(operator == msg.sender, "Operation only permited by operator"); _; } /** * The force collect event */ event ForceCollectEvent ( uint id, uint price, address operator ); /** * The token split event */ event TokenSplitEvent ( uint id, uint supply, uint8 decim, uint price, address owner ); constructor( string _name, string _symbol, address _tokenAddress, uint _id, address _owner, uint _assetPrice, uint _pledgePrice, string _assetFileUrl, string _assetFileHashType, string _assetFileHashValue, string _legalFileUrl, string _legalFileHashType, string _legalFileHashValue, string _digitalAsset ) public AssetHashToken( _id, _owner, _assetPrice, _pledgePrice, _assetFileUrl, _assetFileHashType, _assetFileHashValue, _legalFileUrl, _legalFileHashType, _legalFileHashValue, _digitalAsset ) { name = _name; symbol = _symbol; operator = msg.sender; // TODO set to HashFuture owned address stableToken = ERC20Interface(_tokenAddress); } // ERC 20 Basic Functionality /** * Total supply */ function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } /** * Get the token balance for account `tokenOwner` */ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } /** * Returns the amount of tokens approved by the owner that can be * transferred to the spender's account */ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } /** * Transfer the balance from token owner's account to `to` account * - Owner's account must have sufficient balance to transfer * - 0 value transfers are allowed */ function transfer(address to, uint tokens) public onlySplitted returns (bool success) { require(tokens > 0); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); // ensure that each address appears only once in allowners list // so that distribute divident or force collect only pays one time if (indexOfowner[to] == 0) { allowners.push(to); indexOfowner[to] = allowners.length; } // could be removed? no if (balances[msg.sender] == 0) { uint index = indexOfowner[msg.sender].sub(1); indexOfowner[msg.sender] = 0; if (index != allowners.length.sub(1)) { allowners[index] = allowners[allowners.length.sub(1)]; indexOfowner[allowners[index]] = index.add(1); } //delete allowners[allowners.length.sub(1)]; allowners.length = allowners.length.sub(1); } emit Transfer(msg.sender, to, tokens); return true; } /** * Token owner can approve for `spender` to transferFrom(...) `tokens` * from the token owner's account */ function approve(address spender, uint tokens) public onlySplitted returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } /** * Transfer `tokens` from the `from` account to the `to` account */ function transferFrom(address from, address to, uint tokens) public onlySplitted returns (bool success) { require(tokens > 0); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); // ensure that each address appears only once in allowners list // so that distribute divident or force collect only pays one time if (indexOfowner[to] == 0) { allowners.push(to); indexOfowner[to] = allowners.length; } // could be removed? no if (balances[from] == 0) { uint index = indexOfowner[from].sub(1); indexOfowner[from] = 0; if (index != allowners.length.sub(1)) { allowners[index] = allowners[allowners.length.sub(1)]; indexOfowner[allowners[index]] = index.add(1); } //delete allowners[allowners.length.sub(1)]; allowners.length = allowners.length.sub(1); } emit Transfer(from, to, tokens); return true; } /** * * Warning: may fail when number of owners exceeds 100 due to gas limit of a block in Ethereum. */ function distributeDivident(uint amount) public { // stableToken.approve(address(this), amount) // should be called by the caller to the token contract in previous uint value = 0; uint length = allowners.length; require(stableToken.balanceOf(msg.sender) >= amount, "Insufficient balance for sender"); require(stableToken.allowance(msg.sender, address(this)) >= amount, "Insufficient allowance for contract"); for (uint i = 0; i < length; i++) { //value = amount * balances[allowners[i]] / _totalSupply; value = amount.mul(balances[allowners[i]]); value = value.div(_totalSupply); // Always use a require when doing token transfer! // Do not think it works like the transfer method for ether, // which handles failure and will throw for you. require(stableToken.transferFrom(msg.sender, allowners[i], value)); } } /** * partially distribute divident to given address list */ function partialDistributeDivident(uint amount, address[] _address) public { // stableToken.approve(address(this), amount) // should be called by the caller to the token contract in previous uint value = 0; uint length = _address.length; require(stableToken.balanceOf(msg.sender) >= amount, "Insufficient balance for sender"); require(stableToken.allowance(msg.sender, address(this)) >= amount, "Insufficient allowance for contract"); uint totalAmount = 0; for (uint j = 0; j < length; j++) { totalAmount = totalAmount.add(balances[_address[j]]); } for (uint i = 0; i < length; i++) { value = amount.mul(balances[_address[i]]); value = value.div(totalAmount); // Always use a require when doing token transfer! // Do not think it works like the transfer method for ether, // which handles failure and will throw for you. require(stableToken.transferFrom(msg.sender, _address[i], value)); } } /** * Collect all small keys in batches. * Anyone can force collect all keys if he provides with sufficient stable tokens. * However, due to the gas limitation of Ethereum, he can not collect all keys * with only one call. Hence an agent that can be trusted is need. * The operator is such an agent who will first receive a request to collect all keys, * and then collect them with the stable tokens provided by the claimer. * @param _address each address in the array means a target address to be collected from. */ function collectAllForce(address[] _address) public onlyOperator { // stableToken.approve(address(this), amount) // should be called by the caller to the token contract in previous uint value = 0; uint length = _address.length; uint total_amount = 0; for (uint j = 0; j < length; j++) { if (indexOfowner[_address[j]] == 0) { continue; } total_amount = total_amount.add(collectPrice.mul(balances[_address[j]])); } require(stableToken.balanceOf(msg.sender) >= total_amount, "Insufficient balance for sender"); require(stableToken.allowance(msg.sender, address(this)) >= total_amount, "Insufficient allowance for contract"); for (uint i = 0; i < length; i++) { // Always use a require when doing token transfer! // Do not think it works like the transfer method for ether, // which handles failure and will throw for you. if (indexOfowner[_address[i]] == 0) { continue; } value = collectPrice.mul(balances[_address[i]]); require(stableToken.transferFrom(msg.sender, _address[i], value)); balances[msg.sender] = balances[msg.sender].add(balances[_address[i]]); emit Transfer(_address[i], msg.sender, balances[_address[i]]); balances[_address[i]] = 0; uint index = indexOfowner[_address[i]].sub(1); indexOfowner[_address[i]] = 0; if (index != allowners.length.sub(1)) { allowners[index] = allowners[allowners.length.sub(1)]; indexOfowner[allowners[index]] = index.add(1); } allowners.length = allowners.length.sub(1); } emit ForceCollectEvent(id, collectPrice, operator); } /** * key inssurance. Split the whole token into small keys. * Only the owner can perform this when the token is still valid and unsplitted. * @param _supply Totol supply in ERC20 standard * @param _decim Decimal parameter in ERC20 standard * @param _price The force acquisition price. If a claimer is willing to pay more than this value, he can * buy the keys forcibly. Notice: the claimer can only buy all keys at one time or buy nothing and the * buying process is delegated into a trusted agent. i.e. the operator. * @param _address The initial distribution plan for the keys. This parameter contains the addresses. * @param _amount The amount corresponding to the initial distribution addresses. */ function split(uint _supply, uint8 _decim, uint _price, address[] _address, uint[] _amount) public onlyValid onlyOperator onlyUnsplitted { require(_address.length == _amount.length); isSplitted = true; _totalSupply = _supply * 10 ** uint(_decim); decimals = _decim; collectPrice = _price; uint amount = 0; uint length = _address.length; balances[msg.sender] = _totalSupply; if (indexOfowner[msg.sender] == 0) { allowners.push(msg.sender); indexOfowner[msg.sender] = allowners.length; } emit Transfer(address(0), msg.sender, _totalSupply); for (uint i = 0; i < length; i++) { amount = _amount[i]; // * 10 ** uint(_decim); balances[_address[i]] = amount; balances[msg.sender] = balances[msg.sender].sub(amount); // ensure that each address appears only once in allowners list // so that distribute divident or force collect only pays one time if (indexOfowner[_address[i]] == 0) { allowners.push(_address[i]); indexOfowner[_address[i]] = allowners.length; } emit Transfer(msg.sender, _address[i], amount); } emit TokenSplitEvent(id, _supply, _decim, _price, owner); } /** * Token conversion. Turn the keys to a whole token. * Only the sender with all keys in hand can perform this and he will be the new owner. */ function merge() public onlyValid onlySplitted { require(balances[msg.sender] == _totalSupply); _totalSupply = 0; balances[msg.sender] = 0; owner = msg.sender; isTradable = false; isSplitted = false; emit Transfer(msg.sender, address(0), _totalSupply); emit TokenSplitEvent(id, 0, 0, 0, msg.sender); } }
* Token owner can approve for `spender` to transferFrom(...) `tokens` from the token owner's account/
function approve(address spender, uint tokens) public onlySplitted returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; }
12,672,271
[ 1, 1345, 3410, 848, 6617, 537, 364, 1375, 87, 1302, 264, 68, 358, 7412, 1265, 5825, 13, 1375, 7860, 68, 628, 326, 1147, 3410, 1807, 2236, 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, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 2430, 13, 203, 3639, 1071, 203, 3639, 1338, 5521, 2344, 203, 3639, 1135, 261, 6430, 2216, 13, 203, 565, 288, 203, 3639, 2935, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 65, 273, 2430, 31, 203, 3639, 3626, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 17571, 264, 16, 2430, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0x3bbF2bEC541bDff23C4a6B3F16BdAB77488d72d2/sources/contracts/AlohaDAO.sol
Token power by rarity (1, 2 and 3)
uint256[] public powerByRarity = [1, 5, 50];
3,741,740
[ 1, 1345, 7212, 635, 436, 20498, 261, 21, 16, 576, 471, 890, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 8526, 1071, 7212, 858, 54, 20498, 273, 306, 21, 16, 1381, 16, 6437, 15533, 540, 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 ]
./full_match/5/0x7ABCc4850CEFC98545d986181EEb4F2356D81116/sources/project:/contracts/PeakyBirds.sol
Represented in basis points (7.5%)
uint256 public constant royaltyPercentage = 750;
1,865,608
[ 1, 23869, 329, 316, 10853, 3143, 261, 27, 18, 25, 9, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 2254, 5034, 1071, 5381, 721, 93, 15006, 16397, 273, 2371, 3361, 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-05-16 */ pragma solidity ^0.5.0; // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Safe Math Library // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } contract DogelonMoon is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { name = "DogelonMoon"; symbol = "MUSK"; decimals = 18; _totalSupply = 1000000000000000000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } }
* Constrctor function Initializes contract with initial supply tokens to the creator of the contract/
constructor() public { name = "DogelonMoon"; symbol = "MUSK"; decimals = 18; _totalSupply = 1000000000000000000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); }
6,809,348
[ 1, 442, 701, 30206, 445, 10188, 3128, 6835, 598, 2172, 14467, 2430, 358, 326, 11784, 434, 326, 6835, 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 ]
[ 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, 3885, 1435, 1071, 288, 203, 3639, 508, 273, 315, 40, 717, 292, 265, 16727, 265, 14432, 203, 3639, 3273, 273, 315, 49, 3378, 47, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 12648, 12648, 12648, 17877, 31, 203, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 1234, 18, 15330, 16, 389, 4963, 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 ]
./full_match/295/0x0000000000000000000000000000000000233233/sources/HederaTokenService.sol
Transfers tokens where the calling account/contract is implicitly the first entry in the token transfer list, where the amount is the value needed to zero balance the transfers. Regular signing rules apply for sending (positive amount) or receiving (negative amount) @param token The token to transfer to/from @param sender The sender for the transaction @param receiver The receiver of the transaction @param serialNumber The serial number of the NFT to transfer.
function transferNFT(address token, address sender, address receiver, int64 serialNumber) internal returns (int responseCode) { (bool success, bytes memory result) = precompileAddress.call( abi.encodeWithSelector(IHederaTokenService.transferNFT.selector, token, sender, receiver, serialNumber)); responseCode = success ? abi.decode(result, (int32)) : HederaResponseCodes.UNKNOWN; }
4,664,492
[ 1, 1429, 18881, 2430, 1625, 326, 4440, 2236, 19, 16351, 353, 24682, 326, 1122, 1241, 316, 326, 1147, 7412, 666, 16, 1625, 326, 3844, 353, 326, 460, 3577, 358, 3634, 11013, 326, 29375, 18, 24544, 10611, 2931, 2230, 364, 5431, 261, 21094, 3844, 13, 578, 15847, 261, 13258, 3844, 13, 225, 1147, 1021, 1147, 358, 7412, 358, 19, 2080, 225, 5793, 1021, 5793, 364, 326, 2492, 225, 5971, 1021, 5971, 434, 326, 2492, 225, 2734, 1854, 1021, 2734, 1300, 434, 326, 423, 4464, 358, 7412, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 50, 4464, 12, 2867, 1147, 16, 1758, 5793, 16, 1758, 5971, 16, 509, 1105, 2734, 1854, 13, 2713, 203, 565, 1135, 261, 474, 20407, 13, 203, 565, 288, 203, 3639, 261, 6430, 2216, 16, 1731, 3778, 563, 13, 273, 675, 11100, 1887, 18, 1991, 12, 203, 5411, 24126, 18, 3015, 1190, 4320, 12, 45, 44, 329, 6070, 1345, 1179, 18, 13866, 50, 4464, 18, 9663, 16, 203, 5411, 1147, 16, 5793, 16, 5971, 16, 2734, 1854, 10019, 203, 3639, 20407, 273, 2216, 692, 24126, 18, 3922, 12, 2088, 16, 261, 474, 1578, 3719, 294, 670, 329, 6070, 1064, 6295, 18, 14737, 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 ]
./partial_match/1/0x350b503C05B54A9bF1ef0F91275D8E6dA5B0796D/sources/PhasesPass.sol
* @dev Mints `quantity` tokens and transfers them to `to`. This function is intended for efficient minting only during contract creation. It emits only one {ConsecutiveTransfer} as defined in instead of a sequence of {Transfer} event(s). Calling this function outside of contract creation WILL make your contract non-compliant with the ERC721 standard. For full ERC721 compliance, substituting ERC721 {Transfer} event(s) with the ERC2309 {ConsecutiveTransfer} event is only permissible during contract creation. Requirements: - `to` cannot be the zero address. - `quantity` must be greater than 0. Emits a {ConsecutiveTransfer} event./ Overflows are unrealistic due to the above check for `quantity` to be below the limit. Updates: - `balance += quantity`. - `numberMinted += quantity`. We can directly add to the balance and number minted. Updates: - `address` to the owner. - `startTimestamp` to the timestamp of minting. - `burned` to `false`. - `nextInitialized` to `quantity == 1`.
function _mintERC2309(address to, uint256 quantity) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); if (quantity > MAX_MINT_ERC2309_QUANTITY_LIMIT) revert MintERC2309QuantityExceedsLimit(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); unchecked { _packedAddressData[to] += quantity * ((1 << BITPOS_NUMBER_MINTED) | 1); _packedOwnerships[startTokenId] = _packOwnershipData( to, (_boolToUint256(quantity == 1) << BITPOS_NEXT_INITIALIZED) | _nextExtraData(address(0), to, 0) ); emit ConsecutiveTransfer( startTokenId, startTokenId + quantity - 1, address(0), to ); _currentIndex = startTokenId + quantity; } _afterTokenTransfers(address(0), to, startTokenId, quantity); }
16,000,558
[ 1, 49, 28142, 1375, 16172, 68, 2430, 471, 29375, 2182, 358, 1375, 869, 8338, 1220, 445, 353, 12613, 364, 14382, 312, 474, 310, 1338, 4982, 6835, 6710, 18, 2597, 24169, 1338, 1245, 288, 442, 15655, 5912, 97, 487, 2553, 316, 3560, 434, 279, 3102, 434, 288, 5912, 97, 871, 12, 87, 2934, 21020, 333, 445, 8220, 434, 6835, 6710, 678, 15125, 1221, 3433, 6835, 1661, 17, 832, 18515, 598, 326, 4232, 39, 27, 5340, 4529, 18, 2457, 1983, 4232, 39, 27, 5340, 29443, 16, 7461, 8490, 4232, 39, 27, 5340, 288, 5912, 97, 871, 12, 87, 13, 598, 326, 4232, 39, 4366, 5908, 288, 442, 15655, 5912, 97, 871, 353, 1338, 293, 1840, 1523, 4982, 6835, 6710, 18, 29076, 30, 300, 1375, 869, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 16172, 68, 1297, 506, 6802, 2353, 374, 18, 7377, 1282, 279, 288, 442, 15655, 5912, 97, 871, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 389, 81, 474, 654, 39, 4366, 5908, 12, 2867, 358, 16, 2254, 5034, 10457, 13, 2713, 288, 203, 3639, 2254, 5034, 787, 1345, 548, 273, 389, 2972, 1016, 31, 203, 3639, 309, 261, 869, 422, 1758, 12, 20, 3719, 15226, 490, 474, 774, 7170, 1887, 5621, 203, 3639, 309, 261, 16172, 422, 374, 13, 15226, 490, 474, 7170, 12035, 5621, 203, 3639, 309, 261, 16172, 405, 4552, 67, 49, 3217, 67, 654, 39, 4366, 5908, 67, 3500, 6856, 4107, 67, 8283, 13, 203, 5411, 15226, 490, 474, 654, 39, 4366, 5908, 12035, 424, 5288, 87, 3039, 5621, 203, 203, 3639, 389, 5771, 1345, 1429, 18881, 12, 2867, 12, 20, 3631, 358, 16, 787, 1345, 548, 16, 10457, 1769, 203, 203, 3639, 22893, 288, 203, 5411, 389, 2920, 329, 1887, 751, 63, 869, 65, 1011, 203, 7734, 10457, 380, 203, 7734, 14015, 21, 2296, 20469, 7057, 67, 9931, 67, 6236, 6404, 13, 571, 404, 1769, 203, 203, 5411, 389, 2920, 329, 5460, 12565, 87, 63, 1937, 1345, 548, 65, 273, 389, 2920, 5460, 12565, 751, 12, 203, 7734, 358, 16, 203, 7734, 261, 67, 6430, 774, 5487, 5034, 12, 16172, 422, 404, 13, 2296, 20469, 7057, 67, 25539, 67, 12919, 25991, 13, 571, 203, 10792, 389, 4285, 7800, 751, 12, 2867, 12, 20, 3631, 358, 16, 374, 13, 203, 5411, 11272, 203, 203, 5411, 3626, 735, 15655, 5912, 12, 203, 7734, 787, 1345, 548, 16, 203, 7734, 787, 1345, 548, 397, 10457, 300, 404, 16, 203, 7734, 1758, 12, 20, 3631, 203, 7734, 2 ]
pragma solidity 0.5.11; pragma experimental "ABIEncoderV2"; import "../libs/LibStateChannelApp.sol"; contract MChallengeRegistryCore { // A mapping of appIdentityHash to AppChallenge structs which represents // the current on-chain status of some particular application's state. mapping (bytes32 => LibStateChannelApp.AppChallenge) public appChallenges; // A mapping of appIdentityHash to outcomes mapping (bytes32 => bytes) public appOutcomes; /// @notice Compute a unique hash for a single instance of an App /// @param appIdentity An `AppIdentity` struct that encodes all unique info for an App /// @return A bytes32 hash of the AppIdentity function appIdentityToHash( LibStateChannelApp.AppIdentity memory appIdentity ) internal pure returns (bytes32) { return keccak256( abi.encode(appIdentity.channelNonce, appIdentity.participants) ); } /// @notice Compute a unique hash for the state of a channelized app instance /// @param identityHash The unique hash of an `AppIdentity` /// @param appStateHash The hash of the app state to be signed /// @param versionNumber The versionNumber corresponding to the version of the state /// @param timeout A dynamic timeout value representing the timeout for this state /// @return A bytes32 hash of the RLP encoded arguments function computeAppChallengeHash( bytes32 identityHash, bytes32 appStateHash, uint256 versionNumber, uint256 timeout ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( byte(0x19), identityHash, versionNumber, timeout, appStateHash ) ); } /// @notice Compute a unique hash for an action used in this channel application /// @param turnTaker The address of the user taking the action /// @param previousState The hash of a state this action is being taken on /// @param action The ABI encoded version of the action being taken /// @param versionNumber The versionNumber of the state this action is being taken on /// @return A bytes32 hash of the arguments function computeActionHash( address turnTaker, bytes32 previousState, bytes memory action, uint256 versionNumber ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( byte(0x19), turnTaker, previousState, action, versionNumber ) ); } }
@notice Compute a unique hash for a single instance of an App @param appIdentity An `AppIdentity` struct that encodes all unique info for an App @return A bytes32 hash of the AppIdentity
{ return keccak256( abi.encode(appIdentity.channelNonce, appIdentity.participants) ); }
14,073,455
[ 1, 7018, 279, 3089, 1651, 364, 279, 2202, 791, 434, 392, 4677, 225, 595, 4334, 1922, 1375, 3371, 4334, 68, 1958, 716, 16834, 777, 3089, 1123, 364, 392, 4677, 327, 432, 1731, 1578, 1651, 434, 326, 4677, 4334, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 288, 203, 565, 327, 417, 24410, 581, 5034, 12, 203, 1377, 24126, 18, 3015, 12, 2910, 4334, 18, 4327, 13611, 16, 595, 4334, 18, 2680, 27620, 13, 203, 565, 11272, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x6A6097E4ff385770ceE04B3094c7A0d9D653117a/sources/project_/contracts/FOHLE_Pair.sol
using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance0.sub(uint256(_privateFees1))) / _totalSupply;
1,850,018
[ 1, 9940, 324, 26488, 11932, 450, 17, 86, 396, 7006, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 3844, 21, 273, 4501, 372, 24237, 18, 16411, 12, 12296, 20, 18, 1717, 12, 11890, 5034, 24899, 1152, 2954, 281, 21, 20349, 342, 389, 4963, 3088, 1283, 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 ]
contract mixer { struct anon_registeration{ address sender; uint value; bool valid; } struct public_user{ uint deposit; address addr; bool valid; uint revealed_deposit; uint[] registration_values; // used only if there is violation } struct mixing_deal{ uint start_time; public_user[] users; // must hold array to iterate them mapping (address=>uint) user_to_index_mapping; anon_registeration[] registrations; mapping (address=>uint) registration_to_index_mapping; uint32 min_num_participants; uint registration_deposit_size_in_wei; uint phase_time_in_secs; uint deposit_sum; uint registration_sum; bool violated; } mixing_deal[] deals; enum deal_state{ invalid, initial_deposit, anonymous_registration, anonymous_withdraw, anonymous_revealing, public_withdraw_not_enough_parties, public_withdraw_violation } modifier non_payable { if (msg.value > 0 ) throw; _ } function mixer(){ deals.length = 0; } function number_of_deals( ) constant returns(uint){ return deals.length; } function not_after_phase(mixing_deal deal, uint phase) constant private returns(bool){ return deal.start_time + deal.phase_time_in_secs * phase >= now; } function get_deal_state(uint deal_id) constant returns(deal_state){ if( deals.length <= deal_id ) return deal_state.invalid; mixing_deal deal = deals[ deal_id ]; if( not_after_phase(deal, 1) ) return deal_state.initial_deposit; if( deal.users.length < deal.min_num_participants ) return deal_state.public_withdraw_not_enough_parties; if( not_after_phase(deal, 2) ) return deal_state.anonymous_registration; if( deal.violated ){ if( not_after_phase(deal, 3) ) return deal_state.anonymous_revealing; // else - phase 4 return deal_state.public_withdraw_violation; } else{ return deal_state.anonymous_withdraw; } } function get_deal_status(uint deal_id) constant returns(uint state, uint start_time, uint num_users, uint num_registrations, uint min_num_participants, uint registration_deposit_size_in_wei, uint phase_time_in_secs, uint deposit_sum, uint registration_sum, bool violated ){ state = uint(get_deal_state(deal_id)); if( state != uint(deal_state.invalid) ){ mixing_deal deal = deals[ deal_id ]; start_time = deal.start_time; num_users = deal.users.length; num_registrations = deal.registrations.length; min_num_participants = deal.min_num_participants; registration_deposit_size_in_wei = deal.registration_deposit_size_in_wei; phase_time_in_secs = deal.phase_time_in_secs; deposit_sum = deal.deposit_sum; registration_sum = deal.registration_sum; violated = deal.violated; } } function create_new_deal(uint32 _min_num_participants, uint _registration_deposit_size_in_wei, uint32 _phase_time_in_minutes ) non_payable returns (uint) { uint deal_id = deals.length; deals.length += 1; deals[ deal_id ].start_time = now; deals[ deal_id ].min_num_participants = _min_num_participants; deals[ deal_id ].registration_deposit_size_in_wei = _registration_deposit_size_in_wei; deals[ deal_id ].phase_time_in_secs = _phase_time_in_minutes * 1 minutes; deals[ deal_id ].users.length = 0; deals[ deal_id ].deposit_sum = 0; deals[ deal_id ].registration_sum = 0; deals[ deal_id ].violated = false; return deal_id; } function make_initial_deposit( uint deal_id ){ if( get_deal_state( deal_id ) != deal_state.initial_deposit ) throw; mixing_deal deal = deals[ deal_id ]; uint user_index = deal.users.length; deal.users.length += 1; deal.users[ user_index ].deposit = msg.value; deal.users[ user_index ].addr = msg.sender; deal.users[ user_index ].revealed_deposit = 0; deal.users[ user_index ].valid = true; deal.users[ user_index ].registration_values.length = 0; deal.user_to_index_mapping[ msg.sender ] = user_index; deal.deposit_sum += msg.value; } function make_anonymous_registration( uint deal_id, uint amount_in_wei ){ if( get_deal_state( deal_id ) != deal_state.anonymous_registration ) throw; if( amount_in_wei > 1024 * 1024 * 1024 ether ) throw; // prevent overflows mixing_deal deal = deals[ deal_id ]; if( msg.value != deal.registration_deposit_size_in_wei ) throw; uint reg_id = deal.registrations.length; deal.registrations.length += 1; deal.registrations[ reg_id ].sender = msg.sender; deal.registrations[ reg_id ].value = amount_in_wei; deal.registrations[ reg_id ].valid = true; deal.registration_to_index_mapping[ msg.sender ] = reg_id; deal.registration_sum += amount_in_wei; if( deal.registration_sum > deal.deposit_sum ) deal.violated = true; } function make_anonymous_withdraw(uint deal_id) non_payable{ if( get_deal_state( deal_id ) != deal_state.anonymous_withdraw ) throw; uint reg_index = deals[ deal_id ].registration_to_index_mapping[ msg.sender ]; anon_registeration reg = deals[ deal_id ].registrations[ reg_index ]; if( ! reg.valid ) throw; // invalidate for next time reg.valid = false; uint value = reg.value + deals[ deal_id ].registration_deposit_size_in_wei; if( ! reg.sender.send( value ) ) throw; } function reveal_registration( uint deal_id, address public_address ) non_payable{ if( get_deal_state( deal_id ) != deal_state.anonymous_revealing ) throw; mixing_deal deal = deals[ deal_id ]; // get registration uint reg_index = deal.registration_to_index_mapping[ msg.sender ]; anon_registeration reg = deal.registrations[ reg_index ]; if( ! reg.valid ) throw; reg.valid = false; // get user uint user_index = deal.user_to_index_mapping[ public_address ]; public_user user = deal.users[ user_index ]; if( ! user.valid ) throw; // assume no overflows if( user.deposit >= user.revealed_deposit + reg.value ){ uint rev_id = user.registration_values.length; user.registration_values.length += 1; user.registration_values[ rev_id ] = reg.value; user.revealed_deposit += reg.value; return; } // else - replace with higher value deposit uint max_index = 0; uint max_value = user.registration_values[ 0 ]; for ( uint index = 1; index < user.registration_values.length; index += 1 ){ if( user.registration_values[ index ] > max_value ){ max_index = index; max_value = user.registration_values[ index ]; } } if( max_value < reg.value ) return; // ignore this registration // else - replace max with new reg user.registration_values[ max_index ] = reg.value; user.revealed_deposit = user.revealed_deposit + reg.value - max_value; } function public_withdraw( uint deal_id ) non_payable{ if( ( get_deal_state( deal_id ) != deal_state.public_withdraw_not_enough_parties ) && ( get_deal_state( deal_id ) != deal_state.public_withdraw_violation ) ) throw; mixing_deal deal = deals[ deal_id ]; uint user_index = deal.user_to_index_mapping[ msg.sender ]; public_user user = deal.users[ user_index ]; if( ! user.valid ) throw; user.valid = false; uint value = user.deposit; if( get_deal_state( deal_id ) == deal_state.public_withdraw_violation ){ value += user.registration_values.length * deal.registration_deposit_size_in_wei; } if( ! user.addr.send( value ) ) throw; } }
ignore this registration
if( max_value < reg.value ) return;
7,221,862
[ 1, 6185, 333, 7914, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 12, 943, 67, 1132, 411, 960, 18, 1132, 262, 327, 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 ]
./partial_match/1/0x48b95265749775310B77418Ff6f9675396ABE1e8/sources/@yield-protocol/yieldspace-tv/src/Pool/Pool.sol
Returns how much fyToken would be required to buy `sharesOut`. @dev Note: This fn takes sharesOut as a param while the external fn takes baseOut.
function _buyBasePreview( uint128 sharesOut, uint104 sharesBalance, uint104 fyTokenBalance, int128 g2_ ) internal view beforeMaturity returns (uint128 fyTokenIn) { uint96 scaleFactor_ = scaleFactor; fyTokenIn = YieldMath.fyTokenInForSharesOut( sharesBalance * scaleFactor_, fyTokenBalance * scaleFactor_, sharesOut * scaleFactor_, ts, g2_, _getC(), mu ) / scaleFactor_; } I want to buy `uint128 fyTokenOut` worth of fyTokens. _______ I've transferred you some base tokens -- that should be enough. / GUY \ ┌─────────┐ (^^^| \=========== ┌──────────────┐ │no │ \(\/ | _ _ | │$ $│ │lifeguard│ \ \ (. o o | │ ┌────────────┴─┐ └─┬─────┬─┘ ==+ \ \ | ~ | │ │$ $│ hmm, let's see here │ │ =======+ \ \ \ == / │ │ B A S E │ _____│_____│______ |+ \ \___| |___ │$│ │ .-'"___________________`-.|+ \ / \__/ \ └─┤$ $│ ( .'" '-.)+ \ \ └──────────────┘ |`-..__________________..-'|+ --| GUY |\_/\ / / | |+ | | \ \/ / | |+ | | \ / _......._ /`| --- --- |+ | | \_/ .-:::::::::::-. / /| (o ) (o ) |+ |______| .:::::::::::::::::. / / | |+ |__GG__| : _______ __ __ : _.-" ; | [ |+ | | :: | || | | |::),.-' | ---------- |+ | | | ::: | ___|| |_| |:::/ \ \________/ /+ | | _| ::: | |___ | |::: `-..__________________..-' += | | | ::: | ___||_ _|::: | | | | | | | ::: | | | | ::: | | | | ( ( | :: |___| |___| :: | | | | | | | : fyTokenOut : T----T T----T | | | `:::::::::::::::::' _..._L____J L____J _..._ _| | | `-:::::::::::-' .` "-. `% | | %` .-" `. (_____[__) `'''''''` / \ .: :. / \ '-..___|_..=:` `-:=.._|___..-'
4,008,291
[ 1, 1356, 3661, 9816, 28356, 1345, 4102, 506, 1931, 358, 30143, 1375, 30720, 1182, 8338, 225, 3609, 30, 1220, 2295, 5530, 24123, 1182, 487, 279, 579, 1323, 326, 3903, 2295, 5530, 1026, 1182, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 70, 9835, 2171, 11124, 12, 203, 3639, 2254, 10392, 24123, 1182, 16, 203, 3639, 2254, 21869, 24123, 13937, 16, 203, 3639, 2254, 21869, 28356, 1345, 13937, 16, 203, 3639, 509, 10392, 314, 22, 67, 203, 565, 262, 2713, 1476, 1865, 15947, 2336, 1135, 261, 11890, 10392, 28356, 1345, 382, 13, 288, 203, 3639, 2254, 10525, 3159, 6837, 67, 273, 3159, 6837, 31, 203, 3639, 28356, 1345, 382, 273, 203, 5411, 31666, 10477, 18, 74, 93, 1345, 382, 1290, 24051, 1182, 12, 203, 7734, 24123, 13937, 380, 3159, 6837, 67, 16, 203, 7734, 28356, 1345, 13937, 380, 3159, 6837, 67, 16, 203, 7734, 24123, 1182, 380, 3159, 6837, 67, 16, 203, 7734, 3742, 16, 203, 7734, 314, 22, 67, 16, 203, 7734, 389, 588, 39, 9334, 203, 7734, 4129, 203, 5411, 262, 342, 203, 5411, 3159, 6837, 67, 31, 203, 565, 289, 203, 203, 7682, 467, 2545, 358, 30143, 1375, 11890, 10392, 28356, 1345, 1182, 68, 26247, 434, 28356, 5157, 18, 203, 2398, 389, 7198, 972, 377, 467, 8081, 906, 4193, 1846, 2690, 1026, 2430, 1493, 716, 1410, 506, 7304, 18, 203, 5411, 342, 282, 611, 57, 61, 521, 4766, 1171, 225, 163, 247, 239, 163, 247, 227, 163, 247, 227, 163, 247, 227, 163, 247, 227, 163, 247, 227, 163, 247, 227, 163, 247, 227, 163, 247, 227, 163, 247, 227, 163, 247, 243, 203, 377, 261, 12800, 66, 96, 282, 521, 1432, 12275, 225, 225, 163, 247, 239, 163, 247, 227, 163, 247, 227, 163, 247, 227, 163, 247, 227, 2 ]
pragma solidity ^0.4.21; // File: contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: contracts/token/ERC20Basic.sol /** * @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); } // File: contracts/token/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } // File: contracts/token/BurnableToken.sol /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender&#39;s balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(burner, _value); } } // File: contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: contracts/token/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/token/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: contracts/token/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. * */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File: contracts/token/SafeERC20.sol /** * @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)); } } // File: contracts/BitexToken.sol contract BitexToken is MintableToken, BurnableToken { using SafeERC20 for ERC20; string public constant name = "Bitex Coin"; string public constant symbol = "XBX"; uint8 public decimals = 18; bool public tradingStarted = false; // allow exceptional transfer fro sender address - this mapping can be modified only before the starting rounds mapping (address => bool) public transferable; /** * @dev modifier that throws if spender address is not allowed to transfer * and the trading is not enabled */ modifier allowTransfer(address _spender) { require(tradingStarted || transferable[_spender]); _; } /** * * Only the owner of the token smart contract can add allow token to be transfer before the trading has started * */ function modifyTransferableHash(address _spender, bool value) onlyOwner public { transferable[_spender] = value; } /** * @dev Allows the owner to enable the trading. */ function startTrading() onlyOwner public { tradingStarted = true; } /** * @dev Allows anyone to transfer the tokens once trading has started * @param _to the recipient address of the tokens. * @param _value number of tokens to be transfered. */ function transfer(address _to, uint _value) allowTransfer(msg.sender) public returns (bool){ return super.transfer(_to, _value); } /** * @dev Allows anyone to transfer the tokens once trading has started or if the spender is part of the mapping * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint _value) allowTransfer(_from) public returns (bool){ return super.transferFrom(_from, _to, _value); } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender when not paused. * @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 allowTransfer(_spender) returns (bool) { return super.approve(_spender, _value); } /** * Adding whenNotPaused */ function increaseApproval(address _spender, uint _addedValue) public allowTransfer(_spender) returns (bool success) { return super.increaseApproval(_spender, _addedValue); } /** * Adding whenNotPaused */ function decreaseApproval(address _spender, uint _subtractedValue) public allowTransfer(_spender) returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } }
allow exceptional transfer fro sender address - this mapping can be modified only before the starting rounds
contract BitexToken is MintableToken, BurnableToken { using SafeERC20 for ERC20; string public constant name = "Bitex Coin"; string public constant symbol = "XBX"; uint8 public decimals = 18; bool public tradingStarted = false; mapping (address => bool) public transferable; modifier allowTransfer(address _spender) { require(tradingStarted || transferable[_spender]); _; } function modifyTransferableHash(address _spender, bool value) onlyOwner public { transferable[_spender] = value; } function startTrading() onlyOwner public { tradingStarted = true; } function transfer(address _to, uint _value) allowTransfer(msg.sender) public returns (bool){ return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) allowTransfer(_from) public returns (bool){ return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public allowTransfer(_spender) returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public allowTransfer(_spender) returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public allowTransfer(_spender) returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } }
1,970,154
[ 1, 5965, 1520, 287, 7412, 284, 303, 5793, 1758, 300, 333, 2874, 225, 848, 506, 4358, 1338, 1865, 326, 5023, 21196, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 6539, 338, 1345, 353, 490, 474, 429, 1345, 16, 605, 321, 429, 1345, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 4232, 39, 3462, 31, 203, 203, 565, 533, 1071, 5381, 508, 273, 315, 5775, 338, 28932, 14432, 203, 203, 565, 533, 1071, 5381, 3273, 273, 315, 60, 38, 60, 14432, 203, 203, 565, 2254, 28, 1071, 15105, 273, 6549, 31, 203, 203, 565, 1426, 1071, 1284, 7459, 9217, 273, 629, 31, 203, 203, 565, 2874, 261, 2867, 516, 1426, 13, 1071, 7412, 429, 31, 203, 203, 203, 565, 9606, 1699, 5912, 12, 2867, 389, 87, 1302, 264, 13, 288, 203, 203, 3639, 2583, 12, 313, 14968, 9217, 747, 7412, 429, 63, 67, 87, 1302, 264, 19226, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 5612, 5912, 429, 2310, 12, 2867, 389, 87, 1302, 264, 16, 1426, 460, 13, 1338, 5541, 1071, 288, 203, 3639, 7412, 429, 63, 67, 87, 1302, 264, 65, 273, 460, 31, 203, 565, 289, 203, 203, 565, 445, 787, 1609, 7459, 1435, 1338, 5541, 1071, 288, 203, 3639, 1284, 7459, 9217, 273, 638, 31, 203, 565, 289, 203, 203, 565, 445, 7412, 12, 2867, 389, 869, 16, 2254, 389, 1132, 13, 1699, 5912, 12, 3576, 18, 15330, 13, 1071, 1135, 261, 6430, 15329, 203, 3639, 327, 2240, 18, 13866, 24899, 869, 16, 389, 1132, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 389, 1132, 13, 1699, 5912, 24899, 2080, 13, 1071, 2 ]
/** Source code of Opium Protocol Web https://opium.network Telegram https://t.me/opium_network Twitter https://twitter.com/opium_network */ // File: LICENSE /** The software and documentation available in this repository (the "Software") is protected by copyright law and accessible pursuant to the license set forth below. Copyright © 2020 Blockeys BV. All rights reserved. Permission is hereby granted, free of charge, to any person or organization obtaining the Software (the “Licensee”) to privately study, review, and analyze the Software. Licensee shall not use the Software for any other purpose. Licensee shall not modify, transfer, assign, share, or sub-license the Software or any derivative works of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // File: contracts/Lib/LibDerivative.sol pragma solidity 0.5.16; pragma experimental ABIEncoderV2; /// @title Opium.Lib.LibDerivative contract should be inherited by contracts that use Derivative structure and calculate derivativeHash contract LibDerivative { // Opium derivative structure (ticker) definition struct Derivative { // Margin parameter for syntheticId uint256 margin; // Maturity of derivative uint256 endTime; // Additional parameters for syntheticId uint256[] params; // oracleId of derivative address oracleId; // Margin token address of derivative address token; // syntheticId of derivative address syntheticId; } /// @notice Calculates hash of provided Derivative /// @param _derivative Derivative Instance of derivative to hash /// @return derivativeHash bytes32 Derivative hash function getDerivativeHash(Derivative memory _derivative) public pure returns (bytes32 derivativeHash) { derivativeHash = keccak256(abi.encodePacked( _derivative.margin, _derivative.endTime, _derivative.params, _derivative.oracleId, _derivative.token, _derivative.syntheticId )); } } // File: openzeppelin-solidity/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-solidity/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-solidity/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. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * IMPORTANT: It is unsafe to assume that an address for which this * function returns false is an externally-owned account (EOA) and not a * contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: openzeppelin-solidity/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: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.5.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. */ contract ReentrancyGuard { // counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } } // File: erc721o/contracts/Libs/LibPosition.sol pragma solidity ^0.5.4; library LibPosition { function getLongTokenId(bytes32 _hash) public pure returns (uint256 tokenId) { tokenId = uint256(keccak256(abi.encodePacked(_hash, "LONG"))); } function getShortTokenId(bytes32 _hash) public pure returns (uint256 tokenId) { tokenId = uint256(keccak256(abi.encodePacked(_hash, "SHORT"))); } } // File: contracts/Interface/IDerivativeLogic.sol pragma solidity 0.5.16; /// @title Opium.Interface.IDerivativeLogic contract is an interface that every syntheticId should implement contract IDerivativeLogic is LibDerivative { /// @notice Validates ticker /// @param _derivative Derivative Instance of derivative to validate /// @return Returns boolean whether ticker is valid function validateInput(Derivative memory _derivative) public view returns (bool); /// @notice Calculates margin required for derivative creation /// @param _derivative Derivative Instance of derivative /// @return buyerMargin uint256 Margin needed from buyer (LONG position) /// @return sellerMargin uint256 Margin needed from seller (SHORT position) function getMargin(Derivative memory _derivative) public view returns (uint256 buyerMargin, uint256 sellerMargin); /// @notice Calculates payout for derivative execution /// @param _derivative Derivative Instance of derivative /// @param _result uint256 Data retrieved from oracleId on the maturity /// @return buyerPayout uint256 Payout in ratio for buyer (LONG position holder) /// @return sellerPayout uint256 Payout in ratio for seller (SHORT position holder) function getExecutionPayout(Derivative memory _derivative, uint256 _result) public view returns (uint256 buyerPayout, uint256 sellerPayout); /// @notice Returns syntheticId author address for Opium commissions /// @return authorAddress address The address of syntheticId address function getAuthorAddress() public view returns (address authorAddress); /// @notice Returns syntheticId author commission in base of COMMISSION_BASE /// @return commission uint256 Author commission function getAuthorCommission() public view returns (uint256 commission); /// @notice Returns whether thirdparty could execute on derivative's owner's behalf /// @param _derivativeOwner address Derivative owner address /// @return Returns boolean whether _derivativeOwner allowed third party execution function thirdpartyExecutionAllowed(address _derivativeOwner) public view returns (bool); /// @notice Returns whether syntheticId implements pool logic /// @return Returns whether syntheticId implements pool logic function isPool() public view returns (bool); /// @notice Sets whether thirds parties are allowed or not to execute derivative's on msg.sender's behalf /// @param _allow bool Flag for execution allowance function allowThirdpartyExecution(bool _allow) public; // Event with syntheticId metadata JSON string (for DIB.ONE derivative explorer) event MetadataSet(string metadata); } // File: contracts/Errors/CoreErrors.sol pragma solidity 0.5.16; contract CoreErrors { string constant internal ERROR_CORE_NOT_POOL = "CORE:NOT_POOL"; string constant internal ERROR_CORE_CANT_BE_POOL = "CORE:CANT_BE_POOL"; string constant internal ERROR_CORE_TICKER_WAS_CANCELLED = "CORE:TICKER_WAS_CANCELLED"; string constant internal ERROR_CORE_SYNTHETIC_VALIDATION_ERROR = "CORE:SYNTHETIC_VALIDATION_ERROR"; string constant internal ERROR_CORE_NOT_ENOUGH_TOKEN_ALLOWANCE = "CORE:NOT_ENOUGH_TOKEN_ALLOWANCE"; string constant internal ERROR_CORE_TOKEN_IDS_AND_QUANTITIES_LENGTH_DOES_NOT_MATCH = "CORE:TOKEN_IDS_AND_QUANTITIES_LENGTH_DOES_NOT_MATCH"; string constant internal ERROR_CORE_TOKEN_IDS_AND_DERIVATIVES_LENGTH_DOES_NOT_MATCH = "CORE:TOKEN_IDS_AND_DERIVATIVES_LENGTH_DOES_NOT_MATCH"; string constant internal ERROR_CORE_EXECUTION_BEFORE_MATURITY_NOT_ALLOWED = "CORE:EXECUTION_BEFORE_MATURITY_NOT_ALLOWED"; string constant internal ERROR_CORE_SYNTHETIC_EXECUTION_WAS_NOT_ALLOWED = "CORE:SYNTHETIC_EXECUTION_WAS_NOT_ALLOWED"; string constant internal ERROR_CORE_INSUFFICIENT_POOL_BALANCE = "CORE:INSUFFICIENT_POOL_BALANCE"; string constant internal ERROR_CORE_CANT_CANCEL_DUMMY_ORACLE_ID = "CORE:CANT_CANCEL_DUMMY_ORACLE_ID"; string constant internal ERROR_CORE_CANCELLATION_IS_NOT_ALLOWED = "CORE:CANCELLATION_IS_NOT_ALLOWED"; string constant internal ERROR_CORE_UNKNOWN_POSITION_TYPE = "CORE:UNKNOWN_POSITION_TYPE"; } // File: contracts/Errors/RegistryErrors.sol pragma solidity 0.5.16; contract RegistryErrors { string constant internal ERROR_REGISTRY_ONLY_INITIALIZER = "REGISTRY:ONLY_INITIALIZER"; string constant internal ERROR_REGISTRY_ONLY_OPIUM_ADDRESS_ALLOWED = "REGISTRY:ONLY_OPIUM_ADDRESS_ALLOWED"; string constant internal ERROR_REGISTRY_CANT_BE_ZERO_ADDRESS = "REGISTRY:CANT_BE_ZERO_ADDRESS"; string constant internal ERROR_REGISTRY_ALREADY_SET = "REGISTRY:ALREADY_SET"; } // File: contracts/Registry.sol pragma solidity 0.5.16; /// @title Opium.Registry contract keeps addresses of deployed Opium contracts set to allow them route and communicate to each other contract Registry is RegistryErrors { // Address of Opium.TokenMinter contract address private minter; // Address of Opium.Core contract address private core; // Address of Opium.OracleAggregator contract address private oracleAggregator; // Address of Opium.SyntheticAggregator contract address private syntheticAggregator; // Address of Opium.TokenSpender contract address private tokenSpender; // Address of Opium commission receiver address private opiumAddress; // Address of Opium contract set deployer address public initializer; /// @notice This modifier restricts access to functions, which could be called only by initializer modifier onlyInitializer() { require(msg.sender == initializer, ERROR_REGISTRY_ONLY_INITIALIZER); _; } /// @notice Sets initializer constructor() public { initializer = msg.sender; } // SETTERS /// @notice Sets Opium.TokenMinter, Opium.Core, Opium.OracleAggregator, Opium.SyntheticAggregator, Opium.TokenSpender, Opium commission receiver addresses and allows to do it only once /// @param _minter address Address of Opium.TokenMinter /// @param _core address Address of Opium.Core /// @param _oracleAggregator address Address of Opium.OracleAggregator /// @param _syntheticAggregator address Address of Opium.SyntheticAggregator /// @param _tokenSpender address Address of Opium.TokenSpender /// @param _opiumAddress address Address of Opium commission receiver function init( address _minter, address _core, address _oracleAggregator, address _syntheticAggregator, address _tokenSpender, address _opiumAddress ) external onlyInitializer { require( minter == address(0) && core == address(0) && oracleAggregator == address(0) && syntheticAggregator == address(0) && tokenSpender == address(0) && opiumAddress == address(0), ERROR_REGISTRY_ALREADY_SET ); require( _minter != address(0) && _core != address(0) && _oracleAggregator != address(0) && _syntheticAggregator != address(0) && _tokenSpender != address(0) && _opiumAddress != address(0), ERROR_REGISTRY_CANT_BE_ZERO_ADDRESS ); minter = _minter; core = _core; oracleAggregator = _oracleAggregator; syntheticAggregator = _syntheticAggregator; tokenSpender = _tokenSpender; opiumAddress = _opiumAddress; } /// @notice Allows opium commission receiver address to change itself /// @param _opiumAddress address New opium commission receiver address function changeOpiumAddress(address _opiumAddress) external { require(opiumAddress == msg.sender, ERROR_REGISTRY_ONLY_OPIUM_ADDRESS_ALLOWED); require(_opiumAddress != address(0), ERROR_REGISTRY_CANT_BE_ZERO_ADDRESS); opiumAddress = _opiumAddress; } // GETTERS /// @notice Returns address of Opium.TokenMinter /// @param result address Address of Opium.TokenMinter function getMinter() external view returns (address result) { return minter; } /// @notice Returns address of Opium.Core /// @param result address Address of Opium.Core function getCore() external view returns (address result) { return core; } /// @notice Returns address of Opium.OracleAggregator /// @param result address Address of Opium.OracleAggregator function getOracleAggregator() external view returns (address result) { return oracleAggregator; } /// @notice Returns address of Opium.SyntheticAggregator /// @param result address Address of Opium.SyntheticAggregator function getSyntheticAggregator() external view returns (address result) { return syntheticAggregator; } /// @notice Returns address of Opium.TokenSpender /// @param result address Address of Opium.TokenSpender function getTokenSpender() external view returns (address result) { return tokenSpender; } /// @notice Returns address of Opium commission receiver /// @param result address Address of Opium commission receiver function getOpiumAddress() external view returns (address result) { return opiumAddress; } } // File: contracts/Errors/UsingRegistryErrors.sol pragma solidity 0.5.16; contract UsingRegistryErrors { string constant internal ERROR_USING_REGISTRY_ONLY_CORE_ALLOWED = "USING_REGISTRY:ONLY_CORE_ALLOWED"; } // File: contracts/Lib/UsingRegistry.sol pragma solidity 0.5.16; /// @title Opium.Lib.UsingRegistry contract should be inherited by contracts, that are going to use Opium.Registry contract UsingRegistry is UsingRegistryErrors { // Emitted when registry instance is set event RegistrySet(address registry); // Instance of Opium.Registry contract Registry internal registry; /// @notice This modifier restricts access to functions, which could be called only by Opium.Core modifier onlyCore() { require(msg.sender == registry.getCore(), ERROR_USING_REGISTRY_ONLY_CORE_ALLOWED); _; } /// @notice Defines registry instance and emits appropriate event constructor(address _registry) public { registry = Registry(_registry); emit RegistrySet(_registry); } /// @notice Getter for registry variable /// @return address Address of registry set in current contract function getRegistry() external view returns (address) { return address(registry); } } // File: contracts/Lib/LibCommission.sol pragma solidity 0.5.16; /// @title Opium.Lib.LibCommission contract defines constants for Opium commissions contract LibCommission { // Represents 100% base for commissions calculation uint256 constant public COMMISSION_BASE = 10000; // Represents 100% base for Opium commission uint256 constant public OPIUM_COMMISSION_BASE = 10; // Represents which part of `syntheticId` author commissions goes to opium uint256 constant public OPIUM_COMMISSION_PART = 1; } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.5.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } // File: erc721o/contracts/Libs/UintArray.sol pragma solidity ^0.5.4; library UintArray { function indexOf(uint256[] memory A, uint256 a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (0, false); } function contains(uint256[] memory A, uint256 a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } function difference(uint256[] memory A, uint256[] memory B) internal pure returns (uint256[] memory, uint256[] memory) { uint256 length = A.length; bool[] memory includeMap = new bool[](length); uint256 count = 0; // First count the new length because can't push for in-memory arrays for (uint256 i = 0; i < length; i++) { uint256 e = A[i]; if (!contains(B, e)) { includeMap[i] = true; count++; } } uint256[] memory newUints = new uint256[](count); uint256[] memory newUintsIdxs = new uint256[](count); uint256 j = 0; for (uint256 i = 0; i < length; i++) { if (includeMap[i]) { newUints[j] = A[i]; newUintsIdxs[j] = i; j++; } } return (newUints, newUintsIdxs); } function intersect(uint256[] memory A, uint256[] memory B) internal pure returns (uint256[] memory, uint256[] memory, uint256[] memory) { uint256 length = A.length; bool[] memory includeMap = new bool[](length); uint256 newLength = 0; for (uint256 i = 0; i < length; i++) { if (contains(B, A[i])) { includeMap[i] = true; newLength++; } } uint256[] memory newUints = new uint256[](newLength); uint256[] memory newUintsAIdxs = new uint256[](newLength); uint256[] memory newUintsBIdxs = new uint256[](newLength); uint256 j = 0; for (uint256 i = 0; i < length; i++) { if (includeMap[i]) { newUints[j] = A[i]; newUintsAIdxs[j] = i; (newUintsBIdxs[j], ) = indexOf(B, A[i]); j++; } } return (newUints, newUintsAIdxs, newUintsBIdxs); } function isUnique(uint256[] memory A) internal pure returns (bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { (uint256 idx, bool isIn) = indexOf(A, A[i]); if (isIn && idx < i) { return false; } } return true; } } // File: openzeppelin-solidity/contracts/introspection/IERC165.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: openzeppelin-solidity/contracts/introspection/ERC165.sol pragma solidity ^0.5.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721.sol pragma solidity ^0.5.0; /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } // File: erc721o/contracts/Interfaces/IERC721O.sol pragma solidity ^0.5.4; contract IERC721O { // Token description function name() external view returns (string memory); function symbol() external view returns (string memory); function totalSupply() public view returns (uint256); function exists(uint256 _tokenId) public view returns (bool); function implementsERC721() public pure returns (bool); function tokenByIndex(uint256 _index) public view returns (uint256); function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId); function tokenURI(uint256 _tokenId) public view returns (string memory tokenUri); function getApproved(uint256 _tokenId) public view returns (address); function implementsERC721O() public pure returns (bool); function ownerOf(uint256 _tokenId) public view returns (address _owner); function balanceOf(address owner) public view returns (uint256); function balanceOf(address _owner, uint256 _tokenId) public view returns (uint256); function tokensOwned(address _owner) public view returns (uint256[] memory, uint256[] memory); // Non-Fungible Safe Transfer From function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public; // Non-Fungible Unsafe Transfer From function transferFrom(address _from, address _to, uint256 _tokenId) public; // Fungible Unsafe Transfer function transfer(address _to, uint256 _tokenId, uint256 _quantity) public; // Fungible Unsafe Transfer From function transferFrom(address _from, address _to, uint256 _tokenId, uint256 _quantity) public; // Fungible Safe Transfer From function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount, bytes memory _data) public; // Fungible Safe Batch Transfer From function safeBatchTransferFrom(address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts) public; function safeBatchTransferFrom(address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts, bytes memory _data) public; // Fungible Unsafe Batch Transfer From function batchTransferFrom(address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts) public; // Approvals function setApprovalForAll(address _operator, bool _approved) public; function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId, address _tokenOwner) public view returns (address); function isApprovedForAll(address _owner, address _operator) public view returns (bool isOperator); function isApprovedOrOwner(address _spender, address _owner, uint256 _tokenId) public view returns (bool); function permit(address _holder, address _spender, uint256 _nonce, uint256 _expiry, bool _allowed, bytes calldata _signature) external; // Composable function compose(uint256[] memory _tokenIds, uint256[] memory _tokenRatio, uint256 _quantity) public; function decompose(uint256 _portfolioId, uint256[] memory _tokenIds, uint256[] memory _tokenRatio, uint256 _quantity) public; function recompose(uint256 _portfolioId, uint256[] memory _initialTokenIds, uint256[] memory _initialTokenRatio, uint256[] memory _finalTokenIds, uint256[] memory _finalTokenRatio, uint256 _quantity) public; // Required Events event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event TransferWithQuantity(address indexed from, address indexed to, uint256 indexed tokenId, uint256 quantity); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); event BatchTransfer(address indexed from, address indexed to, uint256[] tokenTypes, uint256[] amounts); event Composition(uint256 portfolioId, uint256[] tokenIds, uint256[] tokenRatio); } // File: erc721o/contracts/Interfaces/IERC721OReceiver.sol pragma solidity ^0.5.4; /** * @title ERC721O token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721O contracts. */ contract IERC721OReceiver { /** * @dev Magic value to be returned upon successful reception of an amount of ERC721O tokens * ERC721O_RECEIVED = `bytes4(keccak256("onERC721OReceived(address,address,uint256,uint256,bytes)"))` = 0xf891ffe0 * ERC721O_BATCH_RECEIVED = `bytes4(keccak256("onERC721OBatchReceived(address,address,uint256[],uint256[],bytes)"))` = 0xd0e17c0b */ bytes4 constant internal ERC721O_RECEIVED = 0xf891ffe0; bytes4 constant internal ERC721O_BATCH_RECEIVED = 0xd0e17c0b; function onERC721OReceived( address _operator, address _from, uint256 tokenId, uint256 amount, bytes memory data ) public returns(bytes4); function onERC721OBatchReceived( address _operator, address _from, uint256[] memory _types, uint256[] memory _amounts, bytes memory _data ) public returns (bytes4); } // File: erc721o/contracts/Libs/ObjectsLib.sol pragma solidity ^0.5.4; library ObjectLib { // Libraries using SafeMath for uint256; enum Operations { ADD, SUB, REPLACE } // Constants regarding bin or chunk sizes for balance packing uint256 constant TYPES_BITS_SIZE = 32; // Max size of each object uint256 constant TYPES_PER_UINT256 = 256 / TYPES_BITS_SIZE; // Number of types per uint256 // // Objects and Tokens Functions // /** * @dev Return the bin number and index within that bin where ID is * @param _tokenId Object type * @return (Bin number, ID's index within that bin) */ function getTokenBinIndex(uint256 _tokenId) internal pure returns (uint256 bin, uint256 index) { bin = _tokenId * TYPES_BITS_SIZE / 256; index = _tokenId % TYPES_PER_UINT256; return (bin, index); } /** * @dev update the balance of a type provided in _binBalances * @param _binBalances Uint256 containing the balances of objects * @param _index Index of the object in the provided bin * @param _amount Value to update the type balance * @param _operation Which operation to conduct : * Operations.REPLACE : Replace type balance with _amount * Operations.ADD : ADD _amount to type balance * Operations.SUB : Substract _amount from type balance */ function updateTokenBalance( uint256 _binBalances, uint256 _index, uint256 _amount, Operations _operation) internal pure returns (uint256 newBinBalance) { uint256 objectBalance; if (_operation == Operations.ADD) { objectBalance = getValueInBin(_binBalances, _index); newBinBalance = writeValueInBin(_binBalances, _index, objectBalance.add(_amount)); } else if (_operation == Operations.SUB) { objectBalance = getValueInBin(_binBalances, _index); newBinBalance = writeValueInBin(_binBalances, _index, objectBalance.sub(_amount)); } else if (_operation == Operations.REPLACE) { newBinBalance = writeValueInBin(_binBalances, _index, _amount); } else { revert("Invalid operation"); // Bad operation } return newBinBalance; } /* * @dev return value in _binValue at position _index * @param _binValue uint256 containing the balances of TYPES_PER_UINT256 types * @param _index index at which to retrieve value * @return Value at given _index in _bin */ function getValueInBin(uint256 _binValue, uint256 _index) internal pure returns (uint256) { // Mask to retrieve data for a given binData uint256 mask = (uint256(1) << TYPES_BITS_SIZE) - 1; // Shift amount uint256 rightShift = 256 - TYPES_BITS_SIZE * (_index + 1); return (_binValue >> rightShift) & mask; } /** * @dev return the updated _binValue after writing _amount at _index * @param _binValue uint256 containing the balances of TYPES_PER_UINT256 types * @param _index Index at which to retrieve value * @param _amount Value to store at _index in _bin * @return Value at given _index in _bin */ function writeValueInBin(uint256 _binValue, uint256 _index, uint256 _amount) internal pure returns (uint256) { require(_amount < 2**TYPES_BITS_SIZE, "Amount to write in bin is too large"); // Mask to retrieve data for a given binData uint256 mask = (uint256(1) << TYPES_BITS_SIZE) - 1; // Shift amount uint256 leftShift = 256 - TYPES_BITS_SIZE * (_index + 1); return (_binValue & ~(mask << leftShift) ) | (_amount << leftShift); } } // File: erc721o/contracts/ERC721OBase.sol pragma solidity ^0.5.4; contract ERC721OBase is IERC721O, ERC165, IERC721 { // Libraries using ObjectLib for ObjectLib.Operations; using ObjectLib for uint256; // Array with all tokenIds uint256[] internal allTokens; // Packed balances mapping(address => mapping(uint256 => uint256)) internal packedTokenBalance; // Operators mapping(address => mapping(address => bool)) internal operators; // Keeps aprovals for tokens from owner to approved address // tokenApprovals[tokenId][owner] = approved mapping (uint256 => mapping (address => address)) internal tokenApprovals; // Token Id state mapping(uint256 => uint256) internal tokenTypes; uint256 constant internal INVALID = 0; uint256 constant internal POSITION = 1; uint256 constant internal PORTFOLIO = 2; // Interface constants bytes4 internal constant INTERFACE_ID_ERC721O = 0x12345678; // EIP712 constants bytes32 public DOMAIN_SEPARATOR; bytes32 public PERMIT_TYPEHASH; // mapping holds nonces for approval permissions // nonces[holder] => nonce mapping (address => uint) public nonces; modifier isOperatorOrOwner(address _from) { require((msg.sender == _from) || operators[_from][msg.sender], "msg.sender is neither _from nor operator"); _; } constructor() public { _registerInterface(INTERFACE_ID_ERC721O); // Calculate EIP712 constants DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,address verifyingContract)"), keccak256(bytes("ERC721o")), keccak256(bytes("1")), address(this) )); PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)"); } function implementsERC721O() public pure returns (bool) { return true; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { return tokenTypes[_tokenId] != INVALID; } /** * @dev return the _tokenId type' balance of _address * @param _address Address to query balance of * @param _tokenId type to query balance of * @return Amount of objects of a given type ID */ function balanceOf(address _address, uint256 _tokenId) public view returns (uint256) { (uint256 bin, uint256 index) = _tokenId.getTokenBinIndex(); return packedTokenBalance[_address][bin].getValueInBin(index); } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets Iterate through the list of existing tokens and return the indexes * and balances of the tokens owner by the user * @param _owner The adddress we are checking * @return indexes The tokenIds * @return balances The balances of each token */ function tokensOwned(address _owner) public view returns (uint256[] memory indexes, uint256[] memory balances) { uint256 numTokens = totalSupply(); uint256[] memory tokenIndexes = new uint256[](numTokens); uint256[] memory tempTokens = new uint256[](numTokens); uint256 count; for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = allTokens[i]; if (balanceOf(_owner, tokenId) > 0) { tempTokens[count] = balanceOf(_owner, tokenId); tokenIndexes[count] = tokenId; count++; } } // copy over the data to a correct size array uint256[] memory _ownedTokens = new uint256[](count); uint256[] memory _ownedTokensIndexes = new uint256[](count); for (uint256 i = 0; i < count; i++) { _ownedTokens[i] = tempTokens[i]; _ownedTokensIndexes[i] = tokenIndexes[i]; } return (_ownedTokensIndexes, _ownedTokens); } /** * @dev Will set _operator operator status to true or false * @param _operator Address to changes operator status. * @param _approved _operator's new operator status (true or false) */ function setApprovalForAll(address _operator, bool _approved) public { // Update operator status operators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /// @notice Approve for all by signature function permit(address _holder, address _spender, uint256 _nonce, uint256 _expiry, bool _allowed, bytes calldata _signature) external { // Calculate hash bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode( PERMIT_TYPEHASH, _holder, _spender, _nonce, _expiry, _allowed )) )); // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly bytes32 r; bytes32 s; uint8 v; bytes memory signature = _signature; assembly { r := mload(add(signature, 32)) s := mload(add(signature, 64)) v := byte(0, mload(add(signature, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } address recoveredAddress; // If the version is correct return the signer address if (v != 27 && v != 28) { recoveredAddress = address(0); } else { // solium-disable-next-line arg-overflow recoveredAddress = ecrecover(digest, v, r, s); } require(_holder != address(0), "Holder can't be zero address"); require(_holder == recoveredAddress, "Signer address is invalid"); require(_expiry == 0 || now <= _expiry, "Permission expired"); require(_nonce == nonces[_holder]++, "Nonce is invalid"); // Update operator status operators[_holder][_spender] = _allowed; emit ApprovalForAll(_holder, _spender, _allowed); } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { require(_to != msg.sender, "Can't approve to yourself"); tokenApprovals[_tokenId][msg.sender] = _to; emit Approval(msg.sender, _to, _tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId, address _tokenOwner) public view returns (address) { return tokenApprovals[_tokenId][_tokenOwner]; } /** * @dev Function that verifies whether _operator is an authorized operator of _tokenHolder. * @param _operator The address of the operator to query status of * @param _owner Address of the tokenHolder * @return A uint256 specifying the amount of tokens still available for the spender. */ function isApprovedForAll(address _owner, address _operator) public view returns (bool isOperator) { return operators[_owner][_operator]; } function isApprovedOrOwner( address _spender, address _owner, uint256 _tokenId ) public view returns (bool) { return ( _spender == _owner || getApproved(_tokenId, _owner) == _spender || isApprovedForAll(_owner, _spender) ); } function _updateTokenBalance( address _from, uint256 _tokenId, uint256 _amount, ObjectLib.Operations op ) internal { (uint256 bin, uint256 index) = _tokenId.getTokenBinIndex(); packedTokenBalance[_from][bin] = packedTokenBalance[_from][bin].updateTokenBalance( index, _amount, op ); } } // File: erc721o/contracts/ERC721OTransferable.sol pragma solidity ^0.5.4; contract ERC721OTransferable is ERC721OBase, ReentrancyGuard { // Libraries using Address for address; // safeTransfer constants bytes4 internal constant ERC721O_RECEIVED = 0xf891ffe0; bytes4 internal constant ERC721O_BATCH_RECEIVED = 0xd0e17c0b; function batchTransferFrom(address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts) public { // Batch Transfering _batchTransferFrom(_from, _to, _tokenIds, _amounts); } /** * @dev transfer objects from different tokenIds to specified address * @param _from The address to BatchTransfer objects from. * @param _to The address to batchTransfer objects to. * @param _tokenIds Array of tokenIds to update balance of * @param _amounts Array of amount of object per type to be transferred. * @param _data Data to pass to onERC721OReceived() function if recipient is contract * Note: Arrays should be sorted so that all tokenIds in a same bin are adjacent (more efficient). */ function safeBatchTransferFrom( address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts, bytes memory _data ) public nonReentrant { // Batch Transfering _batchTransferFrom(_from, _to, _tokenIds, _amounts); // Pass data if recipient is contract if (_to.isContract()) { bytes4 retval = IERC721OReceiver(_to).onERC721OBatchReceived( msg.sender, _from, _tokenIds, _amounts, _data ); require(retval == ERC721O_BATCH_RECEIVED); } } function safeBatchTransferFrom( address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts ) public { safeBatchTransferFrom(_from, _to, _tokenIds, _amounts, ""); } function transfer(address _to, uint256 _tokenId, uint256 _amount) public { _transferFrom(msg.sender, _to, _tokenId, _amount); } function transferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount) public { _transferFrom(_from, _to, _tokenId, _amount); } function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount) public { safeTransferFrom(_from, _to, _tokenId, _amount, ""); } function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount, bytes memory _data) public nonReentrant { _transferFrom(_from, _to, _tokenId, _amount); require( _checkAndCallSafeTransfer(_from, _to, _tokenId, _amount, _data), "Sent to a contract which is not an ERC721O receiver" ); } /** * @dev transfer objects from different tokenIds to specified address * @param _from The address to BatchTransfer objects from. * @param _to The address to batchTransfer objects to. * @param _tokenIds Array of tokenIds to update balance of * @param _amounts Array of amount of object per type to be transferred. * Note: Arrays should be sorted so that all tokenIds in a same bin are adjacent (more efficient). */ function _batchTransferFrom( address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts ) internal isOperatorOrOwner(_from) { // Requirements require(_tokenIds.length == _amounts.length, "Inconsistent array length between args"); require(_to != address(0), "Invalid to address"); // Number of transfers to execute uint256 nTransfer = _tokenIds.length; // Don't do useless calculations if (_from == _to) { for (uint256 i = 0; i < nTransfer; i++) { emit Transfer(_from, _to, _tokenIds[i]); emit TransferWithQuantity(_from, _to, _tokenIds[i], _amounts[i]); } return; } for (uint256 i = 0; i < nTransfer; i++) { require(_amounts[i] <= balanceOf(_from, _tokenIds[i]), "Quantity greater than from balance"); _updateTokenBalance(_from, _tokenIds[i], _amounts[i], ObjectLib.Operations.SUB); _updateTokenBalance(_to, _tokenIds[i], _amounts[i], ObjectLib.Operations.ADD); emit Transfer(_from, _to, _tokenIds[i]); emit TransferWithQuantity(_from, _to, _tokenIds[i], _amounts[i]); } // Emit batchTransfer event emit BatchTransfer(_from, _to, _tokenIds, _amounts); } function _transferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount) internal { require(isApprovedOrOwner(msg.sender, _from, _tokenId), "Not approved"); require(_amount <= balanceOf(_from, _tokenId), "Quantity greater than from balance"); require(_to != address(0), "Invalid to address"); _updateTokenBalance(_from, _tokenId, _amount, ObjectLib.Operations.SUB); _updateTokenBalance(_to, _tokenId, _amount, ObjectLib.Operations.ADD); emit Transfer(_from, _to, _tokenId); emit TransferWithQuantity(_from, _to, _tokenId, _amount); } function _checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, uint256 _amount, bytes memory _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = IERC721OReceiver(_to).onERC721OReceived(msg.sender, _from, _tokenId, _amount, _data); return(retval == ERC721O_RECEIVED); } } // File: erc721o/contracts/ERC721OMintable.sol pragma solidity ^0.5.4; contract ERC721OMintable is ERC721OTransferable { // Libraries using LibPosition for bytes32; // Internal functions function _mint(uint256 _tokenId, address _to, uint256 _supply) internal { // If the token doesn't exist, add it to the tokens array if (!exists(_tokenId)) { tokenTypes[_tokenId] = POSITION; allTokens.push(_tokenId); } _updateTokenBalance(_to, _tokenId, _supply, ObjectLib.Operations.ADD); emit Transfer(address(0), _to, _tokenId); emit TransferWithQuantity(address(0), _to, _tokenId, _supply); } function _burn(address _tokenOwner, uint256 _tokenId, uint256 _quantity) internal { uint256 ownerBalance = balanceOf(_tokenOwner, _tokenId); require(ownerBalance >= _quantity, "TOKEN_MINTER:NOT_ENOUGH_POSITIONS"); _updateTokenBalance(_tokenOwner, _tokenId, _quantity, ObjectLib.Operations.SUB); emit Transfer(_tokenOwner, address(0), _tokenId); emit TransferWithQuantity(_tokenOwner, address(0), _tokenId, _quantity); } function _mint(address _buyer, address _seller, bytes32 _derivativeHash, uint256 _quantity) internal { _mintLong(_buyer, _derivativeHash, _quantity); _mintShort(_seller, _derivativeHash, _quantity); } function _mintLong(address _buyer, bytes32 _derivativeHash, uint256 _quantity) internal { uint256 longTokenId = _derivativeHash.getLongTokenId(); _mint(longTokenId, _buyer, _quantity); } function _mintShort(address _seller, bytes32 _derivativeHash, uint256 _quantity) internal { uint256 shortTokenId = _derivativeHash.getShortTokenId(); _mint(shortTokenId, _seller, _quantity); } function _registerPortfolio(uint256 _portfolioId, uint256[] memory _tokenIds, uint256[] memory _tokenRatio) internal { if (!exists(_portfolioId)) { tokenTypes[_portfolioId] = PORTFOLIO; emit Composition(_portfolioId, _tokenIds, _tokenRatio); } } } // File: erc721o/contracts/ERC721OComposable.sol pragma solidity ^0.5.4; contract ERC721OComposable is ERC721OMintable { // Libraries using UintArray for uint256[]; using SafeMath for uint256; function compose(uint256[] memory _tokenIds, uint256[] memory _tokenRatio, uint256 _quantity) public { require(_tokenIds.length == _tokenRatio.length, "TOKEN_MINTER:TOKEN_IDS_AND_RATIO_LENGTH_DOES_NOT_MATCH"); require(_quantity > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_tokenIds.length > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_tokenIds.isUnique(), "TOKEN_MINTER:TOKEN_IDS_NOT_UNIQUE"); for (uint256 i = 0; i < _tokenIds.length; i++) { _burn(msg.sender, _tokenIds[i], _tokenRatio[i].mul(_quantity)); } uint256 portfolioId = uint256(keccak256(abi.encodePacked( _tokenIds, _tokenRatio ))); _registerPortfolio(portfolioId, _tokenIds, _tokenRatio); _mint(portfolioId, msg.sender, _quantity); } function decompose(uint256 _portfolioId, uint256[] memory _tokenIds, uint256[] memory _tokenRatio, uint256 _quantity) public { require(_tokenIds.length == _tokenRatio.length, "TOKEN_MINTER:TOKEN_IDS_AND_RATIO_LENGTH_DOES_NOT_MATCH"); require(_quantity > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_tokenIds.length > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_tokenIds.isUnique(), "TOKEN_MINTER:TOKEN_IDS_NOT_UNIQUE"); uint256 portfolioId = uint256(keccak256(abi.encodePacked( _tokenIds, _tokenRatio ))); require(portfolioId == _portfolioId, "TOKEN_MINTER:WRONG_PORTFOLIO_ID"); _burn(msg.sender, _portfolioId, _quantity); for (uint256 i = 0; i < _tokenIds.length; i++) { _mint(_tokenIds[i], msg.sender, _tokenRatio[i].mul(_quantity)); } } function recompose( uint256 _portfolioId, uint256[] memory _initialTokenIds, uint256[] memory _initialTokenRatio, uint256[] memory _finalTokenIds, uint256[] memory _finalTokenRatio, uint256 _quantity ) public { require(_initialTokenIds.length == _initialTokenRatio.length, "TOKEN_MINTER:INITIAL_TOKEN_IDS_AND_RATIO_LENGTH_DOES_NOT_MATCH"); require(_finalTokenIds.length == _finalTokenRatio.length, "TOKEN_MINTER:FINAL_TOKEN_IDS_AND_RATIO_LENGTH_DOES_NOT_MATCH"); require(_quantity > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_initialTokenIds.length > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_finalTokenIds.length > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_initialTokenIds.isUnique(), "TOKEN_MINTER:TOKEN_IDS_NOT_UNIQUE"); require(_finalTokenIds.isUnique(), "TOKEN_MINTER:TOKEN_IDS_NOT_UNIQUE"); uint256 oldPortfolioId = uint256(keccak256(abi.encodePacked( _initialTokenIds, _initialTokenRatio ))); require(oldPortfolioId == _portfolioId, "TOKEN_MINTER:WRONG_PORTFOLIO_ID"); _burn(msg.sender, _portfolioId, _quantity); _removedIds(_initialTokenIds, _initialTokenRatio, _finalTokenIds, _finalTokenRatio, _quantity); _addedIds(_initialTokenIds, _initialTokenRatio, _finalTokenIds, _finalTokenRatio, _quantity); _keptIds(_initialTokenIds, _initialTokenRatio, _finalTokenIds, _finalTokenRatio, _quantity); uint256 newPortfolioId = uint256(keccak256(abi.encodePacked( _finalTokenIds, _finalTokenRatio ))); _registerPortfolio(newPortfolioId, _finalTokenIds, _finalTokenRatio); _mint(newPortfolioId, msg.sender, _quantity); } function _removedIds( uint256[] memory _initialTokenIds, uint256[] memory _initialTokenRatio, uint256[] memory _finalTokenIds, uint256[] memory _finalTokenRatio, uint256 _quantity ) private { (uint256[] memory removedIds, uint256[] memory removedIdsIdxs) = _initialTokenIds.difference(_finalTokenIds); for (uint256 i = 0; i < removedIds.length; i++) { uint256 index = removedIdsIdxs[i]; _mint(_initialTokenIds[index], msg.sender, _initialTokenRatio[index].mul(_quantity)); } _finalTokenRatio; } function _addedIds( uint256[] memory _initialTokenIds, uint256[] memory _initialTokenRatio, uint256[] memory _finalTokenIds, uint256[] memory _finalTokenRatio, uint256 _quantity ) private { (uint256[] memory addedIds, uint256[] memory addedIdsIdxs) = _finalTokenIds.difference(_initialTokenIds); for (uint256 i = 0; i < addedIds.length; i++) { uint256 index = addedIdsIdxs[i]; _burn(msg.sender, _finalTokenIds[index], _finalTokenRatio[index].mul(_quantity)); } _initialTokenRatio; } function _keptIds( uint256[] memory _initialTokenIds, uint256[] memory _initialTokenRatio, uint256[] memory _finalTokenIds, uint256[] memory _finalTokenRatio, uint256 _quantity ) private { (uint256[] memory keptIds, uint256[] memory keptInitialIdxs, uint256[] memory keptFinalIdxs) = _initialTokenIds.intersect(_finalTokenIds); for (uint256 i = 0; i < keptIds.length; i++) { uint256 initialIndex = keptInitialIdxs[i]; uint256 finalIndex = keptFinalIdxs[i]; if (_initialTokenRatio[initialIndex] > _finalTokenRatio[finalIndex]) { uint256 diff = _initialTokenRatio[initialIndex] - _finalTokenRatio[finalIndex]; _mint(_initialTokenIds[initialIndex], msg.sender, diff.mul(_quantity)); } else if (_initialTokenRatio[initialIndex] < _finalTokenRatio[finalIndex]) { uint256 diff = _finalTokenRatio[finalIndex] - _initialTokenRatio[initialIndex]; _burn(msg.sender, _initialTokenIds[initialIndex], diff.mul(_quantity)); } } } } // File: erc721o/contracts/Libs/UintsLib.sol pragma solidity ^0.5.4; library UintsLib { function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } } // File: erc721o/contracts/ERC721OBackwardCompatible.sol pragma solidity ^0.5.4; contract ERC721OBackwardCompatible is ERC721OComposable { using UintsLib for uint256; // Interface constants bytes4 internal constant INTERFACE_ID_ERC721 = 0x80ac58cd; bytes4 internal constant INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; bytes4 internal constant INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; // Reciever constants bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; // Metadata URI string internal baseTokenURI; constructor(string memory _baseTokenURI) public ERC721OBase() { baseTokenURI = _baseTokenURI; _registerInterface(INTERFACE_ID_ERC721); _registerInterface(INTERFACE_ID_ERC721_ENUMERABLE); _registerInterface(INTERFACE_ID_ERC721_METADATA); } // ERC721 compatibility function implementsERC721() public pure returns (bool) { return true; } /** * @dev Gets the owner of a given NFT * @param _tokenId uint256 representing the unique token identifier * @return address the owner of the token */ function ownerOf(uint256 _tokenId) public view returns (address) { if (exists(_tokenId)) { return address(this); } return address(0); } /** * @dev Gets the number of tokens owned by the address we are checking * @param _owner The adddress we are checking * @return balance The unique amount of tokens owned */ function balanceOf(address _owner) public view returns (uint256 balance) { (, uint256[] memory tokens) = tokensOwned(_owner); return tokens.length; } // ERC721 - Enumerable compatibility /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId) { (, uint256[] memory tokens) = tokensOwned(_owner); require(_index < tokens.length); return tokens[_index]; } // ERC721 - Metadata compatibility function tokenURI(uint256 _tokenId) public view returns (string memory tokenUri) { require(exists(_tokenId), "Token doesn't exist"); return string(abi.encodePacked( baseTokenURI, _tokenId.uint2str(), ".json" )); } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { if (exists(_tokenId)) { return address(this); } return address(0); } function safeTransferFrom(address _from, address _to, uint256 _tokenId) public { safeTransferFrom(_from, _to, _tokenId, ""); } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public nonReentrant { _transferFrom(_from, _to, _tokenId, 1); require( _checkAndCallSafeTransfer(_from, _to, _tokenId, _data), "Sent to a contract which is not an ERC721 receiver" ); } function transferFrom(address _from, address _to, uint256 _tokenId) public { _transferFrom(_from, _to, _tokenId, 1); } /** * @dev Internal function to invoke `onERC721Received` on a target address * The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function _checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes memory _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = IERC721Receiver(_to).onERC721Received( msg.sender, _from, _tokenId, _data ); return (retval == ERC721_RECEIVED); } } // File: contracts/TokenMinter.sol pragma solidity 0.5.16; /// @title Opium.TokenMinter contract implements ERC721O token standard for minting, burning and transferring position tokens contract TokenMinter is ERC721OBackwardCompatible, UsingRegistry { /// @notice Calls constructors of super-contracts /// @param _baseTokenURI string URI for token explorers /// @param _registry address Address of Opium.registry constructor(string memory _baseTokenURI, address _registry) public ERC721OBackwardCompatible(_baseTokenURI) UsingRegistry(_registry) {} /// @notice Mints LONG and SHORT position tokens /// @param _buyer address Address of LONG position receiver /// @param _seller address Address of SHORT position receiver /// @param _derivativeHash bytes32 Hash of derivative (ticker) of position /// @param _quantity uint256 Quantity of positions to mint function mint(address _buyer, address _seller, bytes32 _derivativeHash, uint256 _quantity) external onlyCore { _mint(_buyer, _seller, _derivativeHash, _quantity); } /// @notice Mints only LONG position tokens for "pooled" derivatives /// @param _buyer address Address of LONG position receiver /// @param _derivativeHash bytes32 Hash of derivative (ticker) of position /// @param _quantity uint256 Quantity of positions to mint function mint(address _buyer, bytes32 _derivativeHash, uint256 _quantity) external onlyCore { _mintLong(_buyer, _derivativeHash, _quantity); } /// @notice Burns position tokens /// @param _tokenOwner address Address of tokens owner /// @param _tokenId uint256 tokenId of positions to burn /// @param _quantity uint256 Quantity of positions to burn function burn(address _tokenOwner, uint256 _tokenId, uint256 _quantity) external onlyCore { _burn(_tokenOwner, _tokenId, _quantity); } /// @notice ERC721 interface compatible function for position token name retrieving /// @return Returns name of token function name() external view returns (string memory) { return "Opium Network Position Token"; } /// @notice ERC721 interface compatible function for position token symbol retrieving /// @return Returns symbol of token function symbol() external view returns (string memory) { return "ONP"; } /// VIEW FUNCTIONS /// @notice Checks whether _spender is approved to spend tokens on _owners behalf or owner itself /// @param _spender address Address of spender /// @param _owner address Address of owner /// @param _tokenId address tokenId of interest /// @return Returns whether _spender is approved to spend tokens function isApprovedOrOwner( address _spender, address _owner, uint256 _tokenId ) public view returns (bool) { return ( _spender == _owner || getApproved(_tokenId, _owner) == _spender || isApprovedForAll(_owner, _spender) || isOpiumSpender(_spender) ); } /// @notice Checks whether _spender is Opium.TokenSpender /// @return Returns whether _spender is Opium.TokenSpender function isOpiumSpender(address _spender) public view returns (bool) { return _spender == registry.getTokenSpender(); } } // File: contracts/Errors/OracleAggregatorErrors.sol pragma solidity 0.5.16; contract OracleAggregatorErrors { string constant internal ERROR_ORACLE_AGGREGATOR_NOT_ENOUGH_ETHER = "ORACLE_AGGREGATOR:NOT_ENOUGH_ETHER"; string constant internal ERROR_ORACLE_AGGREGATOR_QUERY_WAS_ALREADY_MADE = "ORACLE_AGGREGATOR:QUERY_WAS_ALREADY_MADE"; string constant internal ERROR_ORACLE_AGGREGATOR_DATA_DOESNT_EXIST = "ORACLE_AGGREGATOR:DATA_DOESNT_EXIST"; string constant internal ERROR_ORACLE_AGGREGATOR_DATA_ALREADY_EXIST = "ORACLE_AGGREGATOR:DATA_ALREADY_EXIST"; } // File: contracts/Interface/IOracleId.sol pragma solidity 0.5.16; /// @title Opium.Interface.IOracleId contract is an interface that every oracleId should implement interface IOracleId { /// @notice Requests data from `oracleId` one time /// @param timestamp uint256 Timestamp at which data are needed function fetchData(uint256 timestamp) external payable; /// @notice Requests data from `oracleId` multiple times /// @param timestamp uint256 Timestamp at which data are needed for the first time /// @param period uint256 Period in seconds between multiple timestamps /// @param times uint256 How many timestamps are requested function recursivelyFetchData(uint256 timestamp, uint256 period, uint256 times) external payable; /// @notice Requests and returns price in ETH for one request. This function could be called as `view` function. Oraclize API for price calculations restricts making this function as view. /// @return fetchPrice uint256 Price of one data request in ETH function calculateFetchPrice() external returns (uint256 fetchPrice); // Event with oracleId metadata JSON string (for DIB.ONE derivative explorer) event MetadataSet(string metadata); } // File: contracts/OracleAggregator.sol pragma solidity 0.5.16; /// @title Opium.OracleAggregator contract requests and caches the data from `oracleId`s and provides them to the Core for positions execution contract OracleAggregator is OracleAggregatorErrors, ReentrancyGuard { using SafeMath for uint256; // Storage for the `oracleId` results // dataCache[oracleId][timestamp] => data mapping (address => mapping(uint256 => uint256)) public dataCache; // Flags whether data were provided // dataExist[oracleId][timestamp] => bool mapping (address => mapping(uint256 => bool)) public dataExist; // Flags whether data were requested // dataRequested[oracleId][timestamp] => bool mapping (address => mapping(uint256 => bool)) public dataRequested; // MODIFIERS /// @notice Checks whether enough ETH were provided withing data request to proceed /// @param oracleId address Address of the `oracleId` smart contract /// @param times uint256 How many times the `oracleId` is being requested modifier enoughEtherProvided(address oracleId, uint256 times) { // Calling Opium.IOracleId function to get the data fetch price per one request uint256 oneTimePrice = calculateFetchPrice(oracleId); // Checking if enough ether was provided for `times` amount of requests require(msg.value >= oneTimePrice.mul(times), ERROR_ORACLE_AGGREGATOR_NOT_ENOUGH_ETHER); _; } // PUBLIC FUNCTIONS /// @notice Requests data from `oracleId` one time /// @param oracleId address Address of the `oracleId` smart contract /// @param timestamp uint256 Timestamp at which data are needed function fetchData(address oracleId, uint256 timestamp) public payable nonReentrant enoughEtherProvided(oracleId, 1) { // Check if was not requested before and mark as requested _registerQuery(oracleId, timestamp); // Call the `oracleId` contract and transfer ETH IOracleId(oracleId).fetchData.value(msg.value)(timestamp); } /// @notice Requests data from `oracleId` multiple times /// @param oracleId address Address of the `oracleId` smart contract /// @param timestamp uint256 Timestamp at which data are needed for the first time /// @param period uint256 Period in seconds between multiple timestamps /// @param times uint256 How many timestamps are requested function recursivelyFetchData(address oracleId, uint256 timestamp, uint256 period, uint256 times) public payable nonReentrant enoughEtherProvided(oracleId, times) { // Check if was not requested before and mark as requested in loop for each timestamp for (uint256 i = 0; i < times; i++) { _registerQuery(oracleId, timestamp + period * i); } // Call the `oracleId` contract and transfer ETH IOracleId(oracleId).recursivelyFetchData.value(msg.value)(timestamp, period, times); } /// @notice Receives and caches data from `msg.sender` /// @param timestamp uint256 Timestamp of data /// @param data uint256 Data itself function __callback(uint256 timestamp, uint256 data) public { // Don't allow to push data twice require(!dataExist[msg.sender][timestamp], ERROR_ORACLE_AGGREGATOR_DATA_ALREADY_EXIST); // Saving data dataCache[msg.sender][timestamp] = data; // Flagging that data were received dataExist[msg.sender][timestamp] = true; } /// @notice Requests and returns price in ETH for one request. This function could be called as `view` function. Oraclize API for price calculations restricts making this function as view. /// @param oracleId address Address of the `oracleId` smart contract /// @return fetchPrice uint256 Price of one data request in ETH function calculateFetchPrice(address oracleId) public returns(uint256 fetchPrice) { fetchPrice = IOracleId(oracleId).calculateFetchPrice(); } // PRIVATE FUNCTIONS /// @notice Checks if data was not requested and provided before and marks as requested /// @param oracleId address Address of the `oracleId` smart contract /// @param timestamp uint256 Timestamp at which data are requested function _registerQuery(address oracleId, uint256 timestamp) private { // Check if data was not requested and provided yet require(!dataRequested[oracleId][timestamp] && !dataExist[oracleId][timestamp], ERROR_ORACLE_AGGREGATOR_QUERY_WAS_ALREADY_MADE); // Mark as requested dataRequested[oracleId][timestamp] = true; } // VIEW FUNCTIONS /// @notice Returns cached data if they exist, or reverts with an error /// @param oracleId address Address of the `oracleId` smart contract /// @param timestamp uint256 Timestamp at which data were requested /// @return dataResult uint256 Cached data provided by `oracleId` function getData(address oracleId, uint256 timestamp) public view returns(uint256 dataResult) { // Check if Opium.OracleAggregator has data require(hasData(oracleId, timestamp), ERROR_ORACLE_AGGREGATOR_DATA_DOESNT_EXIST); // Return cached data dataResult = dataCache[oracleId][timestamp]; } /// @notice Getter for dataExist mapping /// @param oracleId address Address of the `oracleId` smart contract /// @param timestamp uint256 Timestamp at which data were requested /// @param result bool Returns whether data were provided already function hasData(address oracleId, uint256 timestamp) public view returns(bool result) { return dataExist[oracleId][timestamp]; } } // File: contracts/Errors/SyntheticAggregatorErrors.sol pragma solidity 0.5.16; contract SyntheticAggregatorErrors { string constant internal ERROR_SYNTHETIC_AGGREGATOR_DERIVATIVE_HASH_NOT_MATCH = "SYNTHETIC_AGGREGATOR:DERIVATIVE_HASH_NOT_MATCH"; string constant internal ERROR_SYNTHETIC_AGGREGATOR_WRONG_MARGIN = "SYNTHETIC_AGGREGATOR:WRONG_MARGIN"; string constant internal ERROR_SYNTHETIC_AGGREGATOR_COMMISSION_TOO_BIG = "SYNTHETIC_AGGREGATOR:COMMISSION_TOO_BIG"; } // File: contracts/SyntheticAggregator.sol pragma solidity 0.5.16; /// @notice Opium.SyntheticAggregator contract initialized, identifies and caches syntheticId sensitive data contract SyntheticAggregator is SyntheticAggregatorErrors, LibDerivative, LibCommission, ReentrancyGuard { // Emitted when new ticker is initialized event Create(Derivative derivative, bytes32 derivativeHash); // Enum for types of syntheticId // Invalid - syntheticId is not initialized yet // NotPool - syntheticId with p2p logic // Pool - syntheticId with pooled logic enum SyntheticTypes { Invalid, NotPool, Pool } // Cache of buyer margin by ticker // buyerMarginByHash[derivativeHash] = buyerMargin mapping (bytes32 => uint256) public buyerMarginByHash; // Cache of seller margin by ticker // sellerMarginByHash[derivativeHash] = sellerMargin mapping (bytes32 => uint256) public sellerMarginByHash; // Cache of type by ticker // typeByHash[derivativeHash] = type mapping (bytes32 => SyntheticTypes) public typeByHash; // Cache of commission by ticker // commissionByHash[derivativeHash] = commission mapping (bytes32 => uint256) public commissionByHash; // Cache of author addresses by ticker // authorAddressByHash[derivativeHash] = authorAddress mapping (bytes32 => address) public authorAddressByHash; // PUBLIC FUNCTIONS /// @notice Initializes ticker, if was not initialized and returns `syntheticId` author commission from cache /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself /// @return commission uint256 Synthetic author commission function getAuthorCommission(bytes32 _derivativeHash, Derivative memory _derivative) public nonReentrant returns (uint256 commission) { // Initialize derivative if wasn't initialized before _initDerivative(_derivativeHash, _derivative); commission = commissionByHash[_derivativeHash]; } /// @notice Initializes ticker, if was not initialized and returns `syntheticId` author address from cache /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself /// @return authorAddress address Synthetic author address function getAuthorAddress(bytes32 _derivativeHash, Derivative memory _derivative) public nonReentrant returns (address authorAddress) { // Initialize derivative if wasn't initialized before _initDerivative(_derivativeHash, _derivative); authorAddress = authorAddressByHash[_derivativeHash]; } /// @notice Initializes ticker, if was not initialized and returns buyer and seller margin from cache /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself /// @return buyerMargin uint256 Margin of buyer /// @return sellerMargin uint256 Margin of seller function getMargin(bytes32 _derivativeHash, Derivative memory _derivative) public nonReentrant returns (uint256 buyerMargin, uint256 sellerMargin) { // If it's a pool, just return margin from syntheticId contract if (_isPool(_derivativeHash, _derivative)) { return IDerivativeLogic(_derivative.syntheticId).getMargin(_derivative); } // Initialize derivative if wasn't initialized before _initDerivative(_derivativeHash, _derivative); // Check if margins for _derivativeHash were already cached buyerMargin = buyerMarginByHash[_derivativeHash]; sellerMargin = sellerMarginByHash[_derivativeHash]; } /// @notice Checks whether `syntheticId` implements pooled logic /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself /// @return result bool Returns whether synthetic implements pooled logic function isPool(bytes32 _derivativeHash, Derivative memory _derivative) public nonReentrant returns (bool result) { result = _isPool(_derivativeHash, _derivative); } // PRIVATE FUNCTIONS /// @notice Initializes ticker, if was not initialized and returns whether `syntheticId` implements pooled logic /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself /// @return result bool Returns whether synthetic implements pooled logic function _isPool(bytes32 _derivativeHash, Derivative memory _derivative) private returns (bool result) { // Initialize derivative if wasn't initialized before _initDerivative(_derivativeHash, _derivative); result = typeByHash[_derivativeHash] == SyntheticTypes.Pool; } /// @notice Initializes ticker: caches syntheticId type, margin, author address and commission /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself function _initDerivative(bytes32 _derivativeHash, Derivative memory _derivative) private { // Check if type for _derivativeHash was already cached SyntheticTypes syntheticType = typeByHash[_derivativeHash]; // Type could not be Invalid, thus this condition says us that type was not cached before if (syntheticType != SyntheticTypes.Invalid) { return; } // For security reasons we calculate hash of provided _derivative bytes32 derivativeHash = getDerivativeHash(_derivative); require(derivativeHash == _derivativeHash, ERROR_SYNTHETIC_AGGREGATOR_DERIVATIVE_HASH_NOT_MATCH); // POOL // Get isPool from SyntheticId bool result = IDerivativeLogic(_derivative.syntheticId).isPool(); // Cache type returned from synthetic typeByHash[derivativeHash] = result ? SyntheticTypes.Pool : SyntheticTypes.NotPool; // MARGIN // Get margin from SyntheticId (uint256 buyerMargin, uint256 sellerMargin) = IDerivativeLogic(_derivative.syntheticId).getMargin(_derivative); // We are not allowing both margins to be equal to 0 require(buyerMargin != 0 || sellerMargin != 0, ERROR_SYNTHETIC_AGGREGATOR_WRONG_MARGIN); // Cache margins returned from synthetic buyerMarginByHash[derivativeHash] = buyerMargin; sellerMarginByHash[derivativeHash] = sellerMargin; // AUTHOR ADDRESS // Cache author address returned from synthetic authorAddressByHash[derivativeHash] = IDerivativeLogic(_derivative.syntheticId).getAuthorAddress(); // AUTHOR COMMISSION // Get commission from syntheticId uint256 commission = IDerivativeLogic(_derivative.syntheticId).getAuthorCommission(); // Check if commission is not set > 100% require(commission <= COMMISSION_BASE, ERROR_SYNTHETIC_AGGREGATOR_COMMISSION_TOO_BIG); // Cache commission commissionByHash[derivativeHash] = commission; // If we are here, this basically means this ticker was not used before, so we emit an event for Dapps developers about new ticker (derivative) and it's hash emit Create(_derivative, derivativeHash); } } // File: contracts/Lib/Whitelisted.sol pragma solidity 0.5.16; /// @title Opium.Lib.Whitelisted contract implements whitelist with modifier to restrict access to only whitelisted addresses contract Whitelisted { // Whitelist array address[] internal whitelist; /// @notice This modifier restricts access to functions, which could be called only by whitelisted addresses modifier onlyWhitelisted() { // Allowance flag bool allowed = false; // Going through whitelisted addresses array uint256 whitelistLength = whitelist.length; for (uint256 i = 0; i < whitelistLength; i++) { // If `msg.sender` is met within whitelisted addresses, raise the flag and exit the loop if (whitelist[i] == msg.sender) { allowed = true; break; } } // Check if flag was raised require(allowed, "Only whitelisted allowed"); _; } /// @notice Getter for whitelisted addresses array /// @return Array of whitelisted addresses function getWhitelist() public view returns (address[] memory) { return whitelist; } } // File: contracts/Lib/WhitelistedWithGovernance.sol pragma solidity 0.5.16; /// @title Opium.Lib.WhitelistedWithGovernance contract implements Opium.Lib.Whitelisted and adds governance for whitelist controlling contract WhitelistedWithGovernance is Whitelisted { // Emitted when new governor is set event GovernorSet(address governor); // Emitted when new whitelist is proposed event Proposed(address[] whitelist); // Emitted when proposed whitelist is committed (set) event Committed(address[] whitelist); // Proposal life timelock interval uint256 public timeLockInterval; // Governor address address public governor; // Timestamp of last proposal uint256 public proposalTime; // Proposed whitelist address[] public proposedWhitelist; /// @notice This modifier restricts access to functions, which could be called only by governor modifier onlyGovernor() { require(msg.sender == governor, "Only governor allowed"); _; } /// @notice Contract constructor /// @param _timeLockInterval uint256 Initial value for timelock interval /// @param _governor address Initial value for governor constructor(uint256 _timeLockInterval, address _governor) public { timeLockInterval = _timeLockInterval; governor = _governor; emit GovernorSet(governor); } /// @notice Calling this function governor could propose new whitelist addresses array. Also it allows to initialize first whitelist if it was not initialized yet. function proposeWhitelist(address[] memory _whitelist) public onlyGovernor { // Restrict empty proposals require(_whitelist.length != 0, "Can't be empty"); // Consider empty whitelist as not initialized, as proposing of empty whitelists is not allowed // If whitelist has never been initialized, we set whitelist right away without proposal if (whitelist.length == 0) { whitelist = _whitelist; emit Committed(_whitelist); // Otherwise save current time as timestamp of proposal, save proposed whitelist and emit event } else { proposalTime = now; proposedWhitelist = _whitelist; emit Proposed(_whitelist); } } /// @notice Calling this function governor commits proposed whitelist if timelock interval of proposal was passed function commitWhitelist() public onlyGovernor { // Check if proposal was made require(proposalTime != 0, "Didn't proposed yet"); // Check if timelock interval was passed require((proposalTime + timeLockInterval) < now, "Can't commit yet"); // Set new whitelist and emit event whitelist = proposedWhitelist; emit Committed(whitelist); // Reset proposal time lock proposalTime = 0; } /// @notice This function allows governor to transfer governance to a new governor and emits event /// @param _governor address Address of new governor function setGovernor(address _governor) public onlyGovernor { require(_governor != address(0), "Can't set zero address"); governor = _governor; emit GovernorSet(governor); } } // File: contracts/Lib/WhitelistedWithGovernanceAndChangableTimelock.sol pragma solidity 0.5.16; /// @notice Opium.Lib.WhitelistedWithGovernanceAndChangableTimelock contract implements Opium.Lib.WhitelistedWithGovernance and adds possibility for governor to change timelock interval within timelock interval contract WhitelistedWithGovernanceAndChangableTimelock is WhitelistedWithGovernance { // Emitted when new timelock is proposed event Proposed(uint256 timelock); // Emitted when new timelock is committed (set) event Committed(uint256 timelock); // Timestamp of last timelock proposal uint256 public timeLockProposalTime; // Proposed timelock uint256 public proposedTimeLock; /// @notice Calling this function governor could propose new timelock /// @param _timelock uint256 New timelock value function proposeTimelock(uint256 _timelock) public onlyGovernor { timeLockProposalTime = now; proposedTimeLock = _timelock; emit Proposed(_timelock); } /// @notice Calling this function governor could commit previously proposed new timelock if timelock interval of proposal was passed function commitTimelock() public onlyGovernor { // Check if proposal was made require(timeLockProposalTime != 0, "Didn't proposed yet"); // Check if timelock interval was passed require((timeLockProposalTime + timeLockInterval) < now, "Can't commit yet"); // Set new timelock and emit event timeLockInterval = proposedTimeLock; emit Committed(proposedTimeLock); // Reset timelock time lock timeLockProposalTime = 0; } } // File: contracts/TokenSpender.sol pragma solidity 0.5.16; /// @title Opium.TokenSpender contract holds users ERC20 approvals and allows whitelisted contracts to use tokens contract TokenSpender is WhitelistedWithGovernanceAndChangableTimelock { using SafeERC20 for IERC20; // Initial timelock period uint256 public constant WHITELIST_TIMELOCK = 1 hours; /// @notice Calls constructors of super-contracts /// @param _governor address Address of governor, who is allowed to adjust whitelist constructor(address _governor) public WhitelistedWithGovernance(WHITELIST_TIMELOCK, _governor) {} /// @notice Using this function whitelisted contracts could call ERC20 transfers /// @param token IERC20 Instance of token /// @param from address Address from which tokens are transferred /// @param to address Address of tokens receiver /// @param amount uint256 Amount of tokens to be transferred function claimTokens(IERC20 token, address from, address to, uint256 amount) external onlyWhitelisted { token.safeTransferFrom(from, to, amount); } /// @notice Using this function whitelisted contracts could call ERC721O transfers /// @param token IERC721O Instance of token /// @param from address Address from which tokens are transferred /// @param to address Address of tokens receiver /// @param tokenId uint256 Token ID to be transferred /// @param amount uint256 Amount of tokens to be transferred function claimPositions(IERC721O token, address from, address to, uint256 tokenId, uint256 amount) external onlyWhitelisted { token.safeTransferFrom(from, to, tokenId, amount); } } // File: contracts/Core.sol pragma solidity 0.5.16; /// @title Opium.Core contract creates positions, holds and distributes margin at the maturity contract Core is LibDerivative, LibCommission, UsingRegistry, CoreErrors, ReentrancyGuard { using SafeMath for uint256; using LibPosition for bytes32; using SafeERC20 for IERC20; // Emitted when Core creates new position event Created(address buyer, address seller, bytes32 derivativeHash, uint256 quantity); // Emitted when Core executes positions event Executed(address tokenOwner, uint256 tokenId, uint256 quantity); // Emitted when Core cancels ticker for the first time event Canceled(bytes32 derivativeHash); // Period of time after which ticker could be canceled if no data was provided to the `oracleId` uint256 public constant NO_DATA_CANCELLATION_PERIOD = 2 weeks; // Vaults for pools // This mapping holds balances of pooled positions // poolVaults[syntheticAddress][tokenAddress] => availableBalance mapping (address => mapping(address => uint256)) public poolVaults; // Vaults for fees // This mapping holds balances of fee recipients // feesVaults[feeRecipientAddress][tokenAddress] => availableBalance mapping (address => mapping(address => uint256)) public feesVaults; // Hashes of cancelled tickers mapping (bytes32 => bool) public cancelled; /// @notice Calls Core.Lib.UsingRegistry constructor constructor(address _registry) public UsingRegistry(_registry) {} // PUBLIC FUNCTIONS /// @notice This function allows fee recipients to withdraw their fees /// @param _tokenAddress address Address of an ERC20 token to withdraw function withdrawFee(address _tokenAddress) public nonReentrant { uint256 balance = feesVaults[msg.sender][_tokenAddress]; feesVaults[msg.sender][_tokenAddress] = 0; IERC20(_tokenAddress).safeTransfer(msg.sender, balance); } /// @notice Creates derivative contracts (positions) /// @param _derivative Derivative Derivative definition /// @param _quantity uint256 Quantity of derivatives to be created /// @param _addresses address[2] Addresses of buyer and seller /// [0] - buyer address /// [1] - seller address - if seller is set to `address(0)`, consider as pooled position function create(Derivative memory _derivative, uint256 _quantity, address[2] memory _addresses) public nonReentrant { if (_addresses[1] == address(0)) { _createPooled(_derivative, _quantity, _addresses[0]); } else { _create(_derivative, _quantity, _addresses); } } /// @notice Executes several positions of `msg.sender` with same `tokenId` /// @param _tokenId uint256 `tokenId` of positions that needs to be executed /// @param _quantity uint256 Quantity of positions to execute /// @param _derivative Derivative Derivative definition function execute(uint256 _tokenId, uint256 _quantity, Derivative memory _derivative) public nonReentrant { uint256[] memory tokenIds = new uint256[](1); uint256[] memory quantities = new uint256[](1); Derivative[] memory derivatives = new Derivative[](1); tokenIds[0] = _tokenId; quantities[0] = _quantity; derivatives[0] = _derivative; _execute(msg.sender, tokenIds, quantities, derivatives); } /// @notice Executes several positions of `_tokenOwner` with same `tokenId` /// @param _tokenOwner address Address of the owner of positions /// @param _tokenId uint256 `tokenId` of positions that needs to be executed /// @param _quantity uint256 Quantity of positions to execute /// @param _derivative Derivative Derivative definition function execute(address _tokenOwner, uint256 _tokenId, uint256 _quantity, Derivative memory _derivative) public nonReentrant { uint256[] memory tokenIds = new uint256[](1); uint256[] memory quantities = new uint256[](1); Derivative[] memory derivatives = new Derivative[](1); tokenIds[0] = _tokenId; quantities[0] = _quantity; derivatives[0] = _derivative; _execute(_tokenOwner, tokenIds, quantities, derivatives); } /// @notice Executes several positions of `msg.sender` with different `tokenId`s /// @param _tokenIds uint256[] `tokenId`s of positions that needs to be executed /// @param _quantities uint256[] Quantity of positions to execute for each `tokenId` /// @param _derivatives Derivative[] Derivative definitions for each `tokenId` function execute(uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) public nonReentrant { _execute(msg.sender, _tokenIds, _quantities, _derivatives); } /// @notice Executes several positions of `_tokenOwner` with different `tokenId`s /// @param _tokenOwner address Address of the owner of positions /// @param _tokenIds uint256[] `tokenId`s of positions that needs to be executed /// @param _quantities uint256[] Quantity of positions to execute for each `tokenId` /// @param _derivatives Derivative[] Derivative definitions for each `tokenId` function execute(address _tokenOwner, uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) public nonReentrant { _execute(_tokenOwner, _tokenIds, _quantities, _derivatives); } /// @notice Cancels tickers, burns positions and returns margins to positions owners in case no data were provided within `NO_DATA_CANCELLATION_PERIOD` /// @param _tokenId uint256 `tokenId` of positions that needs to be canceled /// @param _quantity uint256 Quantity of positions to cancel /// @param _derivative Derivative Derivative definition function cancel(uint256 _tokenId, uint256 _quantity, Derivative memory _derivative) public nonReentrant { uint256[] memory tokenIds = new uint256[](1); uint256[] memory quantities = new uint256[](1); Derivative[] memory derivatives = new Derivative[](1); tokenIds[0] = _tokenId; quantities[0] = _quantity; derivatives[0] = _derivative; _cancel(tokenIds, quantities, derivatives); } /// @notice Cancels tickers, burns positions and returns margins to positions owners in case no data were provided within `NO_DATA_CANCELLATION_PERIOD` /// @param _tokenIds uint256[] `tokenId` of positions that needs to be canceled /// @param _quantities uint256[] Quantity of positions to cancel for each `tokenId` /// @param _derivatives Derivative[] Derivative definitions for each `tokenId` function cancel(uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) public nonReentrant { _cancel(_tokenIds, _quantities, _derivatives); } // PRIVATE FUNCTIONS struct CreatePooledLocalVars { SyntheticAggregator syntheticAggregator; IDerivativeLogic derivativeLogic; IERC20 marginToken; TokenSpender tokenSpender; TokenMinter tokenMinter; } /// @notice This function creates pooled positions /// @param _derivative Derivative Derivative definition /// @param _quantity uint256 Quantity of positions to create /// @param _address address Address of position receiver function _createPooled(Derivative memory _derivative, uint256 _quantity, address _address) private { // Local variables CreatePooledLocalVars memory vars; // Create instance of Opium.SyntheticAggregator // Create instance of Opium.IDerivativeLogic // Create instance of margin token // Create instance of Opium.TokenSpender // Create instance of Opium.TokenMinter vars.syntheticAggregator = SyntheticAggregator(registry.getSyntheticAggregator()); vars.derivativeLogic = IDerivativeLogic(_derivative.syntheticId); vars.marginToken = IERC20(_derivative.token); vars.tokenSpender = TokenSpender(registry.getTokenSpender()); vars.tokenMinter = TokenMinter(registry.getMinter()); // Generate hash for derivative bytes32 derivativeHash = getDerivativeHash(_derivative); // Check with Opium.SyntheticAggregator if syntheticId is a pool require(vars.syntheticAggregator.isPool(derivativeHash, _derivative), ERROR_CORE_NOT_POOL); // Check if ticker was canceled require(!cancelled[derivativeHash], ERROR_CORE_TICKER_WAS_CANCELLED); // Validate input data against Derivative logic (`syntheticId`) require(vars.derivativeLogic.validateInput(_derivative), ERROR_CORE_SYNTHETIC_VALIDATION_ERROR); // Get cached margin required according to logic from Opium.SyntheticAggregator (uint256 margin, ) = vars.syntheticAggregator.getMargin(derivativeHash, _derivative); // Check ERC20 tokens allowance: margin * quantity // `msg.sender` must provide margin for position creation require(vars.marginToken.allowance(msg.sender, address(vars.tokenSpender)) >= margin.mul(_quantity), ERROR_CORE_NOT_ENOUGH_TOKEN_ALLOWANCE); // Take ERC20 tokens from msg.sender, should never revert in correct ERC20 implementation vars.tokenSpender.claimTokens(vars.marginToken, msg.sender, address(this), margin.mul(_quantity)); // Since it's a pooled position, we add transferred margin to pool balance poolVaults[_derivative.syntheticId][_derivative.token] = poolVaults[_derivative.syntheticId][_derivative.token].add(margin.mul(_quantity)); // Mint LONG position tokens vars.tokenMinter.mint(_address, derivativeHash, _quantity); emit Created(_address, address(0), derivativeHash, _quantity); } struct CreateLocalVars { SyntheticAggregator syntheticAggregator; IDerivativeLogic derivativeLogic; IERC20 marginToken; TokenSpender tokenSpender; TokenMinter tokenMinter; } /// @notice This function creates p2p positions /// @param _derivative Derivative Derivative definition /// @param _quantity uint256 Quantity of positions to create /// @param _addresses address[2] Addresses of buyer and seller /// [0] - buyer address /// [1] - seller address function _create(Derivative memory _derivative, uint256 _quantity, address[2] memory _addresses) private { // Local variables CreateLocalVars memory vars; // Create instance of Opium.SyntheticAggregator // Create instance of Opium.IDerivativeLogic // Create instance of margin token // Create instance of Opium.TokenSpender // Create instance of Opium.TokenMinter vars.syntheticAggregator = SyntheticAggregator(registry.getSyntheticAggregator()); vars.derivativeLogic = IDerivativeLogic(_derivative.syntheticId); vars.marginToken = IERC20(_derivative.token); vars.tokenSpender = TokenSpender(registry.getTokenSpender()); vars.tokenMinter = TokenMinter(registry.getMinter()); // Generate hash for derivative bytes32 derivativeHash = getDerivativeHash(_derivative); // Check with Opium.SyntheticAggregator if syntheticId is not a pool require(!vars.syntheticAggregator.isPool(derivativeHash, _derivative), ERROR_CORE_CANT_BE_POOL); // Check if ticker was canceled require(!cancelled[derivativeHash], ERROR_CORE_TICKER_WAS_CANCELLED); // Validate input data against Derivative logic (`syntheticId`) require(vars.derivativeLogic.validateInput(_derivative), ERROR_CORE_SYNTHETIC_VALIDATION_ERROR); uint256[2] memory margins; // Get cached margin required according to logic from Opium.SyntheticAggregator // margins[0] - buyerMargin // margins[1] - sellerMargin (margins[0], margins[1]) = vars.syntheticAggregator.getMargin(derivativeHash, _derivative); // Check ERC20 tokens allowance: (margins[0] + margins[1]) * quantity // `msg.sender` must provide margin for position creation require(vars.marginToken.allowance(msg.sender, address(vars.tokenSpender)) >= margins[0].add(margins[1]).mul(_quantity), ERROR_CORE_NOT_ENOUGH_TOKEN_ALLOWANCE); // Take ERC20 tokens from msg.sender, should never revert in correct ERC20 implementation vars.tokenSpender.claimTokens(vars.marginToken, msg.sender, address(this), margins[0].add(margins[1]).mul(_quantity)); // Mint LONG and SHORT positions tokens vars.tokenMinter.mint(_addresses[0], _addresses[1], derivativeHash, _quantity); emit Created(_addresses[0], _addresses[1], derivativeHash, _quantity); } struct ExecuteAndCancelLocalVars { TokenMinter tokenMinter; OracleAggregator oracleAggregator; SyntheticAggregator syntheticAggregator; } /// @notice Executes several positions of `_tokenOwner` with different `tokenId`s /// @param _tokenOwner address Address of the owner of positions /// @param _tokenIds uint256[] `tokenId`s of positions that needs to be executed /// @param _quantities uint256[] Quantity of positions to execute for each `tokenId` /// @param _derivatives Derivative[] Derivative definitions for each `tokenId` function _execute(address _tokenOwner, uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) private { require(_tokenIds.length == _quantities.length, ERROR_CORE_TOKEN_IDS_AND_QUANTITIES_LENGTH_DOES_NOT_MATCH); require(_tokenIds.length == _derivatives.length, ERROR_CORE_TOKEN_IDS_AND_DERIVATIVES_LENGTH_DOES_NOT_MATCH); // Local variables ExecuteAndCancelLocalVars memory vars; // Create instance of Opium.TokenMinter // Create instance of Opium.OracleAggregator // Create instance of Opium.SyntheticAggregator vars.tokenMinter = TokenMinter(registry.getMinter()); vars.oracleAggregator = OracleAggregator(registry.getOracleAggregator()); vars.syntheticAggregator = SyntheticAggregator(registry.getSyntheticAggregator()); for (uint256 i; i < _tokenIds.length; i++) { // Check if execution is performed after endTime require(now > _derivatives[i].endTime, ERROR_CORE_EXECUTION_BEFORE_MATURITY_NOT_ALLOWED); // Checking whether execution is performed by `_tokenOwner` or `_tokenOwner` allowed third party executions on it's behalf require( _tokenOwner == msg.sender || IDerivativeLogic(_derivatives[i].syntheticId).thirdpartyExecutionAllowed(_tokenOwner), ERROR_CORE_SYNTHETIC_EXECUTION_WAS_NOT_ALLOWED ); // Returns payout for all positions uint256 payout = _getPayout(_derivatives[i], _tokenIds[i], _quantities[i], vars); // Transfer payout if (payout > 0) { IERC20(_derivatives[i].token).safeTransfer(_tokenOwner, payout); } // Burn executed position tokens vars.tokenMinter.burn(_tokenOwner, _tokenIds[i], _quantities[i]); emit Executed(_tokenOwner, _tokenIds[i], _quantities[i]); } } /// @notice Cancels tickers, burns positions and returns margins to positions owners in case no data were provided within `NO_DATA_CANCELLATION_PERIOD` /// @param _tokenIds uint256[] `tokenId` of positions that needs to be canceled /// @param _quantities uint256[] Quantity of positions to cancel for each `tokenId` /// @param _derivatives Derivative[] Derivative definitions for each `tokenId` function _cancel(uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) private { require(_tokenIds.length == _quantities.length, ERROR_CORE_TOKEN_IDS_AND_QUANTITIES_LENGTH_DOES_NOT_MATCH); require(_tokenIds.length == _derivatives.length, ERROR_CORE_TOKEN_IDS_AND_DERIVATIVES_LENGTH_DOES_NOT_MATCH); // Local variables ExecuteAndCancelLocalVars memory vars; // Create instance of Opium.TokenMinter // Create instance of Opium.OracleAggregator // Create instance of Opium.SyntheticAggregator vars.tokenMinter = TokenMinter(registry.getMinter()); vars.oracleAggregator = OracleAggregator(registry.getOracleAggregator()); vars.syntheticAggregator = SyntheticAggregator(registry.getSyntheticAggregator()); for (uint256 i; i < _tokenIds.length; i++) { // Don't allow to cancel tickers with "dummy" oracleIds require(_derivatives[i].oracleId != address(0), ERROR_CORE_CANT_CANCEL_DUMMY_ORACLE_ID); // Check if cancellation is called after `NO_DATA_CANCELLATION_PERIOD` and `oracleId` didn't provided data require( _derivatives[i].endTime + NO_DATA_CANCELLATION_PERIOD <= now && !vars.oracleAggregator.hasData(_derivatives[i].oracleId, _derivatives[i].endTime), ERROR_CORE_CANCELLATION_IS_NOT_ALLOWED ); // Generate hash for derivative bytes32 derivativeHash = getDerivativeHash(_derivatives[i]); // Emit `Canceled` event only once and mark ticker as canceled if (!cancelled[derivativeHash]) { cancelled[derivativeHash] = true; emit Canceled(derivativeHash); } uint256[2] memory margins; // Get cached margin required according to logic from Opium.SyntheticAggregator // margins[0] - buyerMargin // margins[1] - sellerMargin (margins[0], margins[1]) = vars.syntheticAggregator.getMargin(derivativeHash, _derivatives[i]); uint256 payout; // Check if `_tokenId` is an ID of LONG position if (derivativeHash.getLongTokenId() == _tokenIds[i]) { // Set payout to buyerPayout payout = margins[0]; // Check if `_tokenId` is an ID of SHORT position } else if (derivativeHash.getShortTokenId() == _tokenIds[i]) { // Set payout to sellerPayout payout = margins[1]; } else { // Either portfolioId, hack or bug revert(ERROR_CORE_UNKNOWN_POSITION_TYPE); } // Transfer payout * _quantities[i] if (payout > 0) { IERC20(_derivatives[i].token).safeTransfer(msg.sender, payout.mul(_quantities[i])); } // Burn canceled position tokens vars.tokenMinter.burn(msg.sender, _tokenIds[i], _quantities[i]); } } /// @notice Calculates payout for position and gets fees /// @param _derivative Derivative Derivative definition /// @param _tokenId uint256 `tokenId` of positions /// @param _quantity uint256 Quantity of positions /// @param _vars ExecuteAndCancelLocalVars Helping local variables /// @return payout uint256 Payout for all tokens function _getPayout(Derivative memory _derivative, uint256 _tokenId, uint256 _quantity, ExecuteAndCancelLocalVars memory _vars) private returns (uint256 payout) { // Trying to getData from Opium.OracleAggregator, could be reverted // Opium allows to use "dummy" oracleIds, in this case data is set to `0` uint256 data; if (_derivative.oracleId != address(0)) { data = _vars.oracleAggregator.getData(_derivative.oracleId, _derivative.endTime); } else { data = 0; } uint256[2] memory payoutRatio; // Get payout ratio from Derivative logic // payoutRatio[0] - buyerPayout // payoutRatio[1] - sellerPayout (payoutRatio[0], payoutRatio[1]) = IDerivativeLogic(_derivative.syntheticId).getExecutionPayout(_derivative, data); // Generate hash for derivative bytes32 derivativeHash = getDerivativeHash(_derivative); // Check if ticker was canceled require(!cancelled[derivativeHash], ERROR_CORE_TICKER_WAS_CANCELLED); uint256[2] memory margins; // Get cached total margin required from Opium.SyntheticAggregator // margins[0] - buyerMargin // margins[1] - sellerMargin (margins[0], margins[1]) = _vars.syntheticAggregator.getMargin(derivativeHash, _derivative); uint256[2] memory payouts; // Calculate payouts from ratio // payouts[0] -> buyerPayout = (buyerMargin + sellerMargin) * buyerPayoutRatio / (buyerPayoutRatio + sellerPayoutRatio) // payouts[1] -> sellerPayout = (buyerMargin + sellerMargin) * sellerPayoutRatio / (buyerPayoutRatio + sellerPayoutRatio) payouts[0] = margins[0].add(margins[1]).mul(payoutRatio[0]).div(payoutRatio[0].add(payoutRatio[1])); payouts[1] = margins[0].add(margins[1]).mul(payoutRatio[1]).div(payoutRatio[0].add(payoutRatio[1])); // Check if `_tokenId` is an ID of LONG position if (derivativeHash.getLongTokenId() == _tokenId) { // Check if it's a pooled position if (_vars.syntheticAggregator.isPool(derivativeHash, _derivative)) { // Pooled position payoutRatio is considered as full payout, not as payoutRatio payout = payoutRatio[0]; // Multiply payout by quantity payout = payout.mul(_quantity); // Check sufficiency of syntheticId balance in poolVaults require( poolVaults[_derivative.syntheticId][_derivative.token] >= payout , ERROR_CORE_INSUFFICIENT_POOL_BALANCE ); // Subtract paid out margin from poolVault poolVaults[_derivative.syntheticId][_derivative.token] = poolVaults[_derivative.syntheticId][_derivative.token].sub(payout); } else { // Set payout to buyerPayout payout = payouts[0]; // Multiply payout by quantity payout = payout.mul(_quantity); } // Take fees only from profit makers // Check: payout > buyerMargin * quantity if (payout > margins[0].mul(_quantity)) { // Get Opium and `syntheticId` author fees and subtract it from payout payout = payout.sub(_getFees(_vars.syntheticAggregator, derivativeHash, _derivative, payout - margins[0].mul(_quantity))); } // Check if `_tokenId` is an ID of SHORT position } else if (derivativeHash.getShortTokenId() == _tokenId) { // Set payout to sellerPayout payout = payouts[1]; // Multiply payout by quantity payout = payout.mul(_quantity); // Take fees only from profit makers // Check: payout > sellerMargin * quantity if (payout > margins[1].mul(_quantity)) { // Get Opium fees and subtract it from payout payout = payout.sub(_getFees(_vars.syntheticAggregator, derivativeHash, _derivative, payout - margins[1].mul(_quantity))); } } else { // Either portfolioId, hack or bug revert(ERROR_CORE_UNKNOWN_POSITION_TYPE); } } /// @notice Calculates `syntheticId` author and opium fees from profit makers /// @param _syntheticAggregator SyntheticAggregator Instance of Opium.SyntheticAggregator /// @param _derivativeHash bytes32 Derivative hash /// @param _derivative Derivative Derivative definition /// @param _profit uint256 payout of one position /// @return fee uint256 Opium and `syntheticId` author fee function _getFees(SyntheticAggregator _syntheticAggregator, bytes32 _derivativeHash, Derivative memory _derivative, uint256 _profit) private returns (uint256 fee) { // Get cached `syntheticId` author address from Opium.SyntheticAggregator address authorAddress = _syntheticAggregator.getAuthorAddress(_derivativeHash, _derivative); // Get cached `syntheticId` fee percentage from Opium.SyntheticAggregator uint256 commission = _syntheticAggregator.getAuthorCommission(_derivativeHash, _derivative); // Calculate fee // fee = profit * commission / COMMISSION_BASE fee = _profit.mul(commission).div(COMMISSION_BASE); // If commission is zero, finish if (fee == 0) { return 0; } // Calculate opium fee // opiumFee = fee * OPIUM_COMMISSION_PART / OPIUM_COMMISSION_BASE uint256 opiumFee = fee.mul(OPIUM_COMMISSION_PART).div(OPIUM_COMMISSION_BASE); // Calculate author fee // authorFee = fee - opiumFee uint256 authorFee = fee.sub(opiumFee); // Get opium address address opiumAddress = registry.getOpiumAddress(); // Update feeVault for Opium team // feesVault[opium][token] += opiumFee feesVaults[opiumAddress][_derivative.token] = feesVaults[opiumAddress][_derivative.token].add(opiumFee); // Update feeVault for `syntheticId` author // feeVault[author][token] += authorFee feesVaults[authorAddress][_derivative.token] = feesVaults[authorAddress][_derivative.token].add(authorFee); } } // File: contracts/Errors/MatchingErrors.sol pragma solidity 0.5.16; contract MatchingErrors { string constant internal ERROR_MATCH_CANCELLATION_NOT_ALLOWED = "MATCH:CANCELLATION_NOT_ALLOWED"; string constant internal ERROR_MATCH_ALREADY_CANCELED = "MATCH:ALREADY_CANCELED"; string constant internal ERROR_MATCH_ORDER_WAS_CANCELED = "MATCH:ORDER_WAS_CANCELED"; string constant internal ERROR_MATCH_TAKER_ADDRESS_WRONG = "MATCH:TAKER_ADDRESS_WRONG"; string constant internal ERROR_MATCH_ORDER_IS_EXPIRED = "MATCH:ORDER_IS_EXPIRED"; string constant internal ERROR_MATCH_SENDER_ADDRESS_WRONG = "MATCH:SENDER_ADDRESS_WRONG"; string constant internal ERROR_MATCH_SIGNATURE_NOT_VERIFIED = "MATCH:SIGNATURE_NOT_VERIFIED"; string constant internal ERROR_MATCH_NOT_ENOUGH_ALLOWED_FEES = "MATCH:NOT_ENOUGH_ALLOWED_FEES"; } // File: contracts/Lib/LibEIP712.sol pragma solidity 0.5.16; /// @title Opium.Lib.LibEIP712 contract implements the domain of EIP712 for meta transactions contract LibEIP712 { // EIP712Domain structure // name - protocol name // version - protocol version // verifyingContract - signed message verifying contract struct EIP712Domain { string name; string version; address verifyingContract; } // Calculate typehash of ERC712Domain bytes32 constant internal EIP712DOMAIN_TYPEHASH = keccak256(abi.encodePacked( "EIP712Domain(", "string name,", "string version,", "address verifyingContract", ")" )); // solhint-disable-next-line var-name-mixedcase bytes32 internal DOMAIN_SEPARATOR; // Calculate domain separator at creation constructor () public { DOMAIN_SEPARATOR = keccak256(abi.encode( EIP712DOMAIN_TYPEHASH, keccak256("Opium Network"), keccak256("1"), address(this) )); } /// @notice Hashes EIP712Message /// @param hashStruct bytes32 Hash of structured message /// @return result bytes32 Hash of EIP712Message function hashEIP712Message(bytes32 hashStruct) internal view returns (bytes32 result) { bytes32 domainSeparator = DOMAIN_SEPARATOR; assembly { // Load free memory pointer let memPtr := mload(64) mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header mstore(add(memPtr, 2), domainSeparator) // EIP712 domain hash mstore(add(memPtr, 34), hashStruct) // Hash of struct // Compute hash result := keccak256(memPtr, 66) } return result; } } // File: contracts/Matching/SwaprateMatch/LibSwaprateOrder.sol pragma solidity 0.5.16; /// @title Opium.Matching.SwaprateMatch.LibSwaprateOrder contract implements EIP712 signed SwaprateOrder for Opium.Matching.SwaprateMatch contract LibSwaprateOrder is LibEIP712 { /** Structure of order Description should be considered from the order signer (maker) perspective syntheticId - address of derivative syntheticId oracleId - address of derivative oracleId token - address of derivative margin token makerMarginAddress - address of token that maker is willing to pay with takerMarginAddress - address of token that maker is willing to receive makerAddress - address of maker takerAddress - address of counterparty (taker). If zero address, then taker could be anyone senderAddress - address which is allowed to settle the order on-chain. If zero address, then anyone could settle relayerAddress - address of the relayer fee recipient affiliateAddress - address of the affiliate fee recipient feeTokenAddress - address of token which is used for fees endTime - timestamp of derivative maturity quantity - quantity of positions maker wants to receive partialFill - whether maker allows partial fill of it's order param0...param9 - additional params to pass it to syntheticId relayerFee - amount of fee in feeToken that should be paid to relayer affiliateFee - amount of fee in feeToken that should be paid to affiliate nonce - unique order ID signature - Signature of EIP712 message. Not used in hash, but then set for order processing purposes */ struct SwaprateOrder { address syntheticId; address oracleId; address token; address makerAddress; address takerAddress; address senderAddress; address relayerAddress; address affiliateAddress; address feeTokenAddress; uint256 endTime; uint256 quantity; uint256 partialFill; uint256 param0; uint256 param1; uint256 param2; uint256 param3; uint256 param4; uint256 param5; uint256 param6; uint256 param7; uint256 param8; uint256 param9; uint256 relayerFee; uint256 affiliateFee; uint256 nonce; // Not used in hash bytes signature; } // Calculate typehash of Order bytes32 constant internal EIP712_ORDER_TYPEHASH = keccak256(abi.encodePacked( "Order(", "address syntheticId,", "address oracleId,", "address token,", "address makerAddress,", "address takerAddress,", "address senderAddress,", "address relayerAddress,", "address affiliateAddress,", "address feeTokenAddress,", "uint256 endTime,", "uint256 quantity,", "uint256 partialFill,", "uint256 param0,", "uint256 param1,", "uint256 param2,", "uint256 param3,", "uint256 param4,", "uint256 param5,", "uint256 param6,", "uint256 param7,", "uint256 param8,", "uint256 param9,", "uint256 relayerFee,", "uint256 affiliateFee,", "uint256 nonce", ")" )); /// @notice Hashes the order /// @param _order SwaprateOrder Order to hash /// @return hash bytes32 Order hash function hashOrder(SwaprateOrder memory _order) public pure returns (bytes32 hash) { hash = keccak256( abi.encodePacked( abi.encodePacked( EIP712_ORDER_TYPEHASH, uint256(_order.syntheticId), uint256(_order.oracleId), uint256(_order.token), uint256(_order.makerAddress), uint256(_order.takerAddress), uint256(_order.senderAddress), uint256(_order.relayerAddress), uint256(_order.affiliateAddress), uint256(_order.feeTokenAddress) ), abi.encodePacked( _order.endTime, _order.quantity, _order.partialFill ), abi.encodePacked( _order.param0, _order.param1, _order.param2, _order.param3, _order.param4 ), abi.encodePacked( _order.param5, _order.param6, _order.param7, _order.param8, _order.param9 ), abi.encodePacked( _order.relayerFee, _order.affiliateFee, _order.nonce ) ) ); } /// @notice Verifies order signature /// @param _hash bytes32 Hash of the order /// @param _signature bytes Signature of the order /// @param _address address Address of the order signer /// @return bool Returns whether `_signature` is valid and was created by `_address` function verifySignature(bytes32 _hash, bytes memory _signature, address _address) internal view returns (bool) { require(_signature.length == 65, "ORDER:INVALID_SIGNATURE_LENGTH"); bytes32 digest = hashEIP712Message(_hash); address recovered = retrieveAddress(digest, _signature); return _address == recovered; } /// @notice Helping function to recover signer address /// @param _hash bytes32 Hash for signature /// @param _signature bytes Signature /// @return address Returns address of signature creator function retrieveAddress(bytes32 _hash, bytes memory _signature) private pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := byte(0, mload(add(_signature, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { // solium-disable-next-line arg-overflow return ecrecover(_hash, v, r, s); } } } // File: contracts/Matching/SwaprateMatch/SwaprateMatchBase.sol pragma solidity 0.5.16; /// @title Opium.Matching.SwaprateMatchBase contract implements logic for order validation and cancelation contract SwaprateMatchBase is MatchingErrors, LibSwaprateOrder, UsingRegistry, ReentrancyGuard { using SafeMath for uint256; using LibPosition for bytes32; using SafeERC20 for IERC20; // Emmitted when order was canceled event Canceled(bytes32 orderHash); // Canceled orders // This mapping holds hashes of canceled orders // canceled[orderHash] => canceled mapping (bytes32 => bool) public canceled; // Verified orders // This mapping holds hashes of verified orders to verify only once // verified[orderHash] => verified mapping (bytes32 => bool) public verified; // Vaults for fees // This mapping holds balances of relayers and affiliates fees to withdraw // balances[feeRecipientAddress][tokenAddress] => balances mapping (address => mapping (address => uint256)) public balances; // Keeps whether fee was already taken mapping (bytes32 => bool) public feeTaken; /// @notice Calling this function maker of the order could cancel it on-chain /// @param _order SwaprateOrder function cancel(SwaprateOrder memory _order) public { require(msg.sender == _order.makerAddress, ERROR_MATCH_CANCELLATION_NOT_ALLOWED); bytes32 orderHash = hashOrder(_order); require(!canceled[orderHash], ERROR_MATCH_ALREADY_CANCELED); canceled[orderHash] = true; emit Canceled(orderHash); } /// @notice Function to withdraw fees from orders for relayer and affiliates /// @param _token IERC20 Instance of token to withdraw function withdraw(IERC20 _token) public nonReentrant { uint256 balance = balances[msg.sender][address(_token)]; balances[msg.sender][address(_token)] = 0; _token.safeTransfer(msg.sender, balance); } /// @notice This function checks whether order was canceled /// @param _hash bytes32 Hash of the order function validateNotCanceled(bytes32 _hash) internal view { require(!canceled[_hash], ERROR_MATCH_ORDER_WAS_CANCELED); } /// @notice This function validates takerAddress of _leftOrder. It should match either with _rightOrder.makerAddress or be set to zero address /// @param _leftOrder SwaprateOrder Left order /// @param _rightOrder SwaprateOrder Right order function validateTakerAddress(SwaprateOrder memory _leftOrder, SwaprateOrder memory _rightOrder) pure internal { require( _leftOrder.takerAddress == address(0) || _leftOrder.takerAddress == _rightOrder.makerAddress, ERROR_MATCH_TAKER_ADDRESS_WRONG ); } /// @notice This function validates whether sender address equals to `msg.sender` or set to zero address /// @param _order SwaprateOrder function validateSenderAddress(SwaprateOrder memory _order) internal view { require( _order.senderAddress == address(0) || _order.senderAddress == msg.sender, ERROR_MATCH_SENDER_ADDRESS_WRONG ); } /// @notice This function validates order signature if not validated before /// @param orderHash bytes32 Hash of the order /// @param _order SwaprateOrder function validateSignature(bytes32 orderHash, SwaprateOrder memory _order) internal { if (verified[orderHash]) { return; } bool result = verifySignature(orderHash, _order.signature, _order.makerAddress); require(result, ERROR_MATCH_SIGNATURE_NOT_VERIFIED); verified[orderHash] = true; } /// @notice This function is responsible for taking relayer and affiliate fees, if they were not taken already /// @param _orderHash bytes32 Hash of the order /// @param _order Order Order itself function takeFees(bytes32 _orderHash, SwaprateOrder memory _order) internal { // Check if fee was already taken if (feeTaken[_orderHash]) { return; } // Check if feeTokenAddress is not set to zero address if (_order.feeTokenAddress == address(0)) { return; } // Calculate total amount of fees needs to be transfered uint256 fees = _order.relayerFee.add(_order.affiliateFee); // If total amount of fees is non-zero if (fees == 0) { return; } // Create instance of fee token IERC20 feeToken = IERC20(_order.feeTokenAddress); // Create instance of TokenSpender TokenSpender tokenSpender = TokenSpender(registry.getTokenSpender()); // Check if user has enough token approval to pay the fees require(feeToken.allowance(_order.makerAddress, address(tokenSpender)) >= fees, ERROR_MATCH_NOT_ENOUGH_ALLOWED_FEES); // Transfer fee tokenSpender.claimTokens(feeToken, _order.makerAddress, address(this), fees); // Get opium address address opiumAddress = registry.getOpiumAddress(); // Add commission to relayer balance, or to opium balance if relayer is not set if (_order.relayerAddress != address(0)) { balances[_order.relayerAddress][_order.feeTokenAddress] = balances[_order.relayerAddress][_order.feeTokenAddress].add(_order.relayerFee); } else { balances[opiumAddress][_order.feeTokenAddress] = balances[opiumAddress][_order.feeTokenAddress].add(_order.relayerFee); } // Add commission to affiliate balance, or to opium balance if affiliate is not set if (_order.affiliateAddress != address(0)) { balances[_order.affiliateAddress][_order.feeTokenAddress] = balances[_order.affiliateAddress][_order.feeTokenAddress].add(_order.affiliateFee); } else { balances[opiumAddress][_order.feeTokenAddress] = balances[opiumAddress][_order.feeTokenAddress].add(_order.affiliateFee); } // Mark the fee of token as taken feeTaken[_orderHash] = true; } /// @notice Helper to get minimal of two integers /// @param _a uint256 First integer /// @param _b uint256 Second integer /// @return uint256 Minimal integer function min(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a < _b ? _a : _b; } } // File: contracts/Matching/SwaprateMatch/SwaprateMatch.sol pragma solidity 0.5.16; /// @title Opium.Matching.SwaprateMatch contract implements create() function to settle a pair of orders and create derivatives for order makers contract SwaprateMatch is SwaprateMatchBase, LibDerivative { // Orders filled quantity // This mapping holds orders filled quantity // filled[orderHash] => filled mapping (bytes32 => uint256) public filled; /// @notice Calls constructors of super-contracts /// @param _registry address Address of Opium.registry constructor (address _registry) public UsingRegistry(_registry) {} /// @notice This function receives left and right orders, derivative related to it /// @param _leftOrder Order /// @param _rightOrder Order /// @param _derivative Derivative Data of derivative for validation and calculation purposes function create(SwaprateOrder memory _leftOrder, SwaprateOrder memory _rightOrder, Derivative memory _derivative) public nonReentrant { // New deals must not offer tokenIds require( _leftOrder.syntheticId == _rightOrder.syntheticId, "MATCH:NOT_CREATION" ); // Check if it's not pool require(!IDerivativeLogic(_derivative.syntheticId).isPool(), "MATCH:CANT_BE_POOL"); // Validate taker if set validateTakerAddress(_leftOrder, _rightOrder); validateTakerAddress(_rightOrder, _leftOrder); // Validate sender if set validateSenderAddress(_leftOrder); validateSenderAddress(_rightOrder); // Validate if was canceled // orderHashes[0] - leftOrderHash // orderHashes[1] - rightOrderHash bytes32[2] memory orderHashes; orderHashes[0] = hashOrder(_leftOrder); validateNotCanceled(orderHashes[0]); validateSignature(orderHashes[0], _leftOrder); orderHashes[1] = hashOrder(_rightOrder); validateNotCanceled(orderHashes[1]); validateSignature(orderHashes[1], _rightOrder); // Calculate derivative hash and get margin // margins[0] - leftMargin // margins[1] - rightMargin (uint256[2] memory margins, ) = _calculateDerivativeAndGetMargin(_derivative); // Calculate and validate availabilities of orders and fill them uint256 fillable = _checkFillability(orderHashes[0], _leftOrder, orderHashes[1], _rightOrder); // Validate derivative parameters with orders _verifyDerivative(_leftOrder, _rightOrder, _derivative); // Take fees takeFees(orderHashes[0], _leftOrder); takeFees(orderHashes[1], _rightOrder); // Send margin to Core _distributeFunds(_leftOrder, _rightOrder, _derivative, margins, fillable); // Settle contracts Core(registry.getCore()).create(_derivative, fillable, [_leftOrder.makerAddress, _rightOrder.makerAddress]); } // PRIVATE FUNCTIONS /// @notice Calculates derivative hash and gets margin /// @param _derivative Derivative /// @return margins uint256[2] left and right margin /// @return derivativeHash bytes32 Hash of the derivative function _calculateDerivativeAndGetMargin(Derivative memory _derivative) private returns (uint256[2] memory margins, bytes32 derivativeHash) { // Calculate derivative related data for validation derivativeHash = getDerivativeHash(_derivative); // Get cached total margin required according to logic // margins[0] - leftMargin // margins[1] - rightMargin (margins[0], margins[1]) = SyntheticAggregator(registry.getSyntheticAggregator()).getMargin(derivativeHash, _derivative); } /// @notice Calculate and validate availabilities of orders and fill them /// @param _leftOrderHash bytes32 /// @param _leftOrder SwaprateOrder /// @param _rightOrderHash bytes32 /// @param _rightOrder SwaprateOrder /// @return fillable uint256 function _checkFillability(bytes32 _leftOrderHash, SwaprateOrder memory _leftOrder, bytes32 _rightOrderHash, SwaprateOrder memory _rightOrder) private returns (uint256 fillable) { // Calculate availabilities of orders uint256 leftAvailable = _leftOrder.quantity.sub(filled[_leftOrderHash]); uint256 rightAvailable = _rightOrder.quantity.sub(filled[_rightOrderHash]); require(leftAvailable != 0 && rightAvailable !=0, "MATCH:NO_AVAILABLE"); // We could only fill minimum available of both counterparties fillable = min(leftAvailable, rightAvailable); // Check fillable with order conditions about partial fill requirements if (_leftOrder.partialFill == 0 && _rightOrder.partialFill == 0) { require(_leftOrder.quantity == _rightOrder.quantity, "MATCH:FULL_FILL_NOT_POSSIBLE"); } else if (_leftOrder.partialFill == 0 && _rightOrder.partialFill == 1) { require(_leftOrder.quantity <= rightAvailable, "MATCH:FULL_FILL_NOT_POSSIBLE"); } else if (_leftOrder.partialFill == 1 && _rightOrder.partialFill == 0) { require(leftAvailable >= _rightOrder.quantity, "MATCH:FULL_FILL_NOT_POSSIBLE"); } // Update filled filled[_leftOrderHash] = filled[_leftOrderHash].add(fillable); filled[_rightOrderHash] = filled[_rightOrderHash].add(fillable); } /// @notice Validate derivative parameters with orders /// @param _leftOrder SwaprateOrder /// @param _rightOrder SwaprateOrder /// @param _derivative Derivative function _verifyDerivative(SwaprateOrder memory _leftOrder, SwaprateOrder memory _rightOrder, Derivative memory _derivative) private pure { string memory orderError = "MATCH:DERIVATIVE_PARAM_IS_WRONG"; // Validate derivative endTime require( _derivative.endTime == _leftOrder.endTime && _derivative.endTime == _rightOrder.endTime, orderError ); // Validate derivative syntheticId require( _derivative.syntheticId == _leftOrder.syntheticId && _derivative.syntheticId == _rightOrder.syntheticId, orderError ); // Validate derivative oracleId require( _derivative.oracleId == _leftOrder.oracleId && _derivative.oracleId == _rightOrder.oracleId, orderError ); // Validate derivative token require( _derivative.token == _leftOrder.token && _derivative.token == _rightOrder.token, orderError ); // Validate derivative params require(_derivative.params.length >= 20, "MATCH:DERIVATIVE_PARAMS_LENGTH_IS_WRONG"); // Validate left order params require(_leftOrder.param0 == _derivative.params[0], orderError); require(_leftOrder.param1 == _derivative.params[1], orderError); require(_leftOrder.param2 == _derivative.params[2], orderError); require(_leftOrder.param3 == _derivative.params[3], orderError); require(_leftOrder.param4 == _derivative.params[4], orderError); require(_leftOrder.param5 == _derivative.params[5], orderError); require(_leftOrder.param6 == _derivative.params[6], orderError); require(_leftOrder.param7 == _derivative.params[7], orderError); require(_leftOrder.param8 == _derivative.params[8], orderError); require(_leftOrder.param9 == _derivative.params[9], orderError); // Validate right order params require(_rightOrder.param0 == _derivative.params[10], orderError); require(_rightOrder.param1 == _derivative.params[11], orderError); require(_rightOrder.param2 == _derivative.params[12], orderError); require(_rightOrder.param3 == _derivative.params[13], orderError); require(_rightOrder.param4 == _derivative.params[14], orderError); require(_rightOrder.param5 == _derivative.params[15], orderError); require(_rightOrder.param6 == _derivative.params[16], orderError); require(_rightOrder.param7 == _derivative.params[17], orderError); require(_rightOrder.param8 == _derivative.params[18], orderError); require(_rightOrder.param9 == _derivative.params[19], orderError); } /// @notice Distributes funds to core /// @param _leftOrder SwaprateOrder /// @param _rightOrder SwaprateOrder /// @param _derivative Derivative /// @param margins uint256[2] left and right margin /// @param _fillable uint256 How many positions are fillable function _distributeFunds(SwaprateOrder memory _leftOrder, SwaprateOrder memory _rightOrder, Derivative memory _derivative, uint256[2] memory margins, uint256 _fillable) private { IERC20 marginToken = IERC20(_derivative.token); TokenSpender tokenSpender = TokenSpender(registry.getTokenSpender()); // Transfer margin from left to Match and send to Core if (margins[0] != 0) { // Check allowance for margins require(marginToken.allowance(_leftOrder.makerAddress, address(tokenSpender)) >= margins[0].mul(_fillable), "MATCH:NOT_ENOUGH_ALLOWED_MARGIN"); // Transfer margins from buyer to Match tokenSpender.claimTokens(marginToken, _leftOrder.makerAddress, address(this), margins[0].mul(_fillable)); } // Transfer margin from right to Match and send to Core if (margins[1] != 0) { // Check allowance for premiums + margin require(marginToken.allowance(_rightOrder.makerAddress, address(tokenSpender)) >= margins[1].mul(_fillable), "MATCH:NOT_ENOUGH_ALLOWED_MARGIN"); // Transfer margins from seller to Match tokenSpender.claimTokens(marginToken, _rightOrder.makerAddress, address(this), margins[1].mul(_fillable)); } if (margins[0].add(margins[1]) != 0) { // Approve margin to Core for derivative creation require(marginToken.approve(address(tokenSpender), margins[0].add(margins[1]).mul(_fillable)), "MATCH:COULDNT_APPROVE_MARGIN_FOR_CORE"); } } }
@notice Creates derivative contracts (positions) @param _derivative Derivative Derivative definition @param _quantity uint256 Quantity of derivatives to be created @param _addresses address[2] Addresses of buyer and seller [0] - buyer address [1] - seller address - if seller is set to `address(0)`, consider as pooled position
function create(Derivative memory _derivative, uint256 _quantity, address[2] memory _addresses) public nonReentrant { if (_addresses[1] == address(0)) { _createPooled(_derivative, _quantity, _addresses[0]); _create(_derivative, _quantity, _addresses); } }
1,368,144
[ 1, 2729, 16417, 20092, 261, 12388, 13, 225, 389, 20615, 1535, 14969, 427, 1535, 14969, 427, 1535, 2379, 225, 389, 16172, 2254, 5034, 18189, 434, 9630, 8785, 358, 506, 2522, 225, 389, 13277, 1758, 63, 22, 65, 23443, 434, 27037, 471, 29804, 306, 20, 65, 300, 27037, 1758, 306, 21, 65, 300, 29804, 1758, 300, 309, 29804, 353, 444, 358, 1375, 2867, 12, 20, 13, 9191, 5260, 487, 25007, 1754, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 752, 12, 26239, 1535, 3778, 389, 20615, 1535, 16, 2254, 5034, 389, 16172, 16, 1758, 63, 22, 65, 3778, 389, 13277, 13, 1071, 1661, 426, 8230, 970, 288, 203, 3639, 309, 261, 67, 13277, 63, 21, 65, 422, 1758, 12, 20, 3719, 288, 203, 5411, 389, 2640, 52, 22167, 24899, 20615, 1535, 16, 389, 16172, 16, 389, 13277, 63, 20, 19226, 203, 5411, 389, 2640, 24899, 20615, 1535, 16, 389, 16172, 16, 389, 13277, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x0528118Aa13Da72DF7506bE8E7467026837788A8/sources/ERC20.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Hei Long", "HLONG") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyCharityFee = 0; uint256 _buyMarketingFee = 0; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellCharityFee = 0; uint256 _sellMarketingFee = 0; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 1000000000000 * 1e18; buyCharityFee = _buyCharityFee; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyCharityFee + buyMarketingFee + buyLiquidityFee + buyDevFee; sellCharityFee = _sellCharityFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellCharityFee + sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
4,275,161
[ 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, 5256, 77, 3407, 3113, 315, 44, 14639, 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, 202, 202, 11890, 5034, 389, 70, 9835, 2156, 560, 14667, 273, 374, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 3882, 21747, 14667, 273, 374, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 48, 18988, 2 ]
pragma solidity ^0.6.0; // See https://solidity.readthedocs.io/en/v0.4.24/assembly.html#opcodes // See https://solidity.readthedocs.io/en/latest/yul.html contract Test { function assemblyReadsState() public view { address addr = address(this); assembly { let str := "abc" let a := balance(addr) let b := sload(0x20) let c := staticcall(2100, addr, 0, 0, 0, 0) let d := origin() let e := gasprice() let f := coinbase() let g := timestamp() let h := number() let i := difficulty() let j := gaslimit() let k := blockhash(1) let l := extcodesize(addr) let m := caller() let n := callvalue() extcodecopy(0, 0, 0, 0) if 1 { let v, t function fn1() { leave } function fn2(arg1, arg2) -> ret1, ret2 {} v, t := fn2(1, 2) } let bV := true let gV switch bV case false { gV := 10 } default { gV := 20 } switch bV case true { gV := 30 } switch bV default { gV := 40 } let xV := 0 for { let iV := 0 } lt(iV, 0x100) { i := add(iV, 0x20) } { xV := add(xV, mload(i)) continue break } let iV := 0 for { } lt(iV, 0x100) { } { // while(i < 0x100) xV := add(xV, mload(i)) iV := add(iV, 0x20) } } } // this one should be non-payable function assemblyWritesState() public { address addr = address(this); assembly { sstore(sload(0x20), 1) let a := gas() // Seems to be "read only", but compiler is complaining about it. let b := call(2100, addr, 0, 0, 0, 0, 0) let c := callcode(2100, addr, 0, 0, 0, 0, 0) let d := delegatecall(2100, addr, 0, 0, 0, 0) // Following two opcodes are creating smart contracts and will cause failure due to invalid args // let e := create(0, 0, 0) // let f := create2(0, 0, 0, 0) log0(0, 0) log1(0, 0, 0) log2(0, 0, 0, 0) log3(0, 0, 0, 0, 0) log4(0, 0, 0, 0, 0, 0) selfdestruct(addr) } } }
this one should be non-payable
function assemblyWritesState() public { address addr = address(this); assembly { sstore(sload(0x20), 1) let b := call(2100, addr, 0, 0, 0, 0, 0) let c := callcode(2100, addr, 0, 0, 0, 0, 0) let d := delegatecall(2100, addr, 0, 0, 0, 0) log0(0, 0) log1(0, 0, 0) log2(0, 0, 0, 0) log3(0, 0, 0, 0, 0) log4(0, 0, 0, 0, 0, 0) selfdestruct(addr) } }
14,092,192
[ 1, 2211, 1245, 1410, 506, 1661, 17, 10239, 429, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 19931, 8368, 1119, 1435, 1071, 288, 203, 3639, 1758, 3091, 273, 1758, 12, 2211, 1769, 203, 203, 3639, 19931, 288, 203, 5411, 272, 2233, 12, 87, 945, 12, 20, 92, 3462, 3631, 404, 13, 203, 203, 5411, 2231, 324, 519, 745, 12, 5340, 713, 16, 3091, 16, 374, 16, 374, 16, 374, 16, 374, 16, 374, 13, 203, 5411, 2231, 276, 519, 745, 710, 12, 5340, 713, 16, 3091, 16, 374, 16, 374, 16, 374, 16, 374, 16, 374, 13, 203, 5411, 2231, 302, 519, 7152, 1991, 12, 5340, 713, 16, 3091, 16, 374, 16, 374, 16, 374, 16, 374, 13, 203, 203, 203, 5411, 613, 20, 12, 20, 16, 374, 13, 203, 5411, 613, 21, 12, 20, 16, 374, 16, 374, 13, 203, 5411, 613, 22, 12, 20, 16, 374, 16, 374, 16, 374, 13, 203, 5411, 613, 23, 12, 20, 16, 374, 16, 374, 16, 374, 16, 374, 13, 203, 5411, 613, 24, 12, 20, 16, 374, 16, 374, 16, 374, 16, 374, 16, 374, 13, 203, 203, 5411, 365, 5489, 8813, 12, 4793, 13, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0xa01b9ac2D10Dfd0c6FCB70675d63aA95C53F1F5C/sources/browser/token.sol
发送代币到合约先判断当前用户是否有足够的钱执行转账
function sendTokenToGame(address _to, uint _value) public returns (bool){ address txAddress = tx.origin; require(balanceOf[txAddress] >= _value); burnBalance = burnBalance.add(_value); _transfer(txAddress, _to, _value); return true; }
14,239,150
[ 1, 166, 242, 244, 170, 227, 228, 165, 124, 101, 166, 121, 228, 166, 235, 113, 166, 243, 235, 168, 123, 104, 166, 232, 235, 166, 235, 102, 167, 249, 260, 166, 126, 246, 166, 236, 240, 168, 247, 106, 167, 235, 120, 167, 251, 112, 166, 243, 104, 167, 255, 236, 169, 119, 116, 166, 102, 258, 168, 253, 231, 170, 245, 114, 167, 236, 105, 169, 99, 239, 169, 126, 110, 169, 117, 104, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1366, 1345, 774, 12496, 12, 2867, 389, 869, 16, 2254, 389, 1132, 13, 1071, 1135, 261, 6430, 15329, 203, 3639, 1758, 2229, 1887, 273, 2229, 18, 10012, 31, 203, 3639, 2583, 12, 12296, 951, 63, 978, 1887, 65, 1545, 389, 1132, 1769, 203, 203, 3639, 18305, 13937, 273, 18305, 13937, 18, 1289, 24899, 1132, 1769, 203, 203, 3639, 389, 13866, 12, 978, 1887, 16, 389, 869, 16, 389, 1132, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xbFEC5B467ffB275b2E0eb692394aEb8B3B212643/sources/project_/contracts/NFTTest.sol
Price for minting one NFT
uint256 public price = 0.01 ether;
13,336,199
[ 1, 5147, 364, 312, 474, 310, 1245, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 6205, 12900, 273, 374, 18, 1611, 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 ]
./partial_match/42/0x377B811C09eF4fC475f1106cc38FF0d81A0FD011/sources/OnePlanetToken.sol
---------------------------------------------------------------------------- Owned contract ----------------------------------------------------------------------------
contract Owned { address payable public owner; address payable public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = 0xf695ECcdf40E7A2D0DBDF73182B167f27CcAB6E2; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address payable _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } }
3,334,610
[ 1, 5802, 7620, 14223, 11748, 6835, 8879, 13849, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 14223, 11748, 288, 203, 565, 1758, 8843, 429, 1071, 3410, 31, 203, 565, 1758, 8843, 429, 1071, 394, 5541, 31, 203, 203, 565, 871, 14223, 9646, 5310, 1429, 4193, 12, 2867, 8808, 389, 2080, 16, 1758, 8808, 389, 869, 1769, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 3410, 273, 374, 5841, 8148, 25, 7228, 24799, 7132, 41, 27, 37, 22, 40, 20, 2290, 4577, 9036, 28246, 38, 28120, 74, 5324, 39, 71, 2090, 26, 41, 22, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 5541, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 7412, 5460, 12565, 12, 2867, 8843, 429, 389, 2704, 5541, 13, 1071, 1338, 5541, 288, 203, 3639, 394, 5541, 273, 389, 2704, 5541, 31, 203, 565, 289, 203, 565, 445, 2791, 5460, 12565, 1435, 1071, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 394, 5541, 1769, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 12, 8443, 16, 394, 5541, 1769, 203, 3639, 3410, 273, 394, 5541, 31, 203, 3639, 394, 5541, 273, 1758, 12, 20, 1769, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xB690fC16279C096999264e3C049fA133024b4d69/sources/contracts/storefront/AbstractStorefront.sol
* @notice Checks if primary sale fee info is valid @param feeInfo Primary sale fee info/
modifier isPrimaryFeeInfoValid(PrimaryFeeInfo memory feeInfo) { require(_isPrimaryFeeInfoValid(feeInfo), "Fee invo invalid"); _; }
3,599,563
[ 1, 4081, 309, 3354, 272, 5349, 14036, 1123, 353, 923, 225, 14036, 966, 15884, 272, 5349, 14036, 1123, 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 ]
[ 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, 9606, 353, 6793, 14667, 966, 1556, 12, 6793, 14667, 966, 3778, 14036, 966, 13, 288, 203, 3639, 2583, 24899, 291, 6793, 14667, 966, 1556, 12, 21386, 966, 3631, 315, 14667, 2198, 83, 2057, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.5.16; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } 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/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. */ contract Ownable is Context { address private _owner; address private _authorizedNewOwner; event OwnershipTransferAuthorization(address indexed authorizedAddress); 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 Returns the address of the current authorized new owner. */ function authorizedNewOwner() public view returns (address) { return _authorizedNewOwner; } /** * @notice Authorizes the transfer of ownership from _owner to the provided address. * NOTE: No transfer will occur unless authorizedAddress calls assumeOwnership( ). * This authorization may be removed by another call to this function authorizing * the null address. * * @param authorizedAddress The address authorized to become the new owner. */ function authorizeOwnershipTransfer(address authorizedAddress) external onlyOwner { _authorizedNewOwner = authorizedAddress; emit OwnershipTransferAuthorization(_authorizedNewOwner); } /** * @notice Transfers ownership of this contract to the _authorizedNewOwner. */ function assumeOwnership() external { require(_msgSender() == _authorizedNewOwner, "Ownable: only the authorized new owner can accept ownership"); emit OwnershipTransferred(_owner, _authorizedNewOwner); _owner = _authorizedNewOwner; _authorizedNewOwner = address(0); } /** * @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. * * @param confirmAddress The address wants to give up ownership. */ function renounceOwnership(address confirmAddress) public onlyOwner { require(confirmAddress == _owner, "Ownable: confirm address is wrong"); emit OwnershipTransferred(_owner, address(0)); _authorizedNewOwner = address(0); _owner = address(0); } } contract AGL is Ownable { /// @notice BEP-20 token name for this token string public constant name = "Agile"; /// @notice BEP-20 token symbol for this token string public constant symbol = "AGL"; /// @notice BEP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public constant totalSupply = 1000000000e18; // 1 billion AGL /// @notice Reward eligible epochs uint32 public constant eligibleEpochs = 30; // 30 epochs /// @notice Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping (address => uint96) internal balances; /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A transferPoint for marking balance from given epoch struct TransferPoint { uint32 epoch; uint96 balance; } /// @notice A epoch config for blocks or ROI per epoch struct EpochConfig { uint32 epoch; uint32 blocks; uint32 roi; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice A record of transfer checkpoints for each account mapping (address => mapping (uint32 => TransferPoint)) public transferPoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The number of transferPoints for each account mapping (address => uint32) public numTransferPoints; /// @notice The claimed amount for each account mapping (address => uint96) public claimedAmounts; /// @notice Configs for epoch EpochConfig[] public epochConfigs; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice An event thats emitted when a transfer point balance changes // event TransferPointChanged(address indexed src, uint srcBalance, address indexed dst, uint dstBalance); /// @notice An event thats emitted when epoch block count changes event EpochConfigChanged(uint32 indexed previousEpoch, uint32 previousBlocks, uint32 previousROI, uint32 indexed newEpoch, uint32 newBlocks, uint32 newROI); /// @notice The standard BEP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard BEP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new AGL token * @param account The initial account to grant all the tokens */ constructor(address account) public { EpochConfig memory newEpochConfig = EpochConfig( 0, 24 * 60 * 60 / 3, // 1 day blocks in BSC 20 // 0.2% ROI increase per epoch ); epochConfigs.push(newEpochConfig); emit EpochConfigChanged(0, 0, 0, newEpochConfig.epoch, newEpochConfig.blocks, newEpochConfig.roi); balances[account] = uint96(totalSupply); _writeTransferPoint(address(0), account, 0, 0, uint96(totalSupply)); emit Transfer(address(0), account, totalSupply); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @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 rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "AGL::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "AGL::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @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 rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "AGL::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "AGL::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "AGL::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "AGL::delegateBySig: invalid nonce"); require(now <= expiry, "AGL::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "AGL::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } /** * @notice Sets block counter per epoch * @param blocks The count of blocks per epoch * @param roi The interet of rate increased per epoch */ function setEpochConfig(uint32 blocks, uint32 roi) public onlyOwner { require(blocks > 0, "AGL::setEpochConfig: zero blocks"); require(roi < 10000, "AGL::setEpochConfig: roi exceeds max fraction"); EpochConfig memory prevEC = epochConfigs[epochConfigs.length - 1]; EpochConfig memory newEC = EpochConfig(getEpochs(block.number), blocks, roi); require(prevEC.blocks != newEC.blocks || prevEC.roi != newEC.roi, "AGL::setEpochConfig: blocks and roi same as before"); //if (prevEC.epoch == newEC.epoch && epochConfigs.length > 1) { if (prevEC.epoch == newEC.epoch) { epochConfigs[epochConfigs.length - 1] = newEC; } else { epochConfigs.push(newEC); } emit EpochConfigChanged(prevEC.epoch, prevEC.blocks, prevEC.roi, newEC.epoch, newEC.blocks, newEC.roi); } /** * @notice Gets block counter per epoch * @return The count of blocks for current epoch */ function getCurrentEpochBlocks() public view returns (uint32 blocks) { blocks = epochConfigs[epochConfigs.length - 1].blocks; } /** * @notice Gets rate of interest for current epoch * @return The rate of interest for current epoch */ function getCurrentEpochROI() public view returns (uint32 roi) { roi = epochConfigs[epochConfigs.length - 1].roi; } /** * @notice Gets current epoch config * @return The EpochConfig for current epoch */ function getCurrentEpochConfig() public view returns (uint32 epoch, uint32 blocks, uint32 roi) { EpochConfig memory ec = epochConfigs[epochConfigs.length - 1]; epoch = ec.epoch; blocks = ec.blocks; roi = ec.roi; } /** * @notice Gets epoch config at given epoch index * @param forEpoch epoch * @return (index of config, config at epoch) */ function getEpochConfig(uint32 forEpoch) public view returns (uint32 index, uint32 epoch, uint32 blocks, uint32 roi) { index = uint32(epochConfigs.length - 1); // solhint-disable-next-line no-inline-assembly for (; index > 0; index--) { if (forEpoch >= epochConfigs[index].epoch) { break; } } EpochConfig memory ec = epochConfigs[index]; epoch = ec.epoch; blocks = ec.blocks; roi = ec.roi; } /** * @notice Gets epoch index at given block number * @param blockNumber The number of blocks * @return epoch index */ function getEpochs(uint blockNumber) public view returns (uint32) { uint96 blocks = 0; uint96 epoch = 0; uint blockNum = blockNumber; for (uint32 i = 0; i < epochConfigs.length; i++) { uint96 deltaBlocks = (uint96(epochConfigs[i].epoch) - epoch) * blocks; if (blockNum < deltaBlocks) { break; } blockNum = blockNum - deltaBlocks; epoch = epochConfigs[i].epoch; blocks = epochConfigs[i].blocks; } if (blocks == 0) { blocks = getCurrentEpochBlocks(); } epoch = epoch + uint96(blockNum / blocks); if (epoch >= 2**32) { epoch = 2**32 - 1; } return uint32(epoch); } /** * @notice Gets the current holding rewart amount for `account` * @param account The address to get holding reward amount * @return The number of current holding reward for `account` */ function getHoldingReward(address account) public view returns (uint96) { // Check if account is holding more than eligible delay uint32 nTransferPoint = numTransferPoints[account]; if (nTransferPoint == 0) { return 0; } uint32 lastEpoch = getEpochs(block.number); if (lastEpoch == 0) { return 0; } lastEpoch = lastEpoch - 1; if (lastEpoch < eligibleEpochs) { return 0; } else { uint32 lastEligibleEpoch = lastEpoch - eligibleEpochs; // Next check implicit zero balance if (transferPoints[account][0].epoch > lastEligibleEpoch) { return 0; } // First check most recent balance if (transferPoints[account][nTransferPoint - 1].epoch <= lastEligibleEpoch) { nTransferPoint = nTransferPoint - 1; } else { uint32 upper = nTransferPoint - 1; nTransferPoint = 0; while (upper > nTransferPoint) { uint32 center = upper - (upper - nTransferPoint) / 2; // ceil, avoiding overflow TransferPoint memory tp = transferPoints[account][center]; if (tp.epoch == lastEligibleEpoch) { nTransferPoint = center; break; } if (tp.epoch < lastEligibleEpoch) { nTransferPoint = center; } else { upper = center - 1; } } } } // Calculate total rewards amount uint256 reward = 0; for (uint32 iTP = 0; iTP <= nTransferPoint; iTP++) { TransferPoint memory tp = transferPoints[account][iTP]; (uint32 iEC,,,uint32 roi) = getEpochConfig(tp.epoch); uint32 startEpoch = tp.epoch; for (; iEC < epochConfigs.length; iEC++) { uint32 epoch = lastEpoch; bool tookNextTP = false; if (iEC < (epochConfigs.length - 1) && epoch > epochConfigs[iEC + 1].epoch) { epoch = epochConfigs[iEC + 1].epoch; } if (iTP < nTransferPoint && epoch > transferPoints[account][iTP + 1].epoch) { epoch = transferPoints[account][iTP + 1].epoch; tookNextTP = true; } reward = reward + (uint256(tp.balance) * roi * sub32(epoch, startEpoch, "AGL::getHoldingReward: invalid epochs")); if (tookNextTP) { break; } startEpoch = epoch; if (iEC < (epochConfigs.length - 1)) { roi = epochConfigs[iEC + 1].roi; } } } uint96 amount = safe96(reward / 10000, "AGL::getHoldingReward: reward exceeds 96 bits"); // Exclude already claimed amount if (claimedAmounts[account] > 0) { amount = sub96(amount, claimedAmounts[account], "AGL::getHoldingReward: invalid claimed amount"); } return amount; } /** * @notice Receive the current holding rewart amount to msg.sender */ function claimReward() public { uint96 holdingReward = getHoldingReward(msg.sender); if (balances[address(this)] < holdingReward) { holdingReward = balances[address(this)]; } claimedAmounts[msg.sender] = add96(claimedAmounts[msg.sender], holdingReward, "AGL::claimReward: invalid claimed amount"); _transferTokens(address(this), msg.sender, holdingReward); } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "AGL::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "AGL::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "AGL::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "AGL::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); if (amount > 0) { _writeTransferPoint(src, dst, numTransferPoints[dst], balances[src], balances[dst]); } } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "AGL::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "AGL::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "AGL::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function _writeTransferPoint(address src, address dst, uint32 nDstPoint, uint96 srcBalance, uint96 dstBalance) internal { uint32 epoch = getEpochs(block.number); if (src != address(this)) { // Revoke sender in reward eligible list for (uint32 i = 0; i < numTransferPoints[src]; i++) { delete transferPoints[src][i]; } // Remove claim amount claimedAmounts[src] = 0; // delete transferPoints[src]; if (srcBalance > 0) { transferPoints[src][0] = TransferPoint(epoch, srcBalance); numTransferPoints[src] = 1; } else { numTransferPoints[src] = 0; } } if (dst != address(this)) { // Add recipient in reward eligible list if (nDstPoint > 0 && transferPoints[dst][nDstPoint - 1].epoch >= epoch) { transferPoints[dst][nDstPoint - 1].balance = dstBalance; } else { transferPoints[dst][nDstPoint] = TransferPoint(epoch, dstBalance); numTransferPoints[dst] = nDstPoint + 1; } } // emit TransferPointChanged(src, balances[src], dst, balances[dst]); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add32(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) { uint32 c = a + b; require(c >= a, errorMessage); return c; } function sub32(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) { require(b <= a, errorMessage); return a - b; } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
* @dev Returns the address of the current authorized new owner./
function authorizedNewOwner() public view returns (address) { return _authorizedNewOwner; }
1,022,936
[ 1, 1356, 326, 1758, 434, 326, 783, 10799, 394, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 10799, 1908, 5541, 1435, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 8434, 1908, 5541, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/IFeePool.sol"; /** * @title FeePool * @author Pods Finance * @notice Represents a pool that manages fee collection. * Shares can be created to redeem the collected fees between participants proportionally. */ contract FeePool is IFeePool, Ownable { using SafeERC20 for IERC20; using SafeMath for uint256; mapping(address => Balance) private _balances; uint256 private _shares; uint256 private _totalLiability; uint256 private _feeBaseValue; uint8 private _feeDecimals; address private immutable _token; uint256 private constant _DYNAMIC_FEE_ALPHA = 2000; uint256 private constant _MAX_FEE_DECIMALS = 38; event FeeUpdated(address token, uint256 newBaseFee, uint8 newFeeDecimals); event FeeWithdrawn(address token, address to, uint256 amountWithdrawn, uint256 sharesBurned); event ShareMinted(address token, address to, uint256 amountMinted); constructor( address token, uint256 feeBaseValue, uint8 feeDecimals ) public { require(token != address(0), "FeePool: Invalid token"); require( feeDecimals <= _MAX_FEE_DECIMALS && feeBaseValue <= uint256(10)**feeDecimals, "FeePool: Invalid Fee data" ); _token = token; _feeBaseValue = feeBaseValue; _feeDecimals = feeDecimals; } /** * @notice Sets fee and the decimals * * @param feeBaseValue Fee value * @param feeDecimals Fee decimals */ function setFee(uint256 feeBaseValue, uint8 feeDecimals) external override onlyOwner { require( feeDecimals <= _MAX_FEE_DECIMALS && feeBaseValue <= uint256(10)**feeDecimals, "FeePool: Invalid Fee data" ); _feeBaseValue = feeBaseValue; _feeDecimals = feeDecimals; emit FeeUpdated(_token, _feeBaseValue, _feeDecimals); } /** * @notice get the withdraw token amount based on the amount of shares that will be burned * * @param to address of the share holder * @param amountOfShares amount of shares to withdraw */ function getWithdrawAmount(address to, uint256 amountOfShares) external override view returns (uint256 amortizedLiability, uint256 withdrawAmount) { return _getWithdrawAmount(to, amountOfShares); } /** * @notice Withdraws collected fees to an address * * @param to To whom the fees should be transferred * @param amountOfShares Amount of Shares to burn */ function withdraw(address to, uint256 amountOfShares) external override onlyOwner { require(_balances[to].shares >= amountOfShares, "Burn exceeds balance"); (uint256 amortizedLiability, uint256 withdrawAmount) = _getWithdrawAmount(to, amountOfShares); _balances[to].shares = _balances[to].shares.sub(amountOfShares); _balances[to].liability = _balances[to].liability.sub(amortizedLiability); _shares = _shares.sub(amountOfShares); _totalLiability = _totalLiability.sub(amortizedLiability); if (withdrawAmount > 0) { IERC20(_token).safeTransfer(to, withdrawAmount); emit FeeWithdrawn(_token, to, withdrawAmount, amountOfShares); } } /** * @notice Creates new shares that represent a fraction when withdrawing fees * * @param to To whom the tokens should be minted * @param amount Amount to mint */ function mint(address to, uint256 amount) external override onlyOwner { // If no share was minted, share value should worth nothing uint256 newLiability = 0; // Otherwise it should divide the total collected by total shares minted if (_shares > 0) { uint256 feesCollected = IERC20(_token).balanceOf(address(this)); newLiability = feesCollected.add(_totalLiability).mul(amount).div(_shares); } _balances[to].shares = _balances[to].shares.add(amount); _balances[to].liability = _balances[to].liability.add(newLiability); _shares = _shares.add(amount); _totalLiability = _totalLiability.add(newLiability); emit ShareMinted(_token, to, amount); } /** * @notice Return the current fee token */ function feeToken() external override view returns (address) { return _token; } /** * @notice Return the current fee value */ function feeValue() external override view returns (uint256 feeBaseValue) { return _feeBaseValue; } /** * @notice Returns the number of decimals used to represent fees */ function feeDecimals() external override view returns (uint8) { return _feeDecimals; } /** * @notice Utility function to calculate fee charges to a given amount * * @param amount Total transaction amount * @param poolAmount Total pool amount */ function getCollectable(uint256 amount, uint256 poolAmount) external override view returns (uint256 totalFee) { uint256 baseFee = amount.mul(_feeBaseValue).div(10**uint256(_feeDecimals)); uint256 dynamicFee = _getDynamicFees(amount, poolAmount); return baseFee.add(dynamicFee); } /** * @dev Returns the `Balance` owned by `account`. */ function balanceOf(address account) external view returns (Balance memory) { return _balances[account]; } /** * @dev Returns the `shares` owned by `account`. */ function sharesOf(address account) external override view returns (uint256) { return _balances[account].shares; } /** * @notice Total count of shares created */ function totalShares() external view returns (uint256) { return _shares; } /** * @notice Calculates a dynamic fee to counterbalance big trades and incentivize liquidity */ function _getDynamicFees(uint256 tradeAmount, uint256 poolAmount) internal pure returns (uint256) { uint256 numerator = _DYNAMIC_FEE_ALPHA * tradeAmount.mul(tradeAmount).mul(tradeAmount); uint256 denominator = poolAmount.mul(poolAmount).mul(poolAmount); uint256 ratio = numerator.div(denominator); return ratio.mul(tradeAmount) / 100; } function _getWithdrawAmount(address to, uint256 amountOfShares) internal view returns (uint256 amortizedLiability, uint256 withdrawAmount) { uint256 feesCollected = IERC20(_token).balanceOf(address(this)); withdrawAmount = 0; amortizedLiability = amountOfShares.mul(_balances[to].liability).div(_balances[to].shares); uint256 collectedGross = feesCollected.add(_totalLiability).mul(amountOfShares).div(_shares); // Prevents negative payouts if (collectedGross > amortizedLiability) { withdrawAmount = collectedGross.sub(amortizedLiability); } return (amortizedLiability, withdrawAmount); } } // 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 Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.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: agpl-3.0 pragma solidity 0.6.12; interface IFeePool { struct Balance { uint256 shares; uint256 liability; } function setFee(uint256 feeBaseValue, uint8 decimals) external; function withdraw(address to, uint256 amount) external; function mint(address to, uint256 amount) external; function feeToken() external view returns (address); function feeValue() external view returns (uint256); function feeDecimals() external view returns (uint8); function getCollectable(uint256 amount, uint256 poolAmount) external view returns (uint256); function sharesOf(address owner) external view returns (uint256); function getWithdrawAmount(address owner, uint256 amountOfShares) external view returns (uint256, uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @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); } } } }
* @notice Calculates a dynamic fee to counterbalance big trades and incentivize liquidity/
function _getDynamicFees(uint256 tradeAmount, uint256 poolAmount) internal pure returns (uint256) { uint256 numerator = _DYNAMIC_FEE_ALPHA * tradeAmount.mul(tradeAmount).mul(tradeAmount); uint256 denominator = poolAmount.mul(poolAmount).mul(poolAmount); uint256 ratio = numerator.div(denominator); return ratio.mul(tradeAmount) / 100; }
511,783
[ 1, 10587, 279, 5976, 14036, 358, 3895, 12296, 5446, 1284, 5489, 471, 316, 2998, 427, 554, 4501, 372, 24237, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 588, 9791, 2954, 281, 12, 11890, 5034, 18542, 6275, 16, 2254, 5034, 2845, 6275, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 16730, 273, 389, 40, 25145, 67, 8090, 41, 67, 26313, 380, 18542, 6275, 18, 16411, 12, 20077, 6275, 2934, 16411, 12, 20077, 6275, 1769, 203, 3639, 2254, 5034, 15030, 273, 2845, 6275, 18, 16411, 12, 6011, 6275, 2934, 16411, 12, 6011, 6275, 1769, 203, 3639, 2254, 5034, 7169, 273, 16730, 18, 2892, 12, 13002, 26721, 1769, 203, 203, 3639, 327, 7169, 18, 16411, 12, 20077, 6275, 13, 342, 2130, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.13; import "./external/@openzeppelin/token/ERC20/extensions/IERC20Metadata.sol"; import "./external/spool-core/SpoolOwnable.sol"; import "./interfaces/IVoSPOOL.sol"; /* ========== STRUCTS ========== */ /** * @notice global tranche struct * @dev used so it can be passed through functions as a struct * @member amount amount minted in tranche */ struct Tranche { uint48 amount; } /** * @notice global tranches struct holding 5 tranches * @dev made to pack multiple tranches in one word * @member zero tranche in pack at position 0 * @member one tranche in pack at position 1 * @member two tranche in pack at position 2 * @member three tranche in pack at position 3 * @member four tranche in pack at position 4 */ struct GlobalTranches { Tranche zero; Tranche one; Tranche two; Tranche three; Tranche four; } /** * @notice user tranche struct * @dev struct holds users minted amount at tranche at index * @member amount users amount minted at tranche * @member index tranche index */ struct UserTranche { uint48 amount; uint16 index; } /** * @notice user tranches struct, holding 4 user tranches * @dev made to pack multiple tranches in one word * @member zero user tranche in pack at position 0 * @member one user tranche in pack at position 1 * @member two user tranche in pack at position 2 * @member three user tranche in pack at position 3 */ struct UserTranches { UserTranche zero; UserTranche one; UserTranche two; UserTranche three; } /** * @title Spool DAO Voting Token Implementation * * @notice The voting SPOOL pseudo-ERC20 Implementation * * An untransferable token implementation meant to be used by the * Spool DAO to mint the voting equivalent of the staked token. * * @dev * Users voting power consists of instant and gradual (maturing) voting power. * voSPOOL contract assumes voting power comes from vesting or staking SPOOL tokens. * As SPOOL tokens have a maximum supply of 210,000,000 * 10**18, we consider this * limitation when storing data (e.g. storing amount divided by 10**12) to save on gas. * * Instant voting power can be used in the full amount as soon as minted. * * Gradual voting power: * Matures linearly over 156 weeks (3 years) up to the minted amount. * If a user burns gradual voting power, all accumulated voting power is * reset to zero. In case there is some amount left, it'll take another 3 * years to achieve fully-matured power. Only gradual voting power is reset * and not instant one. * Gradual voting power updates at every new tranche, which lasts one week. * * Contract consists of: * - CONSTANTS * - STATE VARIABLES * - CONSTRUCTOR * - IERC20 FUNCTIONS * - INSTANT POWER FUNCTIONS * - GRADUAL POWER FUNCTIONS * - GRADUAL POWER: VIEW FUNCTIONS * - GRADUAL POWER: MINT FUNCTIONS * - GRADUAL POWER: BURN FUNCTIONS * - GRADUAL POWER: UPDATE GLOBAL FUNCTIONS * - GRADUAL POWER: UPDATE USER FUNCTIONS * - GRADUAL POWER: GLOBAL HELPER FUNCTIONS * - GRADUAL POWER: USER HELPER FUNCTIONS * - GRADUAL POWER: HELPER FUNCTIONS * - OWNER FUNCTIONS * - RESTRICTION FUNCTIONS * - MODIFIERS */ contract VoSPOOL is SpoolOwnable, IVoSPOOL, IERC20Metadata { /* ========== CONSTANTS ========== */ /// @notice trim size value of the mint amount /// @dev we trim gradual mint amount by `TRIM_SIZE`, so it takes less storage uint256 private constant TRIM_SIZE = 10**12; /// @notice number of tranche amounts stored in one 256bit word uint256 private constant TRANCHES_PER_WORD = 5; /// @notice duration of one tranche uint256 public constant TRANCHE_TIME = 1 weeks; /// @notice amount of tranches to mature to full power uint256 public constant FULL_POWER_TRANCHES_COUNT = 52 * 3; /// @notice time until gradual power is fully-matured /// @dev full power time is 156 weeks (approximately 3 years) uint256 public constant FULL_POWER_TIME = TRANCHE_TIME * FULL_POWER_TRANCHES_COUNT; /// @notice Token name full name string public constant name = "Spool DAO Voting Token"; /// @notice Token symbol string public constant symbol = "voSPOOL"; /// @notice Token decimals uint8 public constant decimals = 18; /* ========== STATE VARIABLES ========== */ /// @notice tranche time for index 1 uint256 public immutable firstTrancheStartTime; /// @notice mapping holding instant minting privileges for addresses mapping(address => bool) public minters; /// @notice mapping holding gradual minting privileges for addresses mapping(address => bool) public gradualMinters; /// @notice total instant voting power uint256 public totalInstantPower; /// @notice user instant voting power mapping(address => uint256) public userInstantPower; /// @notice global gradual power values GlobalGradual private _globalGradual; /// @notice global tranches /// @dev mapping tranche index to a group of tranches (5 tranches per word) mapping(uint256 => GlobalTranches) public indexedGlobalTranches; /// @notice user gradual power values mapping(address => UserGradual) private _userGraduals; /// @notice user tranches /// @dev mapping users to its tranches mapping(address => mapping(uint256 => UserTranches)) public userTranches; /* ========== CONSTRUCTOR ========== */ /** * @notice Sets the value of _spoolOwner and first tranche end time * @dev With `_firstTrancheEndTime` you can set when the first tranche time * finishes and essentially users minted get the first foting power. * e.g. if we set it to Sunday 10pm and tranche time is 1 week, * all new tranches in the future will finish on Sunday 10pm and new * voSPOOL power will mature and be accrued. * * Requirements: * * - first tranche time must be in the future * - first tranche time must must be less than full tranche time in the future * * @param _spoolOwner address of spool owner contract * @param _firstTrancheEndTime first tranche end time after the deployment */ constructor(ISpoolOwner _spoolOwner, uint256 _firstTrancheEndTime) SpoolOwnable(_spoolOwner) { require( _firstTrancheEndTime > block.timestamp, "voSPOOL::constructor: First tranche end time must be in the future" ); require( _firstTrancheEndTime < block.timestamp + TRANCHE_TIME, "voSPOOL::constructor: First tranche end time must be less than full tranche time in the future" ); unchecked { // set first tranche start time firstTrancheStartTime = _firstTrancheEndTime - TRANCHE_TIME; } } /* ========== IERC20 FUNCTIONS ========== */ /** * @notice Returns current total voting power */ function totalSupply() external view override returns (uint256) { (GlobalGradual memory global, ) = _getUpdatedGradual(); return totalInstantPower + _getTotalGradualVotingPower(global); } /** * @notice Returns current user total voting power */ function balanceOf(address account) external view override returns (uint256) { (UserGradual memory _userGradual, ) = _getUpdatedGradualUser(account); return userInstantPower[account] + _getUserGradualVotingPower(_userGradual); } /** * @dev Execution of function is prohibited to disallow token movement */ function transfer(address, uint256) external pure override returns (bool) { revert("voSPOOL::transfer: Prohibited Action"); } /** * @dev Execution of function is prohibited to disallow token movement */ function transferFrom( address, address, uint256 ) external pure override returns (bool) { revert("voSPOOL::transferFrom: Prohibited Action"); } /** * @dev Execution of function is prohibited to disallow token movement */ function approve(address, uint256) external pure override returns (bool) { revert("voSPOOL::approve: Prohibited Action"); } /** * @dev Execution of function is prohibited to disallow token movement */ function allowance(address, address) external pure override returns (uint256) { revert("voSPOOL::allowance: Prohibited Action"); } /* ========== INSTANT POWER FUNCTIONS ========== */ /** * @notice Mints the provided amount as instant voting power. * * Requirements: * * - the caller must be the autorized * * @param to mint to user * @param amount mint amount */ function mint(address to, uint256 amount) external onlyMinter { totalInstantPower += amount; unchecked { userInstantPower[to] += amount; } emit Minted(to, amount); } /** * @notice Burns the provided amount of instant power from the specified user. * @dev only instant power is removed, gradual power stays the same * * Requirements: * * - the caller must be the instant minter * - the user must posses at least the burning `amount` of instant voting power amount * * @param from burn from user * @param amount burn amount */ function burn(address from, uint256 amount) external onlyMinter { require(userInstantPower[from] >= amount, "voSPOOL:burn: User instant power balance too low"); unchecked { userInstantPower[from] -= amount; totalInstantPower -= amount; } emit Burned(from, amount); } /* ========== GRADUAL POWER FUNCTIONS ========== */ /* ---------- GRADUAL POWER: VIEW FUNCTIONS ---------- */ /** * @notice returns updated total gradual voting power (fully-matured and maturing) * * @return totalGradualVotingPower total gradual voting power (fully-matured + maturing) */ function getTotalGradualVotingPower() external view returns (uint256) { (GlobalGradual memory global, ) = _getUpdatedGradual(); return _getTotalGradualVotingPower(global); } /** * @notice returns updated global gradual struct * * @return global updated global gradual struct */ function getGlobalGradual() external view returns (GlobalGradual memory) { (GlobalGradual memory global, ) = _getUpdatedGradual(); return global; } /** * @notice returns not updated global gradual struct * * @return global updated global gradual struct */ function getNotUpdatedGlobalGradual() external view returns (GlobalGradual memory) { return _globalGradual; } /** * @notice returns updated user gradual voting power (fully-matured and maturing) * * @param user address holding voting power * @return userGradualVotingPower user gradual voting power (fully-matured + maturing) */ function getUserGradualVotingPower(address user) external view returns (uint256) { (UserGradual memory _userGradual, ) = _getUpdatedGradualUser(user); return _getUserGradualVotingPower(_userGradual); } /** * @notice returns updated user gradual struct * * @param user user address * @return _userGradual user updated gradual struct */ function getUserGradual(address user) external view returns (UserGradual memory) { (UserGradual memory _userGradual, ) = _getUpdatedGradualUser(user); return _userGradual; } /** * @notice returns not updated user gradual struct * * @param user user address * @return _userGradual user updated gradual struct */ function getNotUpdatedUserGradual(address user) external view returns (UserGradual memory) { return _userGraduals[user]; } /** * @notice Returns current active tranche index * * @return trancheIndex current tranche index */ function getCurrentTrancheIndex() public view returns (uint16) { return _getTrancheIndex(block.timestamp); } /** * @notice Returns tranche index based on `time` * @dev `time` can be any time inside the tranche * * Requirements: * * - `time` must be equal to more than first tranche time * * @param time tranche time time to get the index for * @return trancheIndex tranche index at `time` */ function getTrancheIndex(uint256 time) external view returns (uint256) { require( time >= firstTrancheStartTime, "voSPOOL::getTrancheIndex: Time must be more or equal to the first tranche time" ); return _getTrancheIndex(time); } /** * @notice Returns tranche index based at time * * @param time unix time * @return trancheIndex tranche index at `time` */ function _getTrancheIndex(uint256 time) private view returns (uint16) { unchecked { return uint16(((time - firstTrancheStartTime) / TRANCHE_TIME) + 1); } } /** * @notice Returns next tranche end time * * @return trancheEndTime end time for next tranche */ function getNextTrancheEndTime() external view returns (uint256) { return getTrancheEndTime(getCurrentTrancheIndex()); } /** * @notice Returns tranche end time for tranche index * * @param trancheIndex tranche index * @return trancheEndTime end time for `trancheIndex` */ function getTrancheEndTime(uint256 trancheIndex) public view returns (uint256) { return firstTrancheStartTime + trancheIndex * TRANCHE_TIME; } /** * @notice Returns last finished tranche index * * @return trancheIndex last finished tranche index */ function getLastFinishedTrancheIndex() public view returns (uint16) { unchecked { return getCurrentTrancheIndex() - 1; } } /* ---------- GRADUAL POWER: MINT FUNCTIONS ---------- */ /** * @notice Mints the provided amount of tokens to the specified user to gradually mature up to the amount. * @dev Saves the amount to tranche user index, so the voting power starts maturing. * * Requirements: * * - the caller must be the autorized * * @param to gradual mint to user * @param amount gradual mint amount */ function mintGradual(address to, uint256 amount) external onlyGradualMinter updateGradual updateGradualUser(to) { uint48 trimmedAmount = _trim(amount); _mintGradual(to, trimmedAmount); emit GradualMinted(to, amount); } /** * @notice Mints the provided amount of tokens to the specified user to gradually mature up to the amount. * @dev Saves the amount to tranche user index, so the voting power starts maturing. * * @param to gradual mint to user * @param trimmedAmount gradual mint trimmed amount */ function _mintGradual(address to, uint48 trimmedAmount) private { if (trimmedAmount == 0) { return; } UserGradual memory _userGradual = _userGraduals[to]; // add new maturing amount to user and global amount _userGradual.maturingAmount += trimmedAmount; _globalGradual.totalMaturingAmount += trimmedAmount; // add maturing amount to user tranche UserTranche memory latestTranche = _getUserTranche(to, _userGradual.latestTranchePosition); uint16 currentTrancheIndex = getCurrentTrancheIndex(); bool isFirstGradualMint = !_hasTranches(_userGradual); // if latest user tranche is not current index, update latest // user can have first mint or last tranche deposited is finished if (isFirstGradualMint || latestTranche.index < currentTrancheIndex) { UserTranchePosition memory nextTranchePosition = _getNextUserTranchePosition( _userGradual.latestTranchePosition ); // if first time gradual minting set oldest tranche position if (isFirstGradualMint) { _userGradual.oldestTranchePosition = nextTranchePosition; } // update latest tranche _userGradual.latestTranchePosition = nextTranchePosition; latestTranche = UserTranche(trimmedAmount, currentTrancheIndex); } else { // if user already minted in current tranche, add additional amount latestTranche.amount += trimmedAmount; } // update global tranche amount _addGlobalTranche(latestTranche.index, trimmedAmount); // store updated user values _setUserTranche(to, _userGradual.latestTranchePosition, latestTranche); _userGraduals[to] = _userGradual; } /** * @notice add `amount` to global tranche `index` * * @param index tranche index * @param amount amount to add */ function _addGlobalTranche(uint256 index, uint48 amount) private { Tranche storage tranche = _getTranche(index); tranche.amount += amount; } /** * @notice sets updated `user` `tranche` at position * * @param user user address to set tranche * @param userTranchePosition position to set the `tranche` at * @param tranche updated `user` tranche */ function _setUserTranche( address user, UserTranchePosition memory userTranchePosition, UserTranche memory tranche ) private { UserTranches storage _userTranches = userTranches[user][userTranchePosition.arrayIndex]; if (userTranchePosition.position == 0) { _userTranches.zero = tranche; } else if (userTranchePosition.position == 1) { _userTranches.one = tranche; } else if (userTranchePosition.position == 2) { _userTranches.two = tranche; } else { _userTranches.three = tranche; } } /* ---------- GRADUAL POWER: BURN FUNCTIONS ---------- */ /** * @notice Burns the provided amount of gradual power from the specified user. * @dev User loses all matured power accumulated till now. * Voting power starts maturing from the start if there is any amount left. * * Requirements: * * - the caller must be the gradual minter * * @param from burn from user * @param amount burn amount * @param burnAll true to burn all user amount */ function burnGradual( address from, uint256 amount, bool burnAll ) external onlyGradualMinter updateGradual updateGradualUser(from) { UserGradual memory _userGradual = _userGraduals[from]; uint48 userTotalGradualAmount = _userGradual.maturedVotingPower + _userGradual.maturingAmount; // remove user matured power if (_userGradual.maturedVotingPower > 0) { _globalGradual.totalMaturedVotingPower -= _userGradual.maturedVotingPower; _userGradual.maturedVotingPower = 0; } // remove user maturing if (_userGradual.maturingAmount > 0) { _globalGradual.totalMaturingAmount -= _userGradual.maturingAmount; _userGradual.maturingAmount = 0; } // remove user unmatured power if (_userGradual.rawUnmaturedVotingPower > 0) { _globalGradual.totalRawUnmaturedVotingPower -= _userGradual.rawUnmaturedVotingPower; _userGradual.rawUnmaturedVotingPower = 0; } // if user has any tranches, remove all of them from user and global if (_hasTranches(_userGradual)) { uint256 fromIndex = _userGradual.oldestTranchePosition.arrayIndex; uint256 toIndex = _userGradual.latestTranchePosition.arrayIndex; // loop over user tranches and delete all of them for (uint256 i = fromIndex; i <= toIndex; i++) { // delete from global tranches _deleteUserTranchesFromGlobal(userTranches[from][i]); // delete user tranches delete userTranches[from][i]; } } // reset oldest tranche (meaning user has no tranches) _userGradual.oldestTranchePosition = UserTranchePosition(0, 0); // apply changes to storage _userGraduals[from] = _userGradual; emit GradualBurned(from, amount, burnAll); // if we don't burn all gradual amount, restart maturing if (!burnAll) { uint48 trimmedAmount = _trimRoundUp(amount); // if user still has some amount left, mint gradual from start if (userTotalGradualAmount > trimmedAmount) { unchecked { uint48 userAmountLeft = userTotalGradualAmount - trimmedAmount; // mint amount left _mintGradual(from, userAmountLeft); } } } } /** * @notice remove user tranches amounts from global tranches * @dev remove for all four user tranches in the struct * * @param _userTranches user tranches */ function _deleteUserTranchesFromGlobal(UserTranches memory _userTranches) private { _removeUserTrancheFromGlobal(_userTranches.zero); _removeUserTrancheFromGlobal(_userTranches.one); _removeUserTrancheFromGlobal(_userTranches.two); _removeUserTrancheFromGlobal(_userTranches.three); } /** * @notice remove user tranche amount from global tranche * * @param userTranche user tranche */ function _removeUserTrancheFromGlobal(UserTranche memory userTranche) private { if (userTranche.amount > 0) { Tranche storage tranche = _getTranche(userTranche.index); tranche.amount -= userTranche.amount; } } /* ---------- GRADUAL POWER: UPDATE GLOBAL FUNCTIONS ---------- */ /** * @notice updates global gradual voting power * @dev * * Requirements: * * - the caller must be the gradual minter */ function updateVotingPower() external override onlyGradualMinter { _updateGradual(); } /** * @notice updates global gradual voting power * @dev updates only if changes occured */ function _updateGradual() private { (GlobalGradual memory global, bool didUpdate) = _getUpdatedGradual(); if (didUpdate) { _globalGradual = global; emit GlobalGradualUpdated( global.lastUpdatedTrancheIndex, global.totalMaturedVotingPower, global.totalMaturingAmount, global.totalRawUnmaturedVotingPower ); } } /** * @notice returns updated global gradual values * @dev the update is in-memory * * @return global updated GlobalGradual struct * @return didUpdate flag if `global` was updated */ function _getUpdatedGradual() private view returns (GlobalGradual memory global, bool didUpdate) { uint256 lastFinishedTrancheIndex = getLastFinishedTrancheIndex(); global = _globalGradual; // update gradual until we reach last finished index while (global.lastUpdatedTrancheIndex < lastFinishedTrancheIndex) { // increment index before updating so we calculate based on finished index global.lastUpdatedTrancheIndex++; _updateGradualForTrancheIndex(global); didUpdate = true; } } /** * @notice update global gradual values for tranche `index` * @dev the update is done in-memory on `global` struct * * @param global global gradual struct */ function _updateGradualForTrancheIndex(GlobalGradual memory global) private view { // update unmatured voting power // every new tranche we add totalMaturingAmount to the _totalRawUnmaturedVotingPower global.totalRawUnmaturedVotingPower += global.totalMaturingAmount; // move newly matured voting power to matured // do only if contract is old enough so full power could be achieved if (global.lastUpdatedTrancheIndex >= FULL_POWER_TRANCHES_COUNT) { uint256 maturedIndex = global.lastUpdatedTrancheIndex - FULL_POWER_TRANCHES_COUNT + 1; uint48 newMaturedVotingPower = _getTranche(maturedIndex).amount; // if there is any new fully-matured voting power, update if (newMaturedVotingPower > 0) { // remove new fully matured voting power from non matured raw one uint56 newMaturedAsRawUnmatured = _getMaturedAsRawUnmaturedAmount(newMaturedVotingPower); global.totalRawUnmaturedVotingPower -= newMaturedAsRawUnmatured; // remove new fully-matured power from maturing amount global.totalMaturingAmount -= newMaturedVotingPower; // add new fully-matured voting power global.totalMaturedVotingPower += newMaturedVotingPower; } } } /* ---------- GRADUAL POWER: UPDATE USER FUNCTIONS ---------- */ /** * @notice update gradual user voting power * @dev also updates global gradual voting power * * Requirements: * * - the caller must be the gradual minter * * @param user user address to update */ function updateUserVotingPower(address user) external override onlyGradualMinter { _updateGradual(); _updateGradualUser(user); } /** * @notice update gradual user struct storage * * @param user user address to update */ function _updateGradualUser(address user) private { (UserGradual memory _userGradual, bool didUpdate) = _getUpdatedGradualUser(user); if (didUpdate) { _userGraduals[user] = _userGradual; emit UserGradualUpdated( user, _userGradual.lastUpdatedTrancheIndex, _userGradual.maturedVotingPower, _userGradual.maturingAmount, _userGradual.rawUnmaturedVotingPower ); } } /** * @notice returns updated user gradual struct * @dev the update is returned in-memory * The update is done in 3 steps: * 1. check if user ia alreas, update last updated undex * 2. update voting power for tranches that have fully-matured (if any) * 3. update voting power for tranches that are still maturing * * @param user updated for user address * @return _userGradual updated user gradual struct * @return didUpdate flag if user gradual has updated */ function _getUpdatedGradualUser(address user) private view returns (UserGradual memory, bool) { UserGradual memory _userGradual = _userGraduals[user]; uint16 lastFinishedTrancheIndex = getLastFinishedTrancheIndex(); // 1. if user already updated in this tranche index, skip if (_userGradual.lastUpdatedTrancheIndex == lastFinishedTrancheIndex) { return (_userGradual, false); } // update user if it has maturing power if (_hasTranches(_userGradual)) { // 2. update fully-matured tranches uint16 lastMaturedIndex = _getLastMaturedIndex(); if (lastMaturedIndex > 0) { UserTranche memory oldestTranche = _getUserTranche(user, _userGradual.oldestTranchePosition); // update all fully-matured user tranches while (_hasTranches(_userGradual) && oldestTranche.index <= lastMaturedIndex) { // mature _matureOldestUsersTranche(_userGradual, oldestTranche); // get new user oldest tranche oldestTranche = _getUserTranche(user, _userGradual.oldestTranchePosition); } } // 3. update still maturing tranches if (_isMaturing(_userGradual, lastFinishedTrancheIndex)) { // get number of passed indexes uint56 indexesPassed = lastFinishedTrancheIndex - _userGradual.lastUpdatedTrancheIndex; // add new user matured power _userGradual.rawUnmaturedVotingPower += _userGradual.maturingAmount * indexesPassed; // last synced index _userGradual.lastUpdatedTrancheIndex = lastFinishedTrancheIndex; } } // update user last updated tranche index _userGradual.lastUpdatedTrancheIndex = lastFinishedTrancheIndex; return (_userGradual, true); } /** * @notice mature users oldest tranche, and update oldest with next user tranche * @dev this is called only if we know `oldestTranche` is mature * Updates are done im-memory * * @param _userGradual user gradual struct to update * @param oldestTranche users oldest struct (fully matured one) */ function _matureOldestUsersTranche(UserGradual memory _userGradual, UserTranche memory oldestTranche) private pure { uint16 fullyMaturedFinishedIndex = _getFullyMaturedAtFinishedIndex(oldestTranche.index); uint48 newMaturedVotingPower = oldestTranche.amount; // add new matured voting power // calculate number of passed indexes between last update until fully matured index uint56 indexesPassed = fullyMaturedFinishedIndex - _userGradual.lastUpdatedTrancheIndex; _userGradual.rawUnmaturedVotingPower += _userGradual.maturingAmount * indexesPassed; // update new fully-matured voting power uint56 newMaturedAsRawUnmatured = _getMaturedAsRawUnmaturedAmount(newMaturedVotingPower); // update user gradual values in respect of new fully-matured amount // remove new fully matured voting power from non matured raw one _userGradual.rawUnmaturedVotingPower -= newMaturedAsRawUnmatured; // add new fully-matured voting power _userGradual.maturedVotingPower += newMaturedVotingPower; // remove new fully-matured power from maturing amount _userGradual.maturingAmount -= newMaturedVotingPower; // add next tranche as oldest _setNextOldestUserTranchePosition(_userGradual); // update last updated index until fully matured index _userGradual.lastUpdatedTrancheIndex = fullyMaturedFinishedIndex; } /** * @notice returns index at which the maturing will finish * @dev * e.g. if FULL_POWER_TRANCHES_COUNT=2 and passing index=1, * maturing will complete at the end of index 2. * This is the index we return, similar to last finished index. * * @param index index from which to derive fully matured finished index */ function _getFullyMaturedAtFinishedIndex(uint256 index) private pure returns (uint16) { return uint16(index + FULL_POWER_TRANCHES_COUNT - 1); } /** * @notice updates user oldest tranche position to next one in memory * @dev this is done after an oldest tranche position matures * If oldest tranch position is same as latest one, all user * tranches have matured. In this case we remove tranhe positions from the user * * @param _userGradual user gradual struct to update */ function _setNextOldestUserTranchePosition(UserGradual memory _userGradual) private pure { // if oldest tranche is same as latest, this was the last tranche and we remove it from the user if ( _userGradual.oldestTranchePosition.arrayIndex == _userGradual.latestTranchePosition.arrayIndex && _userGradual.oldestTranchePosition.position == _userGradual.latestTranchePosition.position ) { // reset user tranches as all of them matured _userGradual.oldestTranchePosition = UserTranchePosition(0, 0); } else { // set next user tranche as oldest _userGradual.oldestTranchePosition = _getNextUserTranchePosition(_userGradual.oldestTranchePosition); } } /* ---------- GRADUAL POWER: GLOBAL HELPER FUNCTIONS ---------- */ /** * @notice returns total gradual voting power from `global` * @dev the returned amount is untrimmed * * @param global global gradual struct * @return totalGradualVotingPower total gradual voting power (fully-matured + maturing) */ function _getTotalGradualVotingPower(GlobalGradual memory global) private pure returns (uint256) { return _untrim(global.totalMaturedVotingPower) + _getMaturingVotingPowerFromRaw(_untrim(global.totalRawUnmaturedVotingPower)); } /** * @notice returns global tranche storage struct * @dev we return struct, so we can manipulate the storage in other functions * * @param index tranche index * @return tranche tranche storage struct */ function _getTranche(uint256 index) private view returns (Tranche storage) { uint256 arrayindex = index / TRANCHES_PER_WORD; GlobalTranches storage globalTranches = indexedGlobalTranches[arrayindex]; uint256 globalTranchesPosition = index % TRANCHES_PER_WORD; if (globalTranchesPosition == 0) { return globalTranches.zero; } else if (globalTranchesPosition == 1) { return globalTranches.one; } else if (globalTranchesPosition == 2) { return globalTranches.two; } else if (globalTranchesPosition == 3) { return globalTranches.three; } else { return globalTranches.four; } } /* ---------- GRADUAL POWER: USER HELPER FUNCTIONS ---------- */ /** * @notice gets `user` `tranche` at position * * @param user user address to get tranche from * @param userTranchePosition position to get the `tranche` from * @return tranche `user` tranche */ function _getUserTranche(address user, UserTranchePosition memory userTranchePosition) private view returns (UserTranche memory tranche) { UserTranches storage _userTranches = userTranches[user][userTranchePosition.arrayIndex]; if (userTranchePosition.position == 0) { tranche = _userTranches.zero; } else if (userTranchePosition.position == 1) { tranche = _userTranches.one; } else if (userTranchePosition.position == 2) { tranche = _userTranches.two; } else { tranche = _userTranches.three; } } /** * @notice return last matured tranche index * * @return lastMaturedIndex last matured tranche index */ function _getLastMaturedIndex() private view returns (uint16 lastMaturedIndex) { uint256 currentTrancheIndex = getCurrentTrancheIndex(); if (currentTrancheIndex > FULL_POWER_TRANCHES_COUNT) { unchecked { lastMaturedIndex = uint16(currentTrancheIndex - FULL_POWER_TRANCHES_COUNT); } } } /** * @notice returns the user gradual voting power (fully-matured and maturing) * @dev the returned amount is untrimmed * * @param _userGradual user gradual struct * @return userGradualVotingPower user gradual voting power (fully-matured + maturing) */ function _getUserGradualVotingPower(UserGradual memory _userGradual) private pure returns (uint256) { return _untrim(_userGradual.maturedVotingPower) + _getMaturingVotingPowerFromRaw(_untrim(_userGradual.rawUnmaturedVotingPower)); } /** * @notice returns next user tranche position, based on current one * * @param currentTranchePosition current user tranche position * @return nextTranchePosition next tranche position of `currentTranchePosition` */ function _getNextUserTranchePosition(UserTranchePosition memory currentTranchePosition) private pure returns (UserTranchePosition memory nextTranchePosition) { if (currentTranchePosition.arrayIndex == 0) { nextTranchePosition.arrayIndex = 1; } else { if (currentTranchePosition.position < 3) { nextTranchePosition.arrayIndex = currentTranchePosition.arrayIndex; nextTranchePosition.position = currentTranchePosition.position + 1; } else { nextTranchePosition.arrayIndex = currentTranchePosition.arrayIndex + 1; } } } /** * @notice check if user requires maturing * * @param _userGradual user gradual struct to update * @param lastFinishedTrancheIndex index of last finished tranche index * @return needsMaturing true if user needs maturing, else false */ function _isMaturing(UserGradual memory _userGradual, uint256 lastFinishedTrancheIndex) private pure returns (bool) { return _userGradual.lastUpdatedTrancheIndex < lastFinishedTrancheIndex && _hasTranches(_userGradual); } /** * @notice check if user gradual has any non-matured tranches * * @param _userGradual user gradual struct * @return hasTranches true if user has non-matured tranches */ function _hasTranches(UserGradual memory _userGradual) private pure returns (bool hasTranches) { if (_userGradual.oldestTranchePosition.arrayIndex > 0) { hasTranches = true; } } /* ---------- GRADUAL POWER: HELPER FUNCTIONS ---------- */ /** * @notice return trimmed amount * @dev `amount` is trimmed by `TRIM_SIZE`. * This is done so the amount can be represented in 48bits. * This still gives us enough accuracy so the core logic is not affected. * * @param amount amount to trim * @return trimmedAmount amount divided by `TRIM_SIZE` */ function _trim(uint256 amount) private pure returns (uint48) { return uint48(amount / TRIM_SIZE); } /** * @notice return trimmed amount rounding up if any dust left * * @param amount amount to trim * @return trimmedAmount amount divided by `TRIM_SIZE`, rounded up */ function _trimRoundUp(uint256 amount) private pure returns (uint48 trimmedAmount) { trimmedAmount = _trim(amount); if (_untrim(trimmedAmount) < amount) { unchecked { trimmedAmount++; } } } /** * @notice untrim `trimmedAmount` in respect to `TRIM_SIZE` * * @param trimmedAmount amount previously trimemd * @return untrimmedAmount untrimmed amount */ function _untrim(uint256 trimmedAmount) private pure returns (uint256) { unchecked { return trimmedAmount * TRIM_SIZE; } } /** * @notice calculates voting power from raw unmatured * * @param rawMaturingVotingPower raw maturing voting power amount * @return maturingVotingPower actual maturing power amount */ function _getMaturingVotingPowerFromRaw(uint256 rawMaturingVotingPower) private pure returns (uint256) { return rawMaturingVotingPower / FULL_POWER_TRANCHES_COUNT; } /** * @notice Returns amount represented in raw unmatured value * @dev used to substract fully-matured amount from raw unmatured, when amount matures * * @param amount matured amount * @return asRawUnmatured `amount` multiplied by `FULL_POWER_TRANCHES_COUNT` (raw unmatured amount) */ function _getMaturedAsRawUnmaturedAmount(uint48 amount) private pure returns (uint56) { unchecked { return uint56(amount * FULL_POWER_TRANCHES_COUNT); } } /* ========== OWNER FUNCTIONS ========== */ /** * @notice Sets or resets the instant minter address * * Requirements: * * - the caller must be the owner of the contract * - the minter must not be the zero address * * @param _minter address to set * @param _set true to set, false to reset */ function setMinter(address _minter, bool _set) external onlyOwner { require(_minter != address(0), "voSPOOL::setMinter: minter cannot be the zero address"); minters[_minter] = _set; emit MinterSet(_minter, _set); } /** * @notice Sets or resets the gradual minter address * * Requirements: * * - the caller must be the owner of the contract * - the minter must not be the zero address * * @param _gradualMinter address to set * @param _set true to set, false to reset */ function setGradualMinter(address _gradualMinter, bool _set) external onlyOwner { require(_gradualMinter != address(0), "voSPOOL::setGradualMinter: gradual minter cannot be the zero address"); gradualMinters[_gradualMinter] = _set; emit GradualMinterSet(_gradualMinter, _set); } /* ========== RESTRICTION FUNCTIONS ========== */ /** * @notice Ensures the caller is the instant minter */ function _onlyMinter() private view { require(minters[msg.sender], "voSPOOL::_onlyMinter: Insufficient Privileges"); } /** * @notice Ensures the caller is the gradual minter */ function _onlyGradualMinter() private view { require(gradualMinters[msg.sender], "voSPOOL::_onlyGradualMinter: Insufficient Privileges"); } /* ========== MODIFIERS ========== */ /** * @notice Throws if the caller is not the instant miter */ modifier onlyMinter() { _onlyMinter(); _; } /** * @notice Throws if the caller is not the gradual minter */ modifier onlyGradualMinter() { _onlyGradualMinter(); _; } /** * @notice Update global gradual values */ modifier updateGradual() { _updateGradual(); _; } /** * @notice Update user gradual values */ modifier updateGradualUser(address user) { _updateGradualUser(user); _; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.8.13; import "./interfaces/ISpoolOwner.sol"; abstract contract SpoolOwnable { ISpoolOwner internal immutable spoolOwner; constructor(ISpoolOwner _spoolOwner) { require( address(_spoolOwner) != address(0), "SpoolOwnable::constructor: Spool owner contract address cannot be 0" ); spoolOwner = _spoolOwner; } function isSpoolOwner() internal view returns(bool) { return spoolOwner.isSpoolOwner(msg.sender); } function _onlyOwner() internal view { require(isSpoolOwner(), "SpoolOwnable::onlyOwner: Caller is not the Spool owner"); } modifier onlyOwner() { _onlyOwner(); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.13; interface ISpoolOwner { function isSpoolOwner(address user) external view returns(bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.13; /* ========== STRUCTS ========== */ /** * @notice global gradual struct * @member totalMaturedVotingPower total fully-matured voting power amount * @member totalMaturingAmount total maturing amount (amount of power that is accumulating every week for 1/156 of the amount) * @member totalRawUnmaturedVotingPower total raw voting power still maturing every tranche (totalRawUnmaturedVotingPower/156 is its voting power) * @member lastUpdatedTrancheIndex last (finished) tranche index global gradual has updated */ struct GlobalGradual { uint48 totalMaturedVotingPower; uint48 totalMaturingAmount; uint56 totalRawUnmaturedVotingPower; uint16 lastUpdatedTrancheIndex; } /** * @notice user tranche position struct, pointing at user tranche * @dev points at `userTranches` mapping * @member arrayIndex points at `userTranches` * @member position points at UserTranches position from zero to three (zero, one, two, or three) */ struct UserTranchePosition { uint16 arrayIndex; uint8 position; } /** * @notice user gradual struct, similar to global gradual holds user gragual voting power values * @dev points at `userTranches` mapping * @member maturedVotingPower users fully-matured voting power amount * @member maturingAmount users maturing amount * @member rawUnmaturedVotingPower users raw voting power still maturing every tranche * @member oldestTranchePosition UserTranchePosition pointing at the oldest unmatured UserTranche * @member latestTranchePosition UserTranchePosition pointing at the latest unmatured UserTranche * @member lastUpdatedTrancheIndex last (finished) tranche index user gradual has updated */ struct UserGradual { uint48 maturedVotingPower; // matured voting amount, power accumulated and older than FULL_POWER_TIME, not accumulating anymore uint48 maturingAmount; // total maturing amount (also maximum matured) uint56 rawUnmaturedVotingPower; // current user raw unmatured voting power (increases every new tranche), actual unmatured voting power can be calculated as unmaturedVotingPower / FULL_POWER_TRANCHES_COUNT UserTranchePosition oldestTranchePosition; // if arrayIndex is 0, user has no tranches (even if `latestTranchePosition` is not empty) UserTranchePosition latestTranchePosition; // can only increment, in case of tranche removal, next time user gradually mints we point at tranche at next position uint16 lastUpdatedTrancheIndex; } /** * @title Spool DAO Voting Token interface */ interface IVoSPOOL { /* ========== FUNCTIONS ========== */ function mint(address, uint256) external; function burn(address, uint256) external; function mintGradual(address, uint256) external; function burnGradual( address, uint256, bool ) external; function updateVotingPower() external; function updateUserVotingPower(address user) external; function getTotalGradualVotingPower() external returns (uint256); function getUserGradualVotingPower(address user) external returns (uint256); function getNotUpdatedUserGradual(address user) external view returns (UserGradual memory); function getNotUpdatedGlobalGradual() external view returns (GlobalGradual memory); function getCurrentTrancheIndex() external view returns (uint16); function getLastFinishedTrancheIndex() external view returns (uint16); /* ========== EVENTS ========== */ event Minted(address indexed recipient, uint256 amount); event Burned(address indexed source, uint256 amount); event GradualMinted(address indexed recipient, uint256 amount); event GradualBurned(address indexed source, uint256 amount, bool burnAll); event GlobalGradualUpdated( uint16 indexed lastUpdatedTrancheIndex, uint48 totalMaturedVotingPower, uint48 totalMaturingAmount, uint56 totalRawUnmaturedVotingPower ); event UserGradualUpdated( address indexed user, uint16 indexed lastUpdatedTrancheIndex, uint48 maturedVotingPower, uint48 maturingAmount, uint56 rawUnmaturedVotingPower ); event MinterSet(address indexed minter, bool set); event GradualMinterSet(address indexed minter, bool set); }
* @notice update gradual user struct storage @param user user address to update/
function _updateGradualUser(address user) private { (UserGradual memory _userGradual, bool didUpdate) = _getUpdatedGradualUser(user); if (didUpdate) { _userGraduals[user] = _userGradual; emit UserGradualUpdated( user, _userGradual.lastUpdatedTrancheIndex, _userGradual.maturedVotingPower, _userGradual.maturingAmount, _userGradual.rawUnmaturedVotingPower ); } }
233,224
[ 1, 2725, 6058, 1462, 729, 1958, 2502, 225, 729, 729, 1758, 358, 1089, 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, 389, 2725, 30420, 1462, 1299, 12, 2867, 729, 13, 3238, 288, 203, 202, 202, 12, 1299, 30420, 1462, 3778, 389, 1355, 30420, 1462, 16, 1426, 5061, 1891, 13, 273, 389, 588, 7381, 30420, 1462, 1299, 12, 1355, 1769, 203, 202, 202, 430, 261, 14044, 1891, 13, 288, 203, 1082, 202, 67, 1355, 14571, 2544, 1031, 63, 1355, 65, 273, 389, 1355, 30420, 1462, 31, 203, 1082, 202, 18356, 2177, 30420, 1462, 7381, 12, 203, 9506, 202, 1355, 16, 203, 9506, 202, 67, 1355, 30420, 1462, 18, 2722, 7381, 17730, 18706, 1016, 16, 203, 9506, 202, 67, 1355, 30420, 1462, 18, 81, 1231, 72, 58, 17128, 13788, 16, 203, 9506, 202, 67, 1355, 30420, 1462, 18, 7373, 4017, 6275, 16, 203, 9506, 202, 67, 1355, 30420, 1462, 18, 1899, 984, 81, 1231, 72, 58, 17128, 13788, 203, 1082, 202, 1769, 203, 202, 202, 97, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x1F60b3be173EA9B5D1301Dd39f8A7cA70B4ABee4/sources/contracts/padisah.sol
* @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]; }
5,578,023
[ 1, 9704, 288, 45, 654, 39, 27, 5340, 3572, 25121, 17, 2316, 21268, 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, 1147, 21268, 12, 11890, 5034, 770, 13, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 1615, 411, 4232, 39, 27, 5340, 3572, 25121, 18, 4963, 3088, 1283, 9334, 315, 654, 39, 27, 5340, 3572, 25121, 30, 2552, 770, 596, 434, 4972, 8863, 203, 3639, 327, 389, 454, 5157, 63, 1615, 15533, 203, 565, 289, 203, 203, 27699, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; 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 { 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); } interface IERC20Metadata is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); 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; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } 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 9; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } 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; // assert(a == b * c + a % b); // There is no case in which this doesn't hold 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; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } function div(int256 a, int256 b) internal pure returns (int256) { require(b != -1 || a != MIN_INT256); return a / b; } 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; } 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; } function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } 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 neversellin is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; mapping (address => bool) private _isSniper; bool private _swapping; uint256 private _launchTime; address public feeWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public tradingActive = 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 private _buyMarketingFee; uint256 private _buyLiquidityFee; uint256 private _buyDevFee; uint256 public sellTotalFees; uint256 private _sellMarketingFee; uint256 private _sellLiquidityFee; uint256 private _sellDevFee; uint256 private _tokensForMarketing; uint256 private _tokensForLiquidity; uint256 private _tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // 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 UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event feeWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("Never Sellin", "NEVA") { 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 = 2; uint256 buyLiquidityFee = 1; uint256 buyDevFee = 9; uint256 sellMarketingFee = 2; uint256 sellLiquidityFee = 1; uint256 sellDevFee = 9; uint256 totalSupply = 1e18 * 1e9; maxTransactionAmount = totalSupply * 1 / 100; // 1% maxTransactionAmountTxn maxWallet = totalSupply * 3 / 100; // 3% maxWallet swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet _buyMarketingFee = buyMarketingFee; _buyLiquidityFee = buyLiquidityFee; _buyDevFee = buyDevFee; buyTotalFees = _buyMarketingFee + _buyLiquidityFee + _buyDevFee; _sellMarketingFee = sellMarketingFee; _sellLiquidityFee = sellLiquidityFee; _sellDevFee = sellDevFee; sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee; feeWallet = address(owner()); // set as fee wallet // exclude from paying fees or having max transaction amount 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); } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; _launchTime = block.timestamp; } // 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 sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000) / 1e9, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * 1e9; } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e9, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * 1e9; } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } function updateBuyFees(uint256 marketingFee, uint256 liquidityFee, uint256 devFee) external onlyOwner { _buyMarketingFee = marketingFee; _buyLiquidityFee = liquidityFee; _buyDevFee = devFee; buyTotalFees = _buyMarketingFee + _buyLiquidityFee + _buyDevFee; require(buyTotalFees <= 10, "Must keep fees at 10% or less"); } function updateSellFees(uint256 marketingFee, uint256 liquidityFee, uint256 devFee) external onlyOwner { _sellMarketingFee = marketingFee; _sellLiquidityFee = liquidityFee; _sellDevFee = devFee; sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee; require(sellTotalFees <= 15, "Must keep fees at 15% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public 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 updateFeeWallet(address newWallet) external onlyOwner { emit feeWalletUpdated(newWallet, feeWallet); feeWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function setSnipers(address[] memory snipers_) public onlyOwner() { for (uint i = 0; i < snipers_.length; i++) { if (snipers_[i] != uniswapV2Pair && snipers_[i] != address(uniswapV2Router)) { _isSniper[snipers_[i]] = true; } } } function delSnipers(address[] memory snipers_) public onlyOwner() { for (uint i = 0; i < snipers_.length; i++) { _isSniper[snipers_[i]] = false; } } function isSniper(address addr) public view returns (bool) { return _isSniper[addr]; } 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(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap."); if (amount == 0) { super._transfer(from, to, 0); return; } if (block.timestamp == _launchTime) _isSniper[to] = true; 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."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } // when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if (!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && !_swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { _swapping = true; swapBack(); _swapping = false; } bool takeFee = !_swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if (takeFee) { // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); _tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees; _tokensForDev += fees * _sellDevFee / sellTotalFees; _tokensForMarketing += fees * _sellMarketingFee / sellTotalFees; } // on buy else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); _tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees; _tokensForDev += fees * _buyDevFee / buyTotalFees; _tokensForMarketing += fees * _buyMarketingFee / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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 owner(), block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = _tokensForLiquidity + _tokensForMarketing + _tokensForDev; if (contractBalance == 0 || totalTokensToSwap == 0) return; if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } // 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; if (liquidityTokens > 0 && ethForLiquidity > 0) { _addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, _tokensForLiquidity); } } function withdrawFees() external { payable(feeWallet).transfer(address(this).balance); } receive() external payable {} }
exclude from paying fees or having max transaction amount
constructor() ERC20("Never Sellin", "NEVA") { 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 = 2; uint256 buyLiquidityFee = 1; uint256 buyDevFee = 9; uint256 sellMarketingFee = 2; uint256 sellLiquidityFee = 1; uint256 sellDevFee = 9; uint256 totalSupply = 1e18 * 1e9; _buyMarketingFee = buyMarketingFee; _buyLiquidityFee = buyLiquidityFee; _buyDevFee = buyDevFee; buyTotalFees = _buyMarketingFee + _buyLiquidityFee + _buyDevFee; _sellMarketingFee = sellMarketingFee; _sellLiquidityFee = sellLiquidityFee; _sellDevFee = sellDevFee; sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
6,262,312
[ 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, 50, 6084, 348, 1165, 267, 3113, 315, 5407, 27722, 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, 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, 540, 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, 540, 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, 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, 540, 203, 3639, 2254, 5034, 30143, 3882, 21747, 14667, 273, 576, 31, 203, 3639, 2254, 5034, 30143, 48, 18988, 24237, 14667, 273, 404, 31, 203, 3639, 2254, 5034, 30143, 8870, 14667, 273, 2468, 31, 203, 203, 3639, 2254, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-03-10 */ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.7.1; // File: contracts/BondToken_and_GDOTC/util/TransferETHInterface.sol interface TransferETHInterface { receive() external payable; event LogTransferETH(address indexed from, address indexed to, uint256 value); } // File: contracts/BondToken_and_GDOTC/util/TransferETH.sol abstract contract TransferETH is TransferETHInterface { receive() external payable override { emit LogTransferETH(msg.sender, address(this), msg.value); } function _hasSufficientBalance(uint256 amount) internal view returns (bool ok) { address thisContract = address(this); return amount <= thisContract.balance; } /** * @notice transfer `amount` ETH to the `recipient` account with emitting log */ function _transferETH( address payable recipient, uint256 amount, string memory errorMessage ) internal { require(_hasSufficientBalance(amount), errorMessage); (bool success, ) = recipient.call{value: amount}(""); // solhint-disable-line avoid-low-level-calls require(success, "transferring Ether failed"); emit LogTransferETH(address(this), recipient, amount); } function _transferETH(address payable recipient, uint256 amount) internal { _transferETH(recipient, amount, "TransferETH: transfer amount exceeds balance"); } } // File: @openzeppelin/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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/math/SignedSafeMath.sol /** * @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; } } // File: @openzeppelin/contracts/utils/SafeCast.sol /** * @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 uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // File: contracts/BondToken_and_GDOTC/math/UseSafeMath.sol /** * @notice ((a - 1) / b) + 1 = (a + b -1) / b * for example a.add(10**18 -1).div(10**18) = a.sub(1).div(10**18) + 1 */ library SafeMathDivRoundUp { using SafeMath for uint256; function divRoundUp( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { if (a == 0) { return 0; } require(b > 0, errorMessage); return ((a - 1) / b) + 1; } function divRoundUp(uint256 a, uint256 b) internal pure returns (uint256) { return divRoundUp(a, b, "SafeMathDivRoundUp: modulo by zero"); } } /** * @title UseSafeMath * @dev One can use SafeMath for not only uint256 but also uin64 or uint16, * and also can use SafeCast for uint256. * For example: * uint64 a = 1; * uint64 b = 2; * a = a.add(b).toUint64() // `a` become 3 as uint64 * In addition, one can use SignedSafeMath and SafeCast.toUint256(int256) for int256. * In the case of the operation to the uint64 value, one needs to cast the value into int256 in * advance to use `sub` as SignedSafeMath.sub not SafeMath.sub. * For example: * int256 a = 1; * uint64 b = 2; * int256 c = 3; * a = a.add(int256(b).sub(c)); // `a` becomes 0 as int256 * b = a.toUint256().toUint64(); // `b` becomes 0 as uint64 */ abstract contract UseSafeMath { using SafeMath for uint256; using SafeMathDivRoundUp for uint256; using SafeMath for uint64; using SafeMathDivRoundUp for uint64; using SafeMath for uint16; using SignedSafeMath for int256; using SafeCast for uint256; using SafeCast for int256; } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (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: contracts/BondToken_and_GDOTC/bondToken/BondTokenInterface.sol interface BondTokenInterface is IERC20 { event LogExpire(uint128 rateNumerator, uint128 rateDenominator, bool firstTime); function mint(address account, uint256 amount) external returns (bool success); function expire(uint128 rateNumerator, uint128 rateDenominator) external returns (bool firstTime); function simpleBurn(address account, uint256 amount) external returns (bool success); function burn(uint256 amount) external returns (bool success); function burnAll() external returns (uint256 amount); function getRate() external view returns (uint128 rateNumerator, uint128 rateDenominator); } // File: contracts/BondToken_and_GDOTC/oracle/LatestPriceOracleInterface.sol /** * @dev Interface of the price oracle. */ interface LatestPriceOracleInterface { /** * @dev Returns `true`if oracle is working. */ function isWorking() external returns (bool); /** * @dev Returns the last updated price. Decimals is 8. **/ function latestPrice() external returns (uint256); /** * @dev Returns the timestamp of the last updated price. */ function latestTimestamp() external returns (uint256); } // File: contracts/BondToken_and_GDOTC/oracle/PriceOracleInterface.sol /** * @dev Interface of the price oracle. */ interface PriceOracleInterface is LatestPriceOracleInterface { /** * @dev Returns the latest id. The id start from 1 and increments by 1. */ function latestId() external returns (uint256); /** * @dev Returns the historical price specified by `id`. Decimals is 8. */ function getPrice(uint256 id) external returns (uint256); /** * @dev Returns the timestamp of historical price specified by `id`. */ function getTimestamp(uint256 id) external returns (uint256); } // File: contracts/BondToken_and_GDOTC/bondMaker/BondMakerInterface.sol interface BondMakerInterface { event LogNewBond( bytes32 indexed bondID, address indexed bondTokenAddress, uint256 indexed maturity, bytes32 fnMapID ); event LogNewBondGroup( uint256 indexed bondGroupID, uint256 indexed maturity, uint64 indexed sbtStrikePrice, bytes32[] bondIDs ); event LogIssueNewBonds(uint256 indexed bondGroupID, address indexed issuer, uint256 amount); event LogReverseBondGroupToCollateral( uint256 indexed bondGroupID, address indexed owner, uint256 amount ); event LogExchangeEquivalentBonds( address indexed owner, uint256 indexed inputBondGroupID, uint256 indexed outputBondGroupID, uint256 amount ); event LogLiquidateBond(bytes32 indexed bondID, uint128 rateNumerator, uint128 rateDenominator); function registerNewBond(uint256 maturity, bytes calldata fnMap) external returns ( bytes32 bondID, address bondTokenAddress, bytes32 fnMapID ); function registerNewBondGroup(bytes32[] calldata bondIDList, uint256 maturity) external returns (uint256 bondGroupID); function reverseBondGroupToCollateral(uint256 bondGroupID, uint256 amount) external returns (bool success); function exchangeEquivalentBonds( uint256 inputBondGroupID, uint256 outputBondGroupID, uint256 amount, bytes32[] calldata exceptionBonds ) external returns (bool); function liquidateBond(uint256 bondGroupID, uint256 oracleHintID) external returns (uint256 totalPayment); function collateralAddress() external view returns (address); function oracleAddress() external view returns (PriceOracleInterface); function feeTaker() external view returns (address); function decimalsOfBond() external view returns (uint8); function decimalsOfOraclePrice() external view returns (uint8); function maturityScale() external view returns (uint256); function nextBondGroupID() external view returns (uint256); function getBond(bytes32 bondID) external view returns ( address bondAddress, uint256 maturity, uint64 solidStrikePrice, bytes32 fnMapID ); function getFnMap(bytes32 fnMapID) external view returns (bytes memory fnMap); function getBondGroup(uint256 bondGroupID) external view returns (bytes32[] memory bondIDs, uint256 maturity); function generateFnMapID(bytes calldata fnMap) external view returns (bytes32 fnMapID); function generateBondID(uint256 maturity, bytes calldata fnMap) external view returns (bytes32 bondID); } // File: contracts/BondToken_and_GDOTC/bondMaker/BondMakerCollateralizedErc20Interface.sol interface BondMakerCollateralizedErc20Interface is BondMakerInterface { function issueNewBonds(uint256 bondGroupID, uint256 amount) external returns (uint256 bondAmount); } // File: contracts/BondToken_and_GDOTC/util/Time.sol abstract contract Time { function _getBlockTimestampSec() internal view returns (uint256 unixtimesec) { unixtimesec = block.timestamp; // solhint-disable-line not-rely-on-time } } // File: @openzeppelin/contracts/GSN/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 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/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) { // 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); } } } } // File: @openzeppelin/contracts/token/ERC20/ERC20.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_) { _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 internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: @openzeppelin/contracts/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 () { 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; } } // File: contracts/BondToken_and_GDOTC/bondToken/BondToken.sol abstract contract BondToken is Ownable, BondTokenInterface, ERC20 { using SafeMath for uint256; struct Frac128x128 { uint128 numerator; uint128 denominator; } Frac128x128 internal _rate; constructor( string memory name, string memory symbol, uint8 decimals ) ERC20(name, symbol) { _setupDecimals(decimals); } function mint(address account, uint256 amount) public virtual override onlyOwner returns (bool success) { require(!_isExpired(), "this token contract has expired"); _mint(account, amount); return true; } function transfer(address recipient, uint256 amount) public override(ERC20, IERC20) returns (bool success) { _transfer(msg.sender, recipient, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override(ERC20, IERC20) returns (bool success) { _transfer(sender, recipient, amount); _approve( sender, msg.sender, allowance(sender, msg.sender).sub(amount, "ERC20: transfer amount exceeds allowance") ); return true; } /** * @dev Record the settlement price at maturity in the form of a fraction and let the bond * token expire. */ function expire(uint128 rateNumerator, uint128 rateDenominator) public override onlyOwner returns (bool isFirstTime) { isFirstTime = !_isExpired(); if (isFirstTime) { _setRate(Frac128x128(rateNumerator, rateDenominator)); } emit LogExpire(rateNumerator, rateDenominator, isFirstTime); } function simpleBurn(address from, uint256 amount) public override onlyOwner returns (bool) { if (amount > balanceOf(from)) { return false; } _burn(from, amount); return true; } function burn(uint256 amount) public override returns (bool success) { if (!_isExpired()) { return false; } _burn(msg.sender, amount); if (_rate.numerator != 0) { uint8 decimalsOfCollateral = _getCollateralDecimals(); uint256 withdrawAmount = _applyDecimalGap(amount, decimals(), decimalsOfCollateral) .mul(_rate.numerator) .div(_rate.denominator); _sendCollateralTo(msg.sender, withdrawAmount); } return true; } function burnAll() public override returns (uint256 amount) { amount = balanceOf(msg.sender); bool success = burn(amount); if (!success) { amount = 0; } } /** * @dev rateDenominator never be zero due to div() function, thus initial _rateDenominator is 0 * can be used for flag of non-expired; */ function _isExpired() internal view returns (bool) { return _rate.denominator != 0; } function getRate() public view override returns (uint128 rateNumerator, uint128 rateDenominator) { rateNumerator = _rate.numerator; rateDenominator = _rate.denominator; } function _setRate(Frac128x128 memory rate) internal { require( rate.denominator != 0, "system error: the exchange rate must be non-negative number" ); _rate = rate; } /** * @dev removes a decimal gap from rate. */ function _applyDecimalGap( uint256 baseAmount, uint8 decimalsOfBase, uint8 decimalsOfQuote ) internal pure returns (uint256 quoteAmount) { uint256 n; uint256 d; if (decimalsOfBase > decimalsOfQuote) { d = decimalsOfBase - decimalsOfQuote; } else if (decimalsOfBase < decimalsOfQuote) { n = decimalsOfQuote - decimalsOfBase; } // The consequent multiplication would overflow under extreme and non-blocking circumstances. require(n < 19 && d < 19, "decimal gap needs to be lower than 19"); quoteAmount = baseAmount.mul(10**n).div(10**d); } function _getCollateralDecimals() internal view virtual returns (uint8); function _sendCollateralTo(address receiver, uint256 amount) internal virtual; } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for 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/BondToken_and_GDOTC/bondToken/BondTokenCollateralizedErc20.sol contract BondTokenCollateralizedErc20 is BondToken { using SafeERC20 for ERC20; ERC20 internal immutable COLLATERALIZED_TOKEN; constructor( ERC20 collateralizedTokenAddress, string memory name, string memory symbol, uint8 decimals ) BondToken(name, symbol, decimals) { COLLATERALIZED_TOKEN = collateralizedTokenAddress; } function _getCollateralDecimals() internal view override returns (uint8) { return COLLATERALIZED_TOKEN.decimals(); } function _sendCollateralTo(address receiver, uint256 amount) internal override { COLLATERALIZED_TOKEN.safeTransfer(receiver, amount); } } // File: contracts/BondToken_and_GDOTC/bondToken/BondTokenCollateralizedEth.sol contract BondTokenCollateralizedEth is BondToken, TransferETH { constructor( string memory name, string memory symbol, uint8 decimals ) BondToken(name, symbol, decimals) {} function _getCollateralDecimals() internal pure override returns (uint8) { return 18; } function _sendCollateralTo(address receiver, uint256 amount) internal override { _transferETH(payable(receiver), amount); } } // File: contracts/BondToken_and_GDOTC/bondToken/BondTokenFactory.sol contract BondTokenFactory { address private constant ETH = address(0); function createBondToken( address collateralizedTokenAddress, string calldata name, string calldata symbol, uint8 decimals ) external returns (address createdBondAddress) { if (collateralizedTokenAddress == ETH) { BondTokenCollateralizedEth bond = new BondTokenCollateralizedEth( name, symbol, decimals ); bond.transferOwnership(msg.sender); return address(bond); } else { BondTokenCollateralizedErc20 bond = new BondTokenCollateralizedErc20( ERC20(collateralizedTokenAddress), name, symbol, decimals ); bond.transferOwnership(msg.sender); return address(bond); } } } // File: contracts/BondToken_and_GDOTC/util/Polyline.sol contract Polyline { struct Point { uint64 x; // Value of the x-axis of the x-y plane uint64 y; // Value of the y-axis of the x-y plane } struct LineSegment { Point left; // The left end of the line definition range Point right; // The right end of the line definition range } /** * @notice Return the value of y corresponding to x on the given line. line in the form of * a rational number (numerator / denominator). * If you treat a line as a line segment instead of a line, you should run * includesDomain(line, x) to check whether x is included in the line's domain or not. * @dev To guarantee accuracy, the bit length of the denominator must be greater than or equal * to the bit length of x, and the bit length of the numerator must be greater than or equal * to the sum of the bit lengths of x and y. */ function _mapXtoY(LineSegment memory line, uint64 x) internal pure returns (uint128 numerator, uint64 denominator) { int256 x1 = int256(line.left.x); int256 y1 = int256(line.left.y); int256 x2 = int256(line.right.x); int256 y2 = int256(line.right.y); require(x2 > x1, "must be left.x < right.x"); denominator = uint64(x2 - x1); // Calculate y = ((x2 - x) * y1 + (x - x1) * y2) / (x2 - x1) // in the form of a fraction (numerator / denominator). int256 n = (x - x1) * y2 + (x2 - x) * y1; require(n >= 0, "underflow n"); require(n < 2**128, "system error: overflow n"); numerator = uint128(n); } /** * @notice Checking that a line segment is a valid format. */ function assertLineSegment(LineSegment memory segment) internal pure { uint64 x1 = segment.left.x; uint64 x2 = segment.right.x; require(x1 < x2, "must be left.x < right.x"); } /** * @notice Checking that a polyline is a valid format. */ function assertPolyline(LineSegment[] memory polyline) internal pure { uint256 numOfSegment = polyline.length; require(numOfSegment != 0, "polyline must not be empty array"); LineSegment memory leftSegment = polyline[0]; // mutable int256 gradientNumerator = int256(leftSegment.right.y) - int256(leftSegment.left.y); // mutable int256 gradientDenominator = int256(leftSegment.right.x) - int256(leftSegment.left.x); // mutable // The beginning of the first line segment's domain is 0. require( leftSegment.left.x == uint64(0), "the x coordinate of left end of the first segment must be 0" ); // The value of y when x is 0 is 0. require( leftSegment.left.y == uint64(0), "the y coordinate of left end of the first segment must be 0" ); // Making sure that the first line segment is a correct format. assertLineSegment(leftSegment); // The end of the domain of a segment and the beginning of the domain of the adjacent // segment must coincide. LineSegment memory rightSegment; // mutable for (uint256 i = 1; i < numOfSegment; i++) { rightSegment = polyline[i]; // Make sure that the i-th line segment is a correct format. assertLineSegment(rightSegment); // Checking that the x-coordinates are same. require( leftSegment.right.x == rightSegment.left.x, "given polyline has an undefined domain." ); // Checking that the y-coordinates are same. require( leftSegment.right.y == rightSegment.left.y, "given polyline is not a continuous function" ); int256 nextGradientNumerator = int256(rightSegment.right.y) - int256(rightSegment.left.y); int256 nextGradientDenominator = int256(rightSegment.right.x) - int256(rightSegment.left.x); require( nextGradientNumerator * gradientDenominator != nextGradientDenominator * gradientNumerator, "the sequential segments must not have the same gradient" ); leftSegment = rightSegment; gradientNumerator = nextGradientNumerator; gradientDenominator = nextGradientDenominator; } // rightSegment is lastSegment // About the last line segment. require( gradientNumerator >= 0 && gradientNumerator <= gradientDenominator, "the gradient of last line segment must be non-negative, and equal to or less than 1" ); } /** * @notice zip a LineSegment structure to uint256 * @return zip uint256( 0 ... 0 | x1 | y1 | x2 | y2 ) */ function zipLineSegment(LineSegment memory segment) internal pure returns (uint256 zip) { uint256 x1U256 = uint256(segment.left.x) << (64 + 64 + 64); // uint64 uint256 y1U256 = uint256(segment.left.y) << (64 + 64); // uint64 uint256 x2U256 = uint256(segment.right.x) << 64; // uint64 uint256 y2U256 = uint256(segment.right.y); // uint64 zip = x1U256 | y1U256 | x2U256 | y2U256; } /** * @notice unzip uint256 to a LineSegment structure */ function unzipLineSegment(uint256 zip) internal pure returns (LineSegment memory) { uint64 x1 = uint64(zip >> (64 + 64 + 64)); uint64 y1 = uint64(zip >> (64 + 64)); uint64 x2 = uint64(zip >> 64); uint64 y2 = uint64(zip); return LineSegment({left: Point({x: x1, y: y1}), right: Point({x: x2, y: y2})}); } /** * @notice unzip the fnMap to uint256[]. */ function decodePolyline(bytes memory fnMap) internal pure returns (uint256[] memory) { return abi.decode(fnMap, (uint256[])); } } // File: contracts/BondToken_and_GDOTC/bondMaker/BondMaker.sol abstract contract BondMaker is UseSafeMath, BondMakerInterface, Time, Polyline { using SafeMath for uint256; using SafeMathDivRoundUp for uint256; using SafeMath for uint64; uint8 internal immutable DECIMALS_OF_BOND; uint8 internal immutable DECIMALS_OF_ORACLE_PRICE; address internal immutable FEE_TAKER; uint256 internal immutable MATURITY_SCALE; PriceOracleInterface internal immutable _oracleContract; uint256 internal _nextBondGroupID = 1; /** * @dev The contents in this internal storage variable can be seen by getBond function. */ struct BondInfo { uint256 maturity; BondTokenInterface contractInstance; uint64 strikePrice; bytes32 fnMapID; } mapping(bytes32 => BondInfo) internal _bonds; /** * @dev The contents in this internal storage variable can be seen by getFnMap function. */ mapping(bytes32 => LineSegment[]) internal _registeredFnMap; /** * @dev The contents in this internal storage variable can be seen by getBondGroup function. */ struct BondGroup { bytes32[] bondIDs; uint256 maturity; } mapping(uint256 => BondGroup) internal _bondGroupList; constructor( PriceOracleInterface oracleAddress, address feeTaker, uint256 maturityScale, uint8 decimalsOfBond, uint8 decimalsOfOraclePrice ) { require(address(oracleAddress) != address(0), "oracleAddress should be non-zero address"); _oracleContract = oracleAddress; require(decimalsOfBond < 19, "the decimals of bond must be less than 19"); DECIMALS_OF_BOND = decimalsOfBond; require(decimalsOfOraclePrice < 19, "the decimals of oracle price must be less than 19"); DECIMALS_OF_ORACLE_PRICE = decimalsOfOraclePrice; require(feeTaker != address(0), "the fee taker must be non-zero address"); FEE_TAKER = feeTaker; require(maturityScale != 0, "MATURITY_SCALE must be positive"); MATURITY_SCALE = maturityScale; } /** * @notice Create bond token contract. * The name of this bond token is its bond ID. * @dev To convert bytes32 to string, encode its bond ID at first, then convert to string. * The symbol of any bond token with bond ID is either SBT or LBT; * As SBT is a special case of bond token, any bond token which does not match to the form of * SBT is defined as LBT. */ function registerNewBond(uint256 maturity, bytes calldata fnMap) external virtual override returns ( bytes32, address, bytes32 ) { _assertBeforeMaturity(maturity); require(maturity < _getBlockTimestampSec() + 365 days, "the maturity is too far"); require( maturity % MATURITY_SCALE == 0, "the maturity must be the multiple of MATURITY_SCALE" ); bytes32 bondID = generateBondID(maturity, fnMap); // Check if the same form of bond is already registered. // Cannot detect if the bond is described in a different polyline while two are // mathematically equivalent. require( address(_bonds[bondID].contractInstance) == address(0), "the bond type has been already registered" ); // Register function mapping if necessary. bytes32 fnMapID = generateFnMapID(fnMap); uint64 sbtStrikePrice; if (_registeredFnMap[fnMapID].length == 0) { uint256[] memory polyline = decodePolyline(fnMap); for (uint256 i = 0; i < polyline.length; i++) { _registeredFnMap[fnMapID].push(unzipLineSegment(polyline[i])); } LineSegment[] memory segments = _registeredFnMap[fnMapID]; assertPolyline(segments); require(!_isBondWorthless(segments), "the bond is 0-value at any price"); sbtStrikePrice = _getSbtStrikePrice(segments); } else { LineSegment[] memory segments = _registeredFnMap[fnMapID]; sbtStrikePrice = _getSbtStrikePrice(segments); } BondTokenInterface bondTokenContract = _createNewBondToken(maturity, fnMap); // Set bond info to storage. _bonds[bondID] = BondInfo({ maturity: maturity, contractInstance: bondTokenContract, strikePrice: sbtStrikePrice, fnMapID: fnMapID }); emit LogNewBond(bondID, address(bondTokenContract), maturity, fnMapID); return (bondID, address(bondTokenContract), fnMapID); } /** * @dev Count the number of the end points on x axis. In the case of a simple SBT/LBT split, * 3 for SBT plus 3 for LBT equals to 6. * In the case of SBT with the strike price 100, (x,y) = (0,0), (100,100), (200,100) defines * the form of SBT on the field. * In the case of LBT with the strike price 100, (x,y) = (0,0), (100,0), (200,100) defines * the form of LBT on the field. * Right hand side area of the last grid point is expanded on the last line to the infinity. * nextBreakPointIndex returns the number of unique points on x axis. * In the case of SBT and LBT with the strike price 100, x = 0,100,200 are the unique points * and the number is 3. */ function _assertBondGroup(bytes32[] memory bondIDs, uint256 maturity) internal view { require(bondIDs.length >= 2, "the bond group should consist of 2 or more bonds"); uint256 numOfBreakPoints = 0; for (uint256 i = 0; i < bondIDs.length; i++) { BondInfo storage bond = _bonds[bondIDs[i]]; require(bond.maturity == maturity, "the maturity of the bonds must be same"); LineSegment[] storage polyline = _registeredFnMap[bond.fnMapID]; numOfBreakPoints = numOfBreakPoints.add(polyline.length); } uint256 nextBreakPointIndex = 0; uint64[] memory rateBreakPoints = new uint64[](numOfBreakPoints); for (uint256 i = 0; i < bondIDs.length; i++) { BondInfo storage bond = _bonds[bondIDs[i]]; LineSegment[] storage segments = _registeredFnMap[bond.fnMapID]; for (uint256 j = 0; j < segments.length; j++) { uint64 breakPoint = segments[j].right.x; bool ok = false; for (uint256 k = 0; k < nextBreakPointIndex; k++) { if (rateBreakPoints[k] == breakPoint) { ok = true; break; } } if (ok) { continue; } rateBreakPoints[nextBreakPointIndex] = breakPoint; nextBreakPointIndex++; } } for (uint256 k = 0; k < rateBreakPoints.length; k++) { uint64 rate = rateBreakPoints[k]; uint256 totalBondPriceN = 0; uint256 totalBondPriceD = 1; for (uint256 i = 0; i < bondIDs.length; i++) { BondInfo storage bond = _bonds[bondIDs[i]]; LineSegment[] storage segments = _registeredFnMap[bond.fnMapID]; (uint256 segmentIndex, bool ok) = _correspondSegment(segments, rate); require(ok, "invalid domain expression"); (uint128 n, uint64 d) = _mapXtoY(segments[segmentIndex], rate); if (n != 0) { // a/b + c/d = (ad+bc)/bd // totalBondPrice += (n / d); // N = D*n + N*d, D = D*d totalBondPriceN = totalBondPriceD.mul(n).add(totalBondPriceN.mul(d)); totalBondPriceD = totalBondPriceD.mul(d); } } /** * @dev Ensure that totalBondPrice (= totalBondPriceN / totalBondPriceD) is the same * with rate. Because we need 1 Ether to mint a unit of each bond token respectively, * the sum of cashflow (USD) per a unit of bond token is the same as USD/ETH * rate at maturity. */ require( totalBondPriceN == totalBondPriceD.mul(rate), "the total price at any rateBreakPoints should be the same value as the rate" ); } } /** * @notice Collect bondIDs that regenerate the collateral, and group them as a bond group. * Any bond is described as a set of linear functions(i.e. polyline), * so we can easily check if the set of bondIDs are well-formed by looking at all the end * points of the lines. */ function registerNewBondGroup(bytes32[] calldata bondIDs, uint256 maturity) external virtual override returns (uint256 bondGroupID) { _assertBondGroup(bondIDs, maturity); (, , uint64 sbtStrikePrice, ) = getBond(bondIDs[0]); for (uint256 i = 1; i < bondIDs.length; i++) { (, , uint64 strikePrice, ) = getBond(bondIDs[i]); require(strikePrice == 0, "except the first bond must not be pure SBT"); } // Get and increment next bond group ID bondGroupID = _nextBondGroupID; _nextBondGroupID = _nextBondGroupID.add(1); _bondGroupList[bondGroupID] = BondGroup(bondIDs, maturity); emit LogNewBondGroup(bondGroupID, maturity, sbtStrikePrice, bondIDs); return bondGroupID; } /** * @dev A user needs to issue a bond via BondGroup in order to guarantee that the total value * of bonds in the bond group equals to the token allowance except for about 0.2% fee (accurately 2/1002). * The fee send to Lien token contract when liquidateBond() or reverseBondGroupToCollateral(). */ function _issueNewBonds(uint256 bondGroupID, uint256 collateralAmountWithFee) internal returns (uint256 bondAmount) { (bytes32[] memory bondIDs, uint256 maturity) = getBondGroup(bondGroupID); _assertNonEmptyBondGroup(bondIDs); _assertBeforeMaturity(maturity); uint256 fee = collateralAmountWithFee.mul(2).divRoundUp(1002); uint8 decimalsOfCollateral = _getCollateralDecimals(); bondAmount = _applyDecimalGap( collateralAmountWithFee.sub(fee), decimalsOfCollateral, DECIMALS_OF_BOND ); require(bondAmount != 0, "the minting amount must be non-zero"); for (uint256 i = 0; i < bondIDs.length; i++) { _mintBond(bondIDs[i], msg.sender, bondAmount); } emit LogIssueNewBonds(bondGroupID, msg.sender, bondAmount); } /** * @notice redeems collateral from the total set of bonds in the bondGroupID before maturity date. * @param bondGroupID is the bond group ID. * @param bondAmount is the redeemed bond amount (decimal: 8). */ function reverseBondGroupToCollateral(uint256 bondGroupID, uint256 bondAmount) external virtual override returns (bool) { require(bondAmount != 0, "the bond amount must be non-zero"); (bytes32[] memory bondIDs, uint256 maturity) = getBondGroup(bondGroupID); _assertNonEmptyBondGroup(bondIDs); _assertBeforeMaturity(maturity); for (uint256 i = 0; i < bondIDs.length; i++) { _burnBond(bondIDs[i], msg.sender, bondAmount); } uint8 decimalsOfCollateral = _getCollateralDecimals(); uint256 collateralAmount = _applyDecimalGap( bondAmount, DECIMALS_OF_BOND, decimalsOfCollateral ); uint256 fee = collateralAmount.mul(2).div(1000); // collateral:fee = 1000:2 _sendCollateralTo(payable(FEE_TAKER), fee); _sendCollateralTo(msg.sender, collateralAmount); emit LogReverseBondGroupToCollateral(bondGroupID, msg.sender, collateralAmount); return true; } /** * @notice Burns set of LBTs and mints equivalent set of LBTs that are not in the exception list. * @param inputBondGroupID is the BondGroupID of bonds which you want to burn. * @param outputBondGroupID is the BondGroupID of bonds which you want to mint. * @param exceptionBonds is the list of bondIDs that should be excluded in burn/mint process. */ function exchangeEquivalentBonds( uint256 inputBondGroupID, uint256 outputBondGroupID, uint256 amount, bytes32[] calldata exceptionBonds ) external virtual override returns (bool) { (bytes32[] memory inputIDs, uint256 inputMaturity) = getBondGroup(inputBondGroupID); _assertNonEmptyBondGroup(inputIDs); (bytes32[] memory outputIDs, uint256 outputMaturity) = getBondGroup(outputBondGroupID); _assertNonEmptyBondGroup(outputIDs); require(inputMaturity == outputMaturity, "cannot exchange bonds with different maturities"); _assertBeforeMaturity(inputMaturity); bool flag; uint256 exceptionCount; for (uint256 i = 0; i < inputIDs.length; i++) { // this flag control checks whether the bond is in the scope of burn/mint flag = true; for (uint256 j = 0; j < exceptionBonds.length; j++) { if (exceptionBonds[j] == inputIDs[i]) { flag = false; // this count checks if all the bondIDs in exceptionBonds are included both in inputBondGroupID and outputBondGroupID exceptionCount = exceptionCount.add(1); } } if (flag) { _burnBond(inputIDs[i], msg.sender, amount); } } require( exceptionBonds.length == exceptionCount, "All the exceptionBonds need to be included in input" ); for (uint256 i = 0; i < outputIDs.length; i++) { flag = true; for (uint256 j = 0; j < exceptionBonds.length; j++) { if (exceptionBonds[j] == outputIDs[i]) { flag = false; exceptionCount = exceptionCount.sub(1); } } if (flag) { _mintBond(outputIDs[i], msg.sender, amount); } } require( exceptionCount == 0, "All the exceptionBonds need to be included both in input and output" ); emit LogExchangeEquivalentBonds(msg.sender, inputBondGroupID, outputBondGroupID, amount); return true; } /** * @notice This function distributes the collateral to the bond token holders * after maturity date based on the oracle price. * @param bondGroupID is the target bond group ID. * @param oracleHintID is manually set to be smaller number than the oracle latestId * when the caller wants to save gas. */ function liquidateBond(uint256 bondGroupID, uint256 oracleHintID) external virtual override returns (uint256 totalPayment) { (bytes32[] memory bondIDs, uint256 maturity) = getBondGroup(bondGroupID); _assertNonEmptyBondGroup(bondIDs); require(_getBlockTimestampSec() >= maturity, "the bond has not expired yet"); uint256 latestID = _oracleContract.latestId(); require(latestID != 0, "system error: the ID of oracle data should not be zero"); uint256 price = _getPriceOn( maturity, (oracleHintID != 0 && oracleHintID <= latestID) ? oracleHintID : latestID ); require(price != 0, "price should be non-zero value"); require(price < 2**64, "price should be less than 2^64"); for (uint256 i = 0; i < bondIDs.length; i++) { bytes32 bondID = bondIDs[i]; uint256 payment = _sendCollateralToBondTokenContract(bondID, uint64(price)); totalPayment = totalPayment.add(payment); } if (totalPayment != 0) { uint256 fee = totalPayment.mul(2).div(1000); // collateral:fee = 1000:2 _sendCollateralTo(payable(FEE_TAKER), fee); } } function collateralAddress() external view override returns (address) { return _collateralAddress(); } function oracleAddress() external view override returns (PriceOracleInterface) { return _oracleContract; } function feeTaker() external view override returns (address) { return FEE_TAKER; } function decimalsOfBond() external view override returns (uint8) { return DECIMALS_OF_BOND; } function decimalsOfOraclePrice() external view override returns (uint8) { return DECIMALS_OF_ORACLE_PRICE; } function maturityScale() external view override returns (uint256) { return MATURITY_SCALE; } function nextBondGroupID() external view override returns (uint256) { return _nextBondGroupID; } /** * @notice Returns multiple information for the bondID. * @dev The decimals of strike price is the same as that of oracle price. */ function getBond(bytes32 bondID) public view override returns ( address bondTokenAddress, uint256 maturity, uint64 solidStrikePrice, bytes32 fnMapID ) { BondInfo memory bondInfo = _bonds[bondID]; bondTokenAddress = address(bondInfo.contractInstance); maturity = bondInfo.maturity; solidStrikePrice = bondInfo.strikePrice; fnMapID = bondInfo.fnMapID; } /** * @dev Returns polyline for the fnMapID. */ function getFnMap(bytes32 fnMapID) public view override returns (bytes memory fnMap) { LineSegment[] storage segments = _registeredFnMap[fnMapID]; uint256[] memory polyline = new uint256[](segments.length); for (uint256 i = 0; i < segments.length; i++) { polyline[i] = zipLineSegment(segments[i]); } return abi.encode(polyline); } /** * @dev Returns all the bondIDs and their maturity for the bondGroupID. */ function getBondGroup(uint256 bondGroupID) public view override returns (bytes32[] memory bondIDs, uint256 maturity) { require(bondGroupID < _nextBondGroupID, "the bond group does not exist"); BondGroup memory bondGroup = _bondGroupList[bondGroupID]; bondIDs = bondGroup.bondIDs; maturity = bondGroup.maturity; } /** * @dev Returns keccak256 for the fnMap. */ function generateFnMapID(bytes memory fnMap) public pure override returns (bytes32 fnMapID) { return keccak256(fnMap); } /** * @dev Returns a bond ID determined by this contract address, maturity and fnMap. */ function generateBondID(uint256 maturity, bytes memory fnMap) public view override returns (bytes32 bondID) { return keccak256(abi.encodePacked(address(this), maturity, fnMap)); } function _mintBond( bytes32 bondID, address account, uint256 amount ) internal { BondTokenInterface bondTokenContract = _bonds[bondID].contractInstance; _assertRegisteredBond(bondTokenContract); require(bondTokenContract.mint(account, amount), "failed to mint bond token"); } function _burnBond( bytes32 bondID, address account, uint256 amount ) internal { BondTokenInterface bondTokenContract = _bonds[bondID].contractInstance; _assertRegisteredBond(bondTokenContract); require(bondTokenContract.simpleBurn(account, amount), "failed to burn bond token"); } function _sendCollateralToBondTokenContract(bytes32 bondID, uint64 price) internal returns (uint256 collateralAmount) { BondTokenInterface bondTokenContract = _bonds[bondID].contractInstance; _assertRegisteredBond(bondTokenContract); LineSegment[] storage segments = _registeredFnMap[_bonds[bondID].fnMapID]; (uint256 segmentIndex, bool ok) = _correspondSegment(segments, price); assert(ok); // not found a segment whose price range include current price (uint128 n, uint64 _d) = _mapXtoY(segments[segmentIndex], price); // x = price, y = n / _d // uint64(-1) * uint64(-1) < uint128(-1) uint128 d = uint128(_d) * uint128(price); uint256 totalSupply = bondTokenContract.totalSupply(); bool expiredFlag = bondTokenContract.expire(n, d); // rateE0 = n / d = f(price) / price if (expiredFlag) { uint8 decimalsOfCollateral = _getCollateralDecimals(); collateralAmount = _applyDecimalGap(totalSupply, DECIMALS_OF_BOND, decimalsOfCollateral) .mul(n) .div(d); _sendCollateralTo(address(bondTokenContract), collateralAmount); emit LogLiquidateBond(bondID, n, d); } } /** * @dev Get the price of the oracle data with a minimum timestamp that does more than input value * when you know the ID you are looking for. * @param timestamp is the timestamp that you want to get price. * @param hintID is the ID of the oracle data you are looking for. * @return priceE8 (10^-8 USD) */ function _getPriceOn(uint256 timestamp, uint256 hintID) internal returns (uint256 priceE8) { require( _oracleContract.getTimestamp(hintID) > timestamp, "there is no price data after maturity" ); uint256 id = hintID - 1; while (id != 0) { if (_oracleContract.getTimestamp(id) <= timestamp) { break; } id--; } return _oracleContract.getPrice(id + 1); } /** * @dev removes a decimal gap from rate. */ function _applyDecimalGap( uint256 baseAmount, uint8 decimalsOfBase, uint8 decimalsOfQuote ) internal pure returns (uint256 quoteAmount) { uint256 n; uint256 d; if (decimalsOfBase > decimalsOfQuote) { d = decimalsOfBase - decimalsOfQuote; } else if (decimalsOfBase < decimalsOfQuote) { n = decimalsOfQuote - decimalsOfBase; } // The consequent multiplication would overflow under extreme and non-blocking circumstances. require(n < 19 && d < 19, "decimal gap needs to be lower than 19"); quoteAmount = baseAmount.mul(10**n).div(10**d); } function _assertRegisteredBond(BondTokenInterface bondTokenContract) internal pure { require(address(bondTokenContract) != address(0), "the bond is not registered"); } function _assertNonEmptyBondGroup(bytes32[] memory bondIDs) internal pure { require(bondIDs.length != 0, "the list of bond ID must be non-empty"); } function _assertBeforeMaturity(uint256 maturity) internal view { require(_getBlockTimestampSec() < maturity, "the maturity has already expired"); } function _isBondWorthless(LineSegment[] memory polyline) internal pure returns (bool) { for (uint256 i = 0; i < polyline.length; i++) { LineSegment memory segment = polyline[i]; if (segment.right.y != 0) { return false; } } return true; } /** * @dev Return the strike price only when the form of polyline matches to the definition of SBT. * Check if the form is SBT even when the polyline is in a verbose style. */ function _getSbtStrikePrice(LineSegment[] memory polyline) internal pure returns (uint64) { if (polyline.length != 2) { return 0; } uint64 strikePrice = polyline[0].right.x; if (strikePrice == 0) { return 0; } for (uint256 i = 0; i < polyline.length; i++) { LineSegment memory segment = polyline[i]; if (segment.right.y != strikePrice) { return 0; } } return uint64(strikePrice); } /** * @dev Only when the form of polyline matches to the definition of LBT, this function returns * the minimum collateral price (USD) that LBT is not worthless. * Check if the form is LBT even when the polyline is in a verbose style. */ function _getLbtStrikePrice(LineSegment[] memory polyline) internal pure returns (uint64) { if (polyline.length != 2) { return 0; } uint64 strikePrice = polyline[0].right.x; if (strikePrice == 0) { return 0; } for (uint256 i = 0; i < polyline.length; i++) { LineSegment memory segment = polyline[i]; if (segment.right.y.add(strikePrice) != segment.right.x) { return 0; } } return uint64(strikePrice); } /** * @dev In order to calculate y axis value for the corresponding x axis value, we need to find * the place of domain of x value on the polyline. * As the polyline is already checked to be correctly formed, we can simply look from the right * hand side of the polyline. */ function _correspondSegment(LineSegment[] memory segments, uint64 x) internal pure returns (uint256 i, bool ok) { i = segments.length; while (i > 0) { i--; if (segments[i].left.x <= x) { ok = true; break; } } } // function issueNewBonds(uint256 bondGroupID, uint256 amount) external returns (uint256 bondAmount); function _createNewBondToken(uint256 maturity, bytes memory fnMap) internal virtual returns (BondTokenInterface); function _collateralAddress() internal view virtual returns (address); function _getCollateralDecimals() internal view virtual returns (uint8); function _sendCollateralTo(address receiver, uint256 amount) internal virtual; } // File: contracts/BondToken_and_GDOTC/bondTokenName/BondTokenNameInterface.sol /** * @title bond token name contract interface */ interface BondTokenNameInterface { function genBondTokenName( string calldata shortNamePrefix, string calldata longNamePrefix, uint256 maturity, uint256 solidStrikePriceE4 ) external pure returns (string memory shortName, string memory longName); function getBondTokenName( uint256 maturity, uint256 solidStrikePriceE4, uint256 rateLBTWorthlessE4 ) external pure returns (string memory shortName, string memory longName); } // File: contracts/BondToken_and_GDOTC/bondMaker/BondMakerCollateralizedEth.sol contract BondMakerCollateralizedEth is BondMaker, TransferETH { address private constant ETH = address(0); BondTokenNameInterface internal immutable BOND_TOKEN_NAMER; BondTokenFactory internal immutable BOND_TOKEN_FACTORY; constructor( PriceOracleInterface oracleAddress, address feeTaker, BondTokenNameInterface bondTokenNamerAddress, BondTokenFactory bondTokenFactoryAddress, uint256 maturityScale ) BondMaker(oracleAddress, feeTaker, maturityScale, 8, 8) { require( address(bondTokenNamerAddress) != address(0), "bondTokenNamerAddress should be non-zero address" ); BOND_TOKEN_NAMER = bondTokenNamerAddress; require( address(bondTokenFactoryAddress) != address(0), "bondTokenFactoryAddress should be non-zero address" ); BOND_TOKEN_FACTORY = bondTokenFactoryAddress; } function issueNewBonds(uint256 bondGroupID) public payable returns (uint256 bondAmount) { return _issueNewBonds(bondGroupID, msg.value); } function _createNewBondToken(uint256 maturity, bytes memory fnMap) internal override returns (BondTokenInterface) { (string memory symbol, string memory name) = _getBondTokenName(maturity, fnMap); address bondAddress = BOND_TOKEN_FACTORY.createBondToken( ETH, name, symbol, DECIMALS_OF_BOND ); return BondTokenInterface(bondAddress); } function _getBondTokenName(uint256 maturity, bytes memory fnMap) internal view virtual returns (string memory symbol, string memory name) { bytes32 fnMapID = generateFnMapID(fnMap); LineSegment[] memory segments = _registeredFnMap[fnMapID]; uint64 sbtStrikePrice = _getSbtStrikePrice(segments); uint64 lbtStrikePrice = _getLbtStrikePrice(segments); uint64 sbtStrikePriceE0 = sbtStrikePrice / (uint64(10)**DECIMALS_OF_ORACLE_PRICE); uint64 lbtStrikePriceE0 = lbtStrikePrice / (uint64(10)**DECIMALS_OF_ORACLE_PRICE); if (sbtStrikePrice != 0) { return BOND_TOKEN_NAMER.genBondTokenName("SBT", "SBT", maturity, sbtStrikePriceE0); } else if (lbtStrikePrice != 0) { return BOND_TOKEN_NAMER.genBondTokenName("LBT", "LBT", maturity, lbtStrikePriceE0); } else { return BOND_TOKEN_NAMER.genBondTokenName("IMT", "Immortal Option", maturity, 0); } } function _collateralAddress() internal pure override returns (address) { return address(0); } function _getCollateralDecimals() internal pure override returns (uint8) { return 18; } function _sendCollateralTo(address receiver, uint256 amount) internal override { _transferETH(payable(receiver), amount); } }
* @dev The contents in this internal storage variable can be seen by getBondGroup function./
struct BondGroup { bytes32[] bondIDs; uint256 maturity; } mapping(uint256 => BondGroup) internal _bondGroupList; constructor( PriceOracleInterface oracleAddress, address feeTaker, uint256 maturityScale, uint8 decimalsOfBond, uint8 decimalsOfOraclePrice
6,632,250
[ 1, 1986, 2939, 316, 333, 2713, 2502, 2190, 848, 506, 5881, 635, 29585, 1114, 445, 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 ]
[ 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, 1958, 605, 1434, 1114, 288, 203, 3639, 1731, 1578, 8526, 8427, 5103, 31, 203, 3639, 2254, 5034, 29663, 31, 203, 565, 289, 203, 565, 2874, 12, 11890, 5034, 516, 605, 1434, 1114, 13, 2713, 389, 26425, 1114, 682, 31, 203, 203, 565, 3885, 12, 203, 3639, 20137, 23601, 1358, 20865, 1887, 16, 203, 3639, 1758, 14036, 56, 6388, 16, 203, 3639, 2254, 5034, 29663, 5587, 16, 203, 3639, 2254, 28, 15105, 951, 9807, 16, 203, 3639, 2254, 28, 15105, 951, 23601, 5147, 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 ]
pragma solidity >=0.4.21 <0.7.0; import "./SafeMath.sol"; contract Account { using SafeMath for uint; mapping (address => uint) public stoneOwnerCount; mapping (address => uint) public ironOwnerCount; mapping (address => uint) public foodOwnerCount; mapping (address => uint) public coinOwnerCount; mapping (address => uint) public woodOwnerCount; mapping (address => uint) public power; uint public kingdomAmount; mapping (uint => address) public castleToOwner; mapping (address => uint) public ownerCastleCount; uint IdDigits = 16; uint IdModulus = 10 ** IdDigits; function checkUserAddress() public view returns(bool) { if(ownerCastleCount[msg.sender] > 0) return true; return false; } function getMyIdx() public view returns(uint) { for (uint i=0; i<kingdomAmount; ++i) { if(castleToOwner[i] == msg.sender) { return i; } } return kingdomAmount; } function getUserPower(uint idx) public view returns(uint) { if(idx < kingdomAmount) { return power[castleToOwner[idx]]; } return 0; } function getKingdomAmount() public view returns(uint) { return kingdomAmount; } // for web to create castle function _initializeKingdom(address _owner) internal { require(ownerCastleCount[_owner] == 0); castleToOwner[kingdomAmount] = _owner; kingdomAmount++; ownerCastleCount[_owner]++; foodOwnerCount[_owner] = 10000; woodOwnerCount[_owner] = 10000; stoneOwnerCount[_owner] = 10000; ironOwnerCount[_owner] = 10000; coinOwnerCount[_owner] = 10000; power[_owner] = 0; } function _cost(address _owner, uint food, uint wood, uint iron, uint stone, uint coin) internal returns (bool){ if(foodOwnerCount[_owner]>=food && woodOwnerCount[_owner]>=wood && ironOwnerCount[_owner]>=iron && stoneOwnerCount[_owner]>=stone && coinOwnerCount[_owner]>=coin){ foodOwnerCount[_owner] = foodOwnerCount[_owner].sub(food); woodOwnerCount[_owner] = woodOwnerCount[_owner].sub(wood); ironOwnerCount[_owner] = ironOwnerCount[_owner].sub(iron); stoneOwnerCount[_owner] = stoneOwnerCount[_owner].sub(stone); coinOwnerCount[_owner] = coinOwnerCount[_owner].sub(coin); return true; } return false; } function getFoodAmount() public view returns(uint) { return foodOwnerCount[msg.sender]; } function getIronAmount() public view returns(uint) { return ironOwnerCount[msg.sender]; } function getStoneAmount() public view returns(uint) { return stoneOwnerCount[msg.sender]; } function getCoinAmount() public view returns(uint) { return coinOwnerCount[msg.sender]; } function getWoodAmount() public view returns(uint) { return woodOwnerCount[msg.sender]; } }
for web to create castle
function _initializeKingdom(address _owner) internal { require(ownerCastleCount[_owner] == 0); castleToOwner[kingdomAmount] = _owner; kingdomAmount++; ownerCastleCount[_owner]++; foodOwnerCount[_owner] = 10000; woodOwnerCount[_owner] = 10000; stoneOwnerCount[_owner] = 10000; ironOwnerCount[_owner] = 10000; coinOwnerCount[_owner] = 10000; power[_owner] = 0; }
13,028,759
[ 1, 1884, 3311, 358, 752, 4812, 298, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 11160, 47, 310, 9859, 12, 2867, 389, 8443, 13, 2713, 288, 203, 3639, 2583, 12, 8443, 9735, 298, 1380, 63, 67, 8443, 65, 422, 374, 1769, 203, 3639, 4812, 298, 774, 5541, 63, 79, 310, 9859, 6275, 65, 273, 389, 8443, 31, 203, 3639, 417, 310, 9859, 6275, 9904, 31, 203, 3639, 3410, 9735, 298, 1380, 63, 67, 8443, 3737, 15, 31, 203, 3639, 284, 4773, 5541, 1380, 63, 67, 8443, 65, 273, 12619, 31, 203, 3639, 341, 4773, 5541, 1380, 63, 67, 8443, 65, 273, 12619, 31, 203, 3639, 384, 476, 5541, 1380, 63, 67, 8443, 65, 273, 12619, 31, 203, 3639, 277, 1949, 5541, 1380, 63, 67, 8443, 65, 273, 12619, 31, 203, 3639, 13170, 5541, 1380, 63, 67, 8443, 65, 273, 12619, 31, 203, 3639, 7212, 63, 67, 8443, 65, 273, 374, 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 ]
// SPDX-License-Identifier: MIT // Based on the ReentrancyGuard library from OpenZeppelin Contracts, altered to reduce bytecode size. // Modifier code is inlined by the compiler, which causes its code to appear multiple times in the codebase. By using // private functions, we achieve the same end result with slightly higher runtime gas costs, but reduced bytecode size. pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract 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() { _enterNonReentrant(); _; _exitNonReentrant(); } function _enterNonReentrant() private { // On the first call to nonReentrant, _status will be _NOT_ENTERED _require(_status != _ENTERED, Errors.REENTRANCY); // Any calls to nonReentrant after this point will fail _status = _ENTERED; } function _exitNonReentrant() private { // 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: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/IAuthentication.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/ISignaturesValidator.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/ITemporarilyPausable.sol"; import "@balancer-labs/v2-solidity-utils/contracts/misc/IWETH.sol"; import "./IAsset.sol"; import "./IAuthorizer.sol"; import "./IFlashLoanRecipient.sol"; import "./IProtocolFeesCollector.sol"; pragma solidity ^0.7.0; /** * @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that * don't override one of these declarations. */ interface IVault is ISignaturesValidator, ITemporarilyPausable, IAuthentication { // Generalities about the Vault: // // - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are // transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling // `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by // calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning // a boolean value: in these scenarios, a non-reverting call is assumed to be successful. // // - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g. // while execution control is transferred to a token contract during a swap) will result in a revert. View // functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results. // Contracts calling view functions in the Vault must make sure the Vault has not already been entered. // // - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools. // Authorizer // // Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists // outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller // can perform a given action. /** * @dev Returns the Vault's Authorizer. */ function getAuthorizer() external view returns (IAuthorizer); /** * @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this. * * Emits an `AuthorizerChanged` event. */ function setAuthorizer(IAuthorizer newAuthorizer) external; /** * @dev Emitted when a new authorizer is set by `setAuthorizer`. */ event AuthorizerChanged(IAuthorizer indexed newAuthorizer); // Relayers // // Additionally, it is possible for an account to perform certain actions on behalf of another one, using their // Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions, // and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield // this power, two things must occur: // - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This // means that Balancer governance must approve each individual contract to act as a relayer for the intended // functions. // - Each user must approve the relayer to act on their behalf. // This double protection means users cannot be tricked into approving malicious relayers (because they will not // have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised // Authorizer or governance drain user funds, since they would also need to be approved by each individual user. /** * @dev Returns true if `user` has approved `relayer` to act as a relayer for them. */ function hasApprovedRelayer(address user, address relayer) external view returns (bool); /** * @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise. * * Emits a `RelayerApprovalChanged` event. */ function setRelayerApproval( address sender, address relayer, bool approved ) external; /** * @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`. */ event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved); // Internal Balance // // Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later // transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination // when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced // gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users. // // Internal Balance management features batching, which means a single contract call can be used to perform multiple // operations of different kinds, with different senders and recipients, at once. /** * @dev Returns `user`'s Internal Balance for a set of tokens. */ function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory); /** * @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer) * and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as * it lets integrators reuse a user's Vault allowance. * * For each operation, if the caller is not `sender`, it must be an authorized relayer for them. */ function manageUserBalance(UserBalanceOp[] memory ops) external payable; /** * @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received without manual WETH wrapping or unwrapping. */ struct UserBalanceOp { UserBalanceOpKind kind; IAsset asset; uint256 amount; address sender; address payable recipient; } // There are four possible operations in `manageUserBalance`: // // - DEPOSIT_INTERNAL // Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding // `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`. // // ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped // and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is // relevant for relayers). // // Emits an `InternalBalanceChanged` event. // // // - WITHDRAW_INTERNAL // Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`. // // ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send // it to the recipient as ETH. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_INTERNAL // Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`. // // Reverts if the ETH sentinel value is passed. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_EXTERNAL // Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by // relayers, as it lets them reuse a user's Vault allowance. // // Reverts if the ETH sentinel value is passed. // // Emits an `ExternalBalanceTransfer` event. enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL } /** * @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through * interacting with Pools using Internal Balance. * * Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH * address. */ event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta); /** * @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account. */ event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount); // Pools // // There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced // functionality: // // - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the // balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads), // which increase with the number of registered tokens. // // - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the // balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted // constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are // independent of the number of registered tokens. // // - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like // minimal swap info Pools, these are called via IMinimalSwapInfoPool. enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN } /** * @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which * is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be * changed. * * The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`, * depending on the chosen specialization setting. This contract is known as the Pool's contract. * * Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words, * multiple Pools may share the same contract. * * Emits a `PoolRegistered` event. */ function registerPool(PoolSpecialization specialization) external returns (bytes32); /** * @dev Emitted when a Pool is registered by calling `registerPool`. */ event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization); /** * @dev Returns a Pool's contract address and specialization setting. */ function getPool(bytes32 poolId) external view returns (address, PoolSpecialization); /** * @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens, * exit by receiving registered tokens, and can only swap registered tokens. * * Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length * of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in * ascending order. * * The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset * Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`, * depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore * expected to be highly secured smart contracts with sound design principles, and the decision to register an * Asset Manager should not be made lightly. * * Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset * Manager is set, it cannot be changed except by deregistering the associated token and registering again with a * different Asset Manager. * * Emits a `TokensRegistered` event. */ function registerTokens( bytes32 poolId, IERC20[] memory tokens, address[] memory assetManagers ) external; /** * @dev Emitted when a Pool registers tokens by calling `registerTokens`. */ event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers); /** * @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total * balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens * must be deregistered in the same `deregisterTokens` call. * * A deregistered token can be re-registered later on, possibly with a different Asset Manager. * * Emits a `TokensDeregistered` event. */ function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external; /** * @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`. */ event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens); /** * @dev Returns detailed information for a Pool's registered token. * * `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens * withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token` * equals the sum of `cash` and `managed`. * * Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`, * `managed` or `total` balance to be greater than 2^112 - 1. * * `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a * join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for * example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a * change for this purpose, and will update `lastChangeBlock`. * * `assetManager` is the Pool's token Asset Manager. */ function getPoolTokenInfo(bytes32 poolId, IERC20 token) external view returns ( uint256 cash, uint256 managed, uint256 lastChangeBlock, address assetManager ); /** * @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of * the tokens' `balances` changed. * * The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all * Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order. * * If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same * order as passed to `registerTokens`. * * Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are * the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo` * instead. */ function getPoolTokens(bytes32 poolId) external view returns ( IERC20[] memory tokens, uint256[] memory balances, uint256 lastChangeBlock ); /** * @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will * trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized * Pool shares. * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount * to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces * these maximums. * * If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable * this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the * WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent * back to the caller (not the sender, which is important for relayers). * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be * sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final * `assets` array might not be sorted. Pools with no registered tokens cannot be joined. * * If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only * be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be * withdrawn from Internal Balance: attempting to do so will trigger a revert. * * This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed * directly to the Pool's contract, as is `recipient`. * * Emits a `PoolBalanceChanged` event. */ function joinPool( bytes32 poolId, address sender, address recipient, JoinPoolRequest memory request ) external payable; struct JoinPoolRequest { IAsset[] assets; uint256[] maxAmountsIn; bytes userData; bool fromInternalBalance; } /** * @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will * trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized * Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see * `getPoolTokenInfo`). * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum * token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault: * it just enforces these minimums. * * If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To * enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead * of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit. * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must * be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the * final `assets` array might not be sorted. Pools with no registered tokens cannot be exited. * * If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise, * an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to * do so will trigger a revert. * * `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the * `tokens` array. This array must match the Pool's registered tokens. * * This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and * passed directly to the Pool's contract. * * Emits a `PoolBalanceChanged` event. */ function exitPool( bytes32 poolId, address sender, address payable recipient, ExitPoolRequest memory request ) external; struct ExitPoolRequest { IAsset[] assets; uint256[] minAmountsOut; bytes userData; bool toInternalBalance; } /** * @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively. */ event PoolBalanceChanged( bytes32 indexed poolId, address indexed liquidityProvider, IERC20[] tokens, int256[] deltas, uint256[] protocolFeeAmounts ); enum PoolBalanceChangeKind { JOIN, EXIT } // Swaps // // Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this, // they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be // aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote. // // The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence. // In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'), // and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out'). // More complex swaps, such as one token in to multiple tokens out can be achieved by batching together // individual swaps. // // There are two swap kinds: // - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the // `onSwap` hook) the amount of tokens out (to send to the recipient). // - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines // (via the `onSwap` hook) the amount of tokens in (to receive from the sender). // // Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with // the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated // tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended // swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at // the final intended token. // // In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal // Balance) after all individual swaps have been completed, and the net token balance change computed. This makes // certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost // much less gas than they would otherwise. // // It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple // Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only // updating the Pool's internal accounting). // // To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token // involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the // minimum amount of tokens to receive (by passing a negative value) is specified. // // Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after // this point in time (e.g. if the transaction failed to be included in a block promptly). // // If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do // the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be // passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the // same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers). // // Finally, Internal Balance can be used when either sending or receiving tokens. enum SwapKind { GIVEN_IN, GIVEN_OUT } /** * @dev Performs a swap with a single Pool. * * If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens * taken from the Pool, which must be greater than or equal to `limit`. * * If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens * sent to the Pool, which must be less than or equal to `limit`. * * Internal Balance usage and the recipient are determined by the `funds` struct. * * Emits a `Swap` event. */ function swap( SingleSwap memory singleSwap, FundManagement memory funds, uint256 limit, uint256 deadline ) external payable returns (uint256); /** * @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on * the `kind` value. * * `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address). * Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct SingleSwap { bytes32 poolId; SwapKind kind; IAsset assetIn; IAsset assetOut; uint256 amount; bytes userData; } /** * @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either * the amount of tokens sent to or received from the Pool, depending on the `kind` value. * * Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the * Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at * the same index in the `assets` array. * * Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a * Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or * `amountOut` depending on the swap kind. * * Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out * of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal * the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`. * * The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses, * or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and * out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to * or unwrapped from WETH by the Vault. * * Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies * the minimum or maximum amount of each token the vault is allowed to transfer. * * `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the * equivalent `swap` call. * * Emits `Swap` events. */ function batchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds, int256[] memory limits, uint256 deadline ) external payable returns (int256[] memory); /** * @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the * `assets` array passed to that function, and ETH assets are converted to WETH. * * If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out * from the previous swap, depending on the swap kind. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct BatchSwapStep { bytes32 poolId; uint256 assetInIndex; uint256 assetOutIndex; uint256 amount; bytes userData; } /** * @dev Emitted for each individual swap performed by `swap` or `batchSwap`. */ event Swap( bytes32 indexed poolId, IERC20 indexed tokenIn, IERC20 indexed tokenOut, uint256 amountIn, uint256 amountOut ); /** * @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the * `recipient` account. * * If the caller is not `sender`, it must be an authorized relayer for them. * * If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20 * transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender` * must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of * `joinPool`. * * If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of * transferred. This matches the behavior of `exitPool`. * * Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a * revert. */ struct FundManagement { address sender; bool fromInternalBalance; address payable recipient; bool toInternalBalance; } /** * @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be * simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result. * * Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH) * the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it * receives are the same that an equivalent `batchSwap` call would receive. * * Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct. * This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens, * approve them for the Vault, or even know a user's address. * * Note that this function is not 'view' (due to implementation details): the client code must explicitly execute * eth_call instead of eth_sendTransaction. */ function queryBatchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds ) external returns (int256[] memory assetDeltas); // Flash Loans /** * @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it, * and then reverting unless the tokens plus a proportional protocol fee have been returned. * * The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount * for each token contract. `tokens` must be sorted in ascending order. * * The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the * `receiveFlashLoan` call. * * Emits `FlashLoan` events. */ function flashLoan( IFlashLoanRecipient recipient, IERC20[] memory tokens, uint256[] memory amounts, bytes memory userData ) external; /** * @dev Emitted for each individual flash loan performed by `flashLoan`. */ event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount); // Asset Management // // Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's // tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see // `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly // controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the // prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore // not constrained to the tokens they are managing, but extends to the entire Pool's holdings. // // However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit, // for example by lending unused tokens out for interest, or using them to participate in voting protocols. // // This concept is unrelated to the IAsset interface. /** * @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates. * * Pool Balance management features batching, which means a single contract call can be used to perform multiple * operations of different kinds, with different Pools and tokens, at once. * * For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`. */ function managePoolBalance(PoolBalanceOp[] memory ops) external; struct PoolBalanceOp { PoolBalanceOpKind kind; bytes32 poolId; IERC20 token; uint256 amount; } /** * Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged. * * Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged. * * Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total. * The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss). */ enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE } /** * @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`. */ event PoolBalanceManaged( bytes32 indexed poolId, address indexed assetManager, IERC20 indexed token, int256 cashDelta, int256 managedDelta ); // Protocol Fees // // Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by // permissioned accounts. // // There are two kinds of protocol fees: // // - flash loan fees: charged on all flash loans, as a percentage of the amounts lent. // // - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including // swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather, // Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the // Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as // exiting a Pool in debt without first paying their share. /** * @dev Returns the current protocol fee module. */ function getProtocolFeesCollector() external view returns (IProtocolFeesCollector); /** * @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an * error in some part of the system. * * The Vault can only be paused during an initial time period, after which pausing is forever disabled. * * While the contract is paused, the following features are disabled: * - depositing and transferring internal balance * - transferring external balance (using the Vault's allowance) * - swaps * - joining Pools * - Asset Manager interactions * * Internal Balance can still be withdrawn, and Pools exited. */ function setPaused(bool paused) external; /** * @dev Returns the Vault's WETH instance. */ function WETH() external view returns (IWETH); // solhint-disable-previous-line func-name-mixedcase } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/IAuthentication.sol"; interface IAuthorizerAdaptor is IAuthentication { /** * @notice Returns the Balancer Vault */ function getVault() external view returns (IVault); /** * @notice Returns the Authorizer */ function getAuthorizer() external view returns (IAuthorizer); /** * @notice Performs an arbitrary function call on a target contract, provided the caller is authorized to do so. * @param target - Address of the contract to be called * @param data - Calldata to be sent to the target contract * @return The bytes encoded return value from the performed function call */ function performAction(address target, bytes calldata data) external payable returns (bytes memory); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/helpers/IAuthentication.sol"; import "./IAuthorizerAdaptor.sol"; import "./IGaugeController.sol"; import "./ILiquidityGauge.sol"; import "./ILiquidityGaugeFactory.sol"; import "./IStakingLiquidityGauge.sol"; interface IGaugeAdder is IAuthentication { enum GaugeType { LiquidityMiningCommittee, veBAL, Ethereum, Polygon, Arbitrum } event GaugeFactoryAdded(GaugeType indexed gaugeType, ILiquidityGaugeFactory gaugeFactory); /** * @notice Returns the gauge corresponding to a Balancer pool `pool` on Ethereum mainnet. * Only returns gauges which have been added to the Gauge Controller. * @dev Gauge Factories also implement a `getPoolGauge` function which maps pools to gauges which it has deployed. * This function provides global information by using which gauge has been added to the Gauge Controller * to represent the canonical gauge for a given pool address. */ function getPoolGauge(IERC20 pool) external view returns (ILiquidityGauge); /** * @notice Returns the `index`'th factory for gauge type `gaugeType` */ function getFactoryForGaugeType(GaugeType gaugeType, uint256 index) external view returns (address); /** * @notice Returns the number of factories for gauge type `gaugeType` */ function getFactoryForGaugeTypeCount(GaugeType gaugeType) external view returns (uint256); /** * @notice Returns whether `gauge` has been deployed by one of the listed factories for the gauge type `gaugeType` */ function isGaugeFromValidFactory(address gauge, GaugeType gaugeType) external view returns (bool); /** * @notice Adds a new gauge to the GaugeController for the "Ethereum" type. */ function addEthereumGauge(IStakingLiquidityGauge gauge) external; /** * @notice Adds a new gauge to the GaugeController for the "Polygon" type. * This function must be called with the address of the *root* gauge which is deployed on Ethereum mainnet. * It should not be called with the address of the gauge which is deployed on Polygon */ function addPolygonGauge(address rootGauge) external; /** * @notice Adds a new gauge to the GaugeController for the "Arbitrum" type. * This function must be called with the address of the *root* gauge which is deployed on Ethereum mainnet. * It should not be called with the address of the gauge which is deployed on Arbitrum */ function addArbitrumGauge(address rootGauge) external; /** * @notice Adds `factory` as an allowlisted factory contract for gauges with type `gaugeType`. */ function addGaugeFactory(ILiquidityGaugeFactory factory, GaugeType gaugeType) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "./IAuthorizerAdaptor.sol"; import "./IVotingEscrow.sol"; // For compatibility, we're keeping the same function names as in the original Curve code, including the mixed-case // naming convention. // solhint-disable func-name-mixedcase interface IGaugeController { function checkpoint_gauge(address gauge) external; function gauge_relative_weight(address gauge, uint256 time) external returns (uint256); function voting_escrow() external view returns (IVotingEscrow); function token() external view returns (IERC20); function add_type(string calldata name, uint256 weight) external; function change_type_weight(int128 typeId, uint256 weight) external; // Gauges are to be added with zero initial weight so the full signature is not required function add_gauge(address gauge, int128 gaugeType) external; function n_gauge_types() external view returns (int128); function gauge_types(address gauge) external view returns (int128); function admin() external view returns (IAuthorizerAdaptor); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/helpers/IAuthentication.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; import "./IBalancerToken.sol"; interface IBalancerTokenAdmin is IAuthentication { // solhint-disable func-name-mixedcase function INITIAL_RATE() external view returns (uint256); function RATE_REDUCTION_TIME() external view returns (uint256); function RATE_REDUCTION_COEFFICIENT() external view returns (uint256); function RATE_DENOMINATOR() external view returns (uint256); // solhint-enable func-name-mixedcase /** * @notice Returns the address of the Balancer Governance Token */ function getBalancerToken() external view returns (IBalancerToken); /** * @notice Returns the Balancer Vault. */ function getVault() external view returns (IVault); function activate() external; function rate() external view returns (uint256); function startEpochTimeWrite() external returns (uint256); function mint(address to, uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./ILiquidityGauge.sol"; interface ILiquidityGaugeFactory { /** * @notice Returns true if `gauge` was created by this factory. */ function isGaugeFromFactory(address gauge) external view returns (bool); function create(address pool) external returns (address); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; // solhint-disable /** * @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are * supported. */ function _require(bool condition, uint256 errorCode) pure { if (!condition) _revert(errorCode); } /** * @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported. */ function _revert(uint256 errorCode) pure { // We're going to dynamically create a revert string based on the error code, with the following format: // 'BAL#{errorCode}' // where the code is left-padded with zeroes to three digits (so they range from 000 to 999). // // We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a // number (8 to 16 bits) than the individual string characters. // // The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a // much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a // safe place to rely on it without worrying about how its usage might affect e.g. memory contents. assembly { // First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999 // range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for // the '0' character. let units := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let tenths := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let hundreds := add(mod(errorCode, 10), 0x30) // With the individual characters, we can now construct the full string. The "BAL#" part is a known constant // (0x42414c23): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the // characters to it, each shifted by a multiple of 8. // The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits // per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte // array). let revertReason := shl(200, add(0x42414c23000000, add(add(units, shl(8, tenths)), shl(16, hundreds)))) // We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded // message will have the following layout: // [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ] // The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We // also write zeroes to the next 28 bytes of memory, but those are about to be overwritten. mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000) // Next is the offset to the location of the string, which will be placed immediately after (20 bytes away). mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020) // The string length is fixed: 7 characters. mstore(0x24, 7) // Finally, the string itself is stored. mstore(0x44, revertReason) // Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of // the encoded message is therefore 4 + 32 + 32 + 32 = 100. revert(0, 100) } } library Errors { // Math uint256 internal constant ADD_OVERFLOW = 0; uint256 internal constant SUB_OVERFLOW = 1; uint256 internal constant SUB_UNDERFLOW = 2; uint256 internal constant MUL_OVERFLOW = 3; uint256 internal constant ZERO_DIVISION = 4; uint256 internal constant DIV_INTERNAL = 5; uint256 internal constant X_OUT_OF_BOUNDS = 6; uint256 internal constant Y_OUT_OF_BOUNDS = 7; uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8; uint256 internal constant INVALID_EXPONENT = 9; // Input uint256 internal constant OUT_OF_BOUNDS = 100; uint256 internal constant UNSORTED_ARRAY = 101; uint256 internal constant UNSORTED_TOKENS = 102; uint256 internal constant INPUT_LENGTH_MISMATCH = 103; uint256 internal constant ZERO_TOKEN = 104; // Shared pools uint256 internal constant MIN_TOKENS = 200; uint256 internal constant MAX_TOKENS = 201; uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202; uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203; uint256 internal constant MINIMUM_BPT = 204; uint256 internal constant CALLER_NOT_VAULT = 205; uint256 internal constant UNINITIALIZED = 206; uint256 internal constant BPT_IN_MAX_AMOUNT = 207; uint256 internal constant BPT_OUT_MIN_AMOUNT = 208; uint256 internal constant EXPIRED_PERMIT = 209; uint256 internal constant NOT_TWO_TOKENS = 210; uint256 internal constant DISABLED = 211; // Pools uint256 internal constant MIN_AMP = 300; uint256 internal constant MAX_AMP = 301; uint256 internal constant MIN_WEIGHT = 302; uint256 internal constant MAX_STABLE_TOKENS = 303; uint256 internal constant MAX_IN_RATIO = 304; uint256 internal constant MAX_OUT_RATIO = 305; uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306; uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307; uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308; uint256 internal constant INVALID_TOKEN = 309; uint256 internal constant UNHANDLED_JOIN_KIND = 310; uint256 internal constant ZERO_INVARIANT = 311; uint256 internal constant ORACLE_INVALID_SECONDS_QUERY = 312; uint256 internal constant ORACLE_NOT_INITIALIZED = 313; uint256 internal constant ORACLE_QUERY_TOO_OLD = 314; uint256 internal constant ORACLE_INVALID_INDEX = 315; uint256 internal constant ORACLE_BAD_SECS = 316; uint256 internal constant AMP_END_TIME_TOO_CLOSE = 317; uint256 internal constant AMP_ONGOING_UPDATE = 318; uint256 internal constant AMP_RATE_TOO_HIGH = 319; uint256 internal constant AMP_NO_ONGOING_UPDATE = 320; uint256 internal constant STABLE_INVARIANT_DIDNT_CONVERGE = 321; uint256 internal constant STABLE_GET_BALANCE_DIDNT_CONVERGE = 322; uint256 internal constant RELAYER_NOT_CONTRACT = 323; uint256 internal constant BASE_POOL_RELAYER_NOT_CALLED = 324; uint256 internal constant REBALANCING_RELAYER_REENTERED = 325; uint256 internal constant GRADUAL_UPDATE_TIME_TRAVEL = 326; uint256 internal constant SWAPS_DISABLED = 327; uint256 internal constant CALLER_IS_NOT_LBP_OWNER = 328; uint256 internal constant PRICE_RATE_OVERFLOW = 329; uint256 internal constant INVALID_JOIN_EXIT_KIND_WHILE_SWAPS_DISABLED = 330; uint256 internal constant WEIGHT_CHANGE_TOO_FAST = 331; uint256 internal constant LOWER_GREATER_THAN_UPPER_TARGET = 332; uint256 internal constant UPPER_TARGET_TOO_HIGH = 333; uint256 internal constant UNHANDLED_BY_LINEAR_POOL = 334; uint256 internal constant OUT_OF_TARGET_RANGE = 335; uint256 internal constant UNHANDLED_EXIT_KIND = 336; uint256 internal constant UNAUTHORIZED_EXIT = 337; uint256 internal constant MAX_MANAGEMENT_SWAP_FEE_PERCENTAGE = 338; uint256 internal constant UNHANDLED_BY_MANAGED_POOL = 339; uint256 internal constant UNHANDLED_BY_PHANTOM_POOL = 340; uint256 internal constant TOKEN_DOES_NOT_HAVE_RATE_PROVIDER = 341; uint256 internal constant INVALID_INITIALIZATION = 342; uint256 internal constant OUT_OF_NEW_TARGET_RANGE = 343; uint256 internal constant UNAUTHORIZED_OPERATION = 344; uint256 internal constant UNINITIALIZED_POOL_CONTROLLER = 345; // Lib uint256 internal constant REENTRANCY = 400; uint256 internal constant SENDER_NOT_ALLOWED = 401; uint256 internal constant PAUSED = 402; uint256 internal constant PAUSE_WINDOW_EXPIRED = 403; uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404; uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405; uint256 internal constant INSUFFICIENT_BALANCE = 406; uint256 internal constant INSUFFICIENT_ALLOWANCE = 407; uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408; uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409; uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410; uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411; uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412; uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413; uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414; uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415; uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416; uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417; uint256 internal constant SAFE_ERC20_CALL_FAILED = 418; uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419; uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420; uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421; uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422; uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423; uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424; uint256 internal constant BUFFER_PERIOD_EXPIRED = 425; uint256 internal constant CALLER_IS_NOT_OWNER = 426; uint256 internal constant NEW_OWNER_IS_ZERO = 427; uint256 internal constant CODE_DEPLOYMENT_FAILED = 428; uint256 internal constant CALL_TO_NON_CONTRACT = 429; uint256 internal constant LOW_LEVEL_CALL_FAILED = 430; uint256 internal constant NOT_PAUSED = 431; uint256 internal constant ADDRESS_ALREADY_ALLOWLISTED = 432; uint256 internal constant ADDRESS_NOT_ALLOWLISTED = 433; uint256 internal constant ERC20_BURN_EXCEEDS_BALANCE = 434; // Vault uint256 internal constant INVALID_POOL_ID = 500; uint256 internal constant CALLER_NOT_POOL = 501; uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502; uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503; uint256 internal constant INVALID_SIGNATURE = 504; uint256 internal constant EXIT_BELOW_MIN = 505; uint256 internal constant JOIN_ABOVE_MAX = 506; uint256 internal constant SWAP_LIMIT = 507; uint256 internal constant SWAP_DEADLINE = 508; uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509; uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510; uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511; uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512; uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513; uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514; uint256 internal constant INVALID_POST_LOAN_BALANCE = 515; uint256 internal constant INSUFFICIENT_ETH = 516; uint256 internal constant UNALLOCATED_ETH = 517; uint256 internal constant ETH_TRANSFER = 518; uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519; uint256 internal constant TOKENS_MISMATCH = 520; uint256 internal constant TOKEN_NOT_REGISTERED = 521; uint256 internal constant TOKEN_ALREADY_REGISTERED = 522; uint256 internal constant TOKENS_ALREADY_SET = 523; uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524; uint256 internal constant NONZERO_TOKEN_BALANCE = 525; uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526; uint256 internal constant POOL_NO_TOKENS = 527; uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528; // Fees uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600; uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601; uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; interface IAuthentication { /** * @dev Returns the action identifier associated with the external function described by `selector`. */ function getActionId(bytes4 selector) external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev Interface for the SignatureValidator helper, used to support meta-transactions. */ interface ISignaturesValidator { /** * @dev Returns the EIP712 domain separator. */ function getDomainSeparator() external view returns (bytes32); /** * @dev Returns the next nonce used by an address to sign messages. */ function getNextNonce(address user) external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev Interface for the TemporarilyPausable helper. */ interface ITemporarilyPausable { /** * @dev Emitted every time the pause state changes by `_setPaused`. */ event PausedStateChanged(bool paused); /** * @dev Returns the current paused state. */ function getPausedState() external view returns ( bool paused, uint256 pauseWindowEndTime, uint256 bufferPeriodEndTime ); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../openzeppelin/IERC20.sol"; /** * @dev Interface for WETH9. * See https://github.com/gnosis/canonical-weth/blob/0dd1ea3e295eef916d0c6223ec63141137d22d67/contracts/WETH9.sol */ interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero * address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like * types. * * This concept is unrelated to a Pool's Asset Managers. */ interface IAsset { // solhint-disable-previous-line no-empty-blocks } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; interface IAuthorizer { /** * @dev Returns true if `account` can perform the action described by `actionId` in the contract `where`. */ function canPerform( bytes32 actionId, address account, address where ) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; // Inspired by Aave Protocol's IFlashLoanReceiver. import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; interface IFlashLoanRecipient { /** * @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient. * * At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this * call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the * Vault, or else the entire flash loan will revert. * * `userData` is the same value passed in the `IVault.flashLoan` call. */ function receiveFlashLoan( IERC20[] memory tokens, uint256[] memory amounts, uint256[] memory feeAmounts, bytes memory userData ) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "./IVault.sol"; import "./IAuthorizer.sol"; interface IProtocolFeesCollector { event SwapFeePercentageChanged(uint256 newSwapFeePercentage); event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage); function withdrawCollectedFees( IERC20[] calldata tokens, uint256[] calldata amounts, address recipient ) external; function setSwapFeePercentage(uint256 newSwapFeePercentage) external; function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external; function getSwapFeePercentage() external view returns (uint256); function getFlashLoanFeePercentage() external view returns (uint256); function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts); function getAuthorizer() external view returns (IAuthorizer); function vault() external view returns (IVault); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; // For compatibility, we're keeping the same function names as in the original Curve code, including the mixed-case // naming convention. // solhint-disable func-name-mixedcase interface ILiquidityGauge { function integrate_fraction(address user) external view returns (uint256); function user_checkpoint(address user) external returns (bool); function is_killed() external view returns (bool); function killGauge() external; function unkillGauge() external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "./ILiquidityGauge.sol"; // For compatibility, we're keeping the same function names as in the original Curve code, including the mixed-case // naming convention. // solhint-disable func-name-mixedcase interface IStakingLiquidityGauge is ILiquidityGauge, IERC20 { function initialize(address lpToken) external; function lp_token() external view returns (IERC20); function deposit(uint256 value, address recipient) external; function withdraw(uint256 value) external; function claim_rewards(address user) external; function add_reward(address rewardToken, address distributor) external; function set_reward_distributor(address rewardToken, address distributor) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./IAuthorizerAdaptor.sol"; // For compatibility, we're keeping the same function names as in the original Curve code, including the mixed-case // naming convention. // solhint-disable func-name-mixedcase interface IVotingEscrow { struct Point { int128 bias; int128 slope; // - dweight / dt uint256 ts; uint256 blk; // block } function epoch() external view returns (uint256); function totalSupply(uint256 timestamp) external view returns (uint256); function user_point_epoch(address user) external view returns (uint256); function point_history(uint256 timestamp) external view returns (Point memory); function user_point_history(address user, uint256 timestamp) external view returns (Point memory); function checkpoint() external; function admin() external view returns (IAuthorizerAdaptor); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; interface IBalancerToken is IERC20 { function mint(address to, uint256 amount) external; function getRoleMemberCount(bytes32 role) external view returns (uint256); function getRoleMember(bytes32 role, uint256 index) external view returns (address); 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; // solhint-disable-next-line func-name-mixedcase function DEFAULT_ADMIN_ROLE() external view returns (bytes32); // solhint-disable-next-line func-name-mixedcase function MINTER_ROLE() external view returns (bytes32); // solhint-disable-next-line func-name-mixedcase function SNAPSHOT_ROLE() external view returns (bytes32); function snapshot() external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/helpers/IAuthentication.sol"; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; interface IBALTokenHolder is IAuthentication { function getName() external view returns (string memory); function withdrawFunds(address recipient, uint256 amount) external; function sweepTokens( IERC20 token, address recipient, uint256 amount ) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ReentrancyGuard.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; import "@balancer-labs/v2-liquidity-mining/contracts/interfaces/IAuthorizerAdaptor.sol"; import "@balancer-labs/v2-liquidity-mining/contracts/interfaces/IGaugeAdder.sol"; import "@balancer-labs/v2-liquidity-mining/contracts/interfaces/IGaugeController.sol"; import "@balancer-labs/v2-liquidity-mining/contracts/interfaces/ISingleRecipientGauge.sol"; import "@balancer-labs/v2-liquidity-mining/contracts/interfaces/IBalancerTokenAdmin.sol"; import "@balancer-labs/v2-standalone-utils/contracts/interfaces/IBALTokenHolder.sol"; /** * @dev The currently deployed Authorizer has a different interface relative to the Authorizer in the monorepo * for granting/revoking roles(referred to as permissions in the new Authorizer) and so we require a one-off interface */ interface ICurrentAuthorizer is IAuthorizer { // solhint-disable-next-line func-name-mixedcase function DEFAULT_ADMIN_ROLE() external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; } // solhint-disable-next-line contract-name-camelcase contract veBALGaugeFixCoordinator is ReentrancyGuard { IVault private immutable _vault; IAuthorizerAdaptor private immutable _authorizerAdaptor; IGaugeController private immutable _gaugeController; IBalancerTokenAdmin private immutable _balancerTokenAdmin; // Weekly emissions are 145k BAL. Recall that BAL has 18 decimals. uint256 public constant VEBAL_BAL_MINT_AMOUNT = 29000e18; // 2 weeks worth of 10% of emissions uint256 public constant ARBITRUM_BAL_MINT_AMOUNT = 20300e18; // 2 weeks worth of 7% of emissions uint256 public constant POLYGON_BAL_MINT_AMOUNT = 49300e18; // 2 weeks worth of 17% of emissions // The total amount of BAL to mint is 29k + 20.3k + 49.3k = 98.6k enum DeploymentStage { PENDING, FIRST_STAGE_DONE } DeploymentStage private _currentDeploymentStage; constructor( IAuthorizerAdaptor authorizerAdaptor, IBalancerTokenAdmin balancerTokenAdmin, IGaugeController gaugeController ) { _currentDeploymentStage = DeploymentStage.PENDING; IVault vault = authorizerAdaptor.getVault(); _vault = vault; _authorizerAdaptor = authorizerAdaptor; _balancerTokenAdmin = balancerTokenAdmin; _gaugeController = gaugeController; } /** * @notice Returns the Balancer Vault. */ function getVault() public view returns (IVault) { return _vault; } /** * @notice Returns the Balancer Vault's current authorizer. */ function getAuthorizer() public view returns (ICurrentAuthorizer) { return ICurrentAuthorizer(address(getVault().getAuthorizer())); } function getAuthorizerAdaptor() public view returns (IAuthorizerAdaptor) { return _authorizerAdaptor; } function getCurrentDeploymentStage() external view returns (DeploymentStage) { return _currentDeploymentStage; } function performFirstStage() external nonReentrant { // Check internal state require(_currentDeploymentStage == DeploymentStage.PENDING, "First step already performed"); // Check external state: we need admin permission on the Authorizer ICurrentAuthorizer authorizer = getAuthorizer(); require(authorizer.canPerform(bytes32(0), address(this), address(0)), "Not Authorizer admin"); // Step 1: Deprecate the LM committee gauge type on the GaugeController. _deprecateLMCommittee(); // Step 2: Set equal weights for all other gauge types. _setGaugeTypeWeights(); // Step 3: Mint BAL which was to be distributed to Polygon and Arbitrum LPs to a multisig for distribution. _mintMissingBAL(); // Step 4: Renounce admin role over the Authorizer. authorizer.revokeRole(bytes32(0), address(this)); _currentDeploymentStage = DeploymentStage.FIRST_STAGE_DONE; } function _deprecateLMCommittee() private { ICurrentAuthorizer authorizer = getAuthorizer(); // The LM committee has been deprecated so we set the type weight to zero and kill the relevant gauge bytes32 changeTypeWeightRole = _authorizerAdaptor.getActionId(IGaugeController.change_type_weight.selector); authorizer.grantRole(changeTypeWeightRole, address(this)); _setGaugeTypeWeight(IGaugeAdder.GaugeType.LiquidityMiningCommittee, 0); authorizer.revokeRole(changeTypeWeightRole, address(this)); address lmCommitteeGauge = 0x7AA5475b2eA29a9F4a1B9Cf1cB72512D1B4Ab75e; require( _streq( IBALTokenHolder(ISingleRecipientGauge(lmCommitteeGauge).getRecipient()).getName(), "Liquidity Mining Committee BAL Holder" ), "Incorrect gauge" ); bytes32 killGaugeRole = _authorizerAdaptor.getActionId(ILiquidityGauge.killGauge.selector); authorizer.grantRole(killGaugeRole, address(this)); _killGauge(lmCommitteeGauge); authorizer.revokeRole(killGaugeRole, address(this)); } function _setGaugeTypeWeights() private { ICurrentAuthorizer authorizer = getAuthorizer(); bytes32 changeTypeWeightRole = _authorizerAdaptor.getActionId(IGaugeController.change_type_weight.selector); authorizer.grantRole(changeTypeWeightRole, address(this)); // We set all gauge types to have an equal weight, except the LMC. uint256 equalTypeWeight = 1; _setGaugeTypeWeight(IGaugeAdder.GaugeType.veBAL, equalTypeWeight); _setGaugeTypeWeight(IGaugeAdder.GaugeType.Ethereum, equalTypeWeight); _setGaugeTypeWeight(IGaugeAdder.GaugeType.Polygon, equalTypeWeight); _setGaugeTypeWeight(IGaugeAdder.GaugeType.Arbitrum, equalTypeWeight); authorizer.revokeRole(changeTypeWeightRole, address(this)); } function _mintMissingBAL() private { ICurrentAuthorizer authorizer = getAuthorizer(); // Mint BAL necessary to make veBAL holders and Polygon and Arbitrum LPs whole. // See: https://forum.balancer.fi/t/decide-on-gauge-unexpected-behavior/2960#keeping-promises-13 IBALTokenHolder veBALHolder = IBALTokenHolder(0x3C1d00181ff86fbac0c3C52991fBFD11f6491D70); require(_streq(veBALHolder.getName(), "Temporary veBAL Liquidity Mining BAL Holder"), "Incorrect holder"); IBALTokenHolder arbitrumHolder = IBALTokenHolder(0x0C925fcE89a22E36EbD9B3C6E0262234E853d2F6); require(_streq(arbitrumHolder.getName(), "Temporary Arbitrum Liquidity Mining BAL Holder"), "Incorrect holder"); IBALTokenHolder polygonHolder = IBALTokenHolder(0x98087bf6A5CA828a6E09391aCE674DBaBB6a4C56); require(_streq(polygonHolder.getName(), "Temporary Polygon Liquidity Mining BAL Holder"), "Incorrect holder"); bytes32 mintBALRole = _balancerTokenAdmin.getActionId(IBalancerTokenAdmin.mint.selector); authorizer.grantRole(mintBALRole, address(this)); _balancerTokenAdmin.mint(address(veBALHolder), VEBAL_BAL_MINT_AMOUNT); _balancerTokenAdmin.mint(address(arbitrumHolder), ARBITRUM_BAL_MINT_AMOUNT); _balancerTokenAdmin.mint(address(polygonHolder), POLYGON_BAL_MINT_AMOUNT); authorizer.revokeRole(mintBALRole, address(this)); } function _killGauge(address gauge) private { getAuthorizerAdaptor().performAction(gauge, abi.encodeWithSelector(ILiquidityGauge.killGauge.selector)); } function _setGaugeTypeWeight(IGaugeAdder.GaugeType typeId, uint256 weight) private { getAuthorizerAdaptor().performAction( address(_gaugeController), abi.encodeWithSelector(IGaugeController.change_type_weight.selector, int128(typeId), weight) ); } function _streq(string memory a, string memory b) private pure returns (bool) { return keccak256(bytes(a)) == keccak256(bytes(b)); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./ILiquidityGauge.sol"; interface ISingleRecipientGauge is ILiquidityGauge { function initialize(address recipient) external; function getRecipient() external view returns (address); }
* @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported./ We're going to dynamically create a revert string based on the error code, with the following format: 'BAL#{errorCode}' where the code is left-padded with zeroes to three digits (so they range from 000 to 999). We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a number (8 to 16 bits) than the individual string characters. The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a safe place to rely on it without worrying about how its usage might affect e.g. memory contents.
function _revert(uint256 errorCode) pure { function getProtocolFeesCollector() external view returns (IProtocolFeesCollector); function setPaused(bool paused) external; function WETH() external view returns (IWETH); } pragma solidity ^0.7.0; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/IAuthentication.sol"; } pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/helpers/IAuthentication.sol"; import "./IAuthorizerAdaptor.sol"; import "./IGaugeController.sol"; import "./ILiquidityGauge.sol"; import "./ILiquidityGaugeFactory.sol"; import "./IStakingLiquidityGauge.sol"; } pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "./IAuthorizerAdaptor.sol"; import "./IVotingEscrow.sol"; } pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/helpers/IAuthentication.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; import "./IBalancerToken.sol"; } pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./ILiquidityGauge.sol"; } pragma solidity ^0.7.0; } assembly { let units := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let tenths := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let hundreds := add(mod(errorCode, 10), 0x30) let revertReason := shl(200, add(0x42414c23000000, add(add(units, shl(8, tenths)), shl(16, hundreds)))) mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000) mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020) mstore(0x24, 7) mstore(0x44, revertReason) revert(0, 100) } }
10,459,199
[ 1, 426, 31537, 598, 279, 15226, 3971, 4191, 1375, 27754, 8338, 5098, 6198, 731, 358, 22249, 854, 3260, 18, 19, 1660, 4565, 8554, 358, 18373, 752, 279, 15226, 533, 2511, 603, 326, 555, 981, 16, 598, 326, 3751, 740, 30, 296, 38, 1013, 95, 27754, 1713, 1625, 326, 981, 353, 2002, 17, 6982, 785, 598, 3634, 281, 358, 8925, 6815, 261, 2048, 2898, 1048, 628, 20546, 358, 22249, 2934, 1660, 2727, 1404, 1240, 15226, 2064, 7488, 316, 326, 6835, 358, 1923, 22801, 963, 30, 518, 5530, 9816, 5242, 3476, 358, 1707, 279, 1300, 261, 28, 358, 2872, 4125, 13, 2353, 326, 7327, 533, 3949, 18, 1021, 5976, 533, 6710, 4886, 716, 13040, 3377, 506, 8249, 316, 348, 7953, 560, 16, 1496, 19931, 5360, 364, 279, 9816, 5545, 550, 4471, 16, 3382, 12392, 22801, 963, 18, 16803, 333, 445, 6301, 1434, 22913, 15226, 87, 16, 333, 353, 279, 4183, 3166, 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, 915, 389, 266, 1097, 12, 11890, 5034, 12079, 13, 16618, 288, 203, 565, 445, 18648, 2954, 281, 7134, 1435, 3903, 1476, 1135, 261, 45, 5752, 2954, 281, 7134, 1769, 203, 203, 565, 445, 444, 28590, 12, 6430, 17781, 13, 3903, 31, 203, 203, 565, 445, 678, 1584, 44, 1435, 3903, 1476, 1135, 261, 45, 59, 1584, 44, 1769, 203, 97, 203, 203, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 27, 18, 20, 31, 203, 203, 5666, 8787, 18770, 17, 80, 5113, 19, 90, 22, 17, 26983, 19, 16351, 87, 19, 15898, 19, 8188, 3714, 18, 18281, 14432, 203, 5666, 8787, 18770, 17, 80, 5113, 19, 90, 22, 17, 30205, 560, 17, 5471, 19, 16351, 87, 19, 11397, 19, 45, 6492, 18, 18281, 14432, 203, 203, 97, 203, 203, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 27, 18, 20, 31, 203, 203, 5666, 8787, 18770, 17, 80, 5113, 19, 90, 22, 17, 30205, 560, 17, 5471, 19, 16351, 87, 19, 11397, 19, 45, 6492, 18, 18281, 14432, 203, 203, 5666, 25165, 45, 17170, 29888, 18, 18281, 14432, 203, 5666, 25165, 3047, 8305, 2933, 18, 18281, 14432, 203, 5666, 25165, 2627, 18988, 24237, 18941, 18, 18281, 14432, 203, 5666, 25165, 2627, 18988, 24237, 18941, 1733, 18, 18281, 14432, 203, 5666, 25165, 45, 510, 6159, 48, 18988, 24237, 18941, 18, 18281, 14432, 203, 203, 97, 203, 203, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 27, 18, 20, 31, 203, 203, 5666, 8787, 18770, 17, 80, 5113, 19, 90, 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/SingularityHeroes.sol pragma solidity 0.7.0; /** * @title SingularityHeroes contract * @dev Extends ERC721 Non-Fungible Token Standard basic implementation */ contract SingularityHeroes is ERC721, Ownable { using SafeMath for uint256; uint256 public constant heroesPrice = 67000000000000000; // 0.067 ETH uint256 public constant maxHeroesPurchase = 25; uint256 public MAX_HEROES = 10000; bool public saleIsActive = false; constructor() ERC721("TheSingularityHeroes", "TSH") {} function withdraw() public onlyOwner { uint256 balance = address(this).balance; msg.sender.transfer(balance); } function reserveHeroes() public onlyOwner { uint256 supply = totalSupply(); uint256 i; for (i = 0; i < 250; i++) { _safeMint(msg.sender, supply + i); } } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } function mintHeroes(uint256 numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Heroes"); require( numberOfTokens <= maxHeroesPurchase, "Can only mint 25 tokens at a time" ); require( totalSupply().add(numberOfTokens) <= MAX_HEROES, "Purchase would exceed max supply of Heroes" ); require( heroesPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct" ); for (uint256 i = 0; i < numberOfTokens; i++) { uint256 mintIndex = totalSupply(); if (totalSupply() < MAX_HEROES) { _safeMint(msg.sender, mintIndex); } } } }
Equivalent to contains(map, key)
if (keyIndex == 0) return (false, 0);
1,093
[ 1, 22606, 358, 1914, 12, 1458, 16, 498, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 261, 856, 1016, 422, 374, 13, 327, 261, 5743, 16, 374, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/40/0x8CFA3e3b2d869F5120Cc0aF1da5780e152Dc3b7f/sources/contracts/ApeUsdtUsdc.sol
70% of Platform fee
uint256 public TREASURY_FEE = 700;
9,541,716
[ 1, 7301, 9, 434, 11810, 14036, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 1071, 399, 862, 3033, 1099, 61, 67, 8090, 41, 273, 2371, 713, 31, 13491, 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/5/0x34cCE743F93880657df0dDb4B83B1f7818eb8fb4/sources/contracts/project/jpeg/JPEGDateFinder.sol
@notice Set Stage of NFT Contract. @param _stage stage of nft contract
function setStage(Stage _stage) external onlyOwner { stage = _stage; }
1,910,959
[ 1, 694, 16531, 434, 423, 4464, 13456, 18, 225, 389, 12869, 6009, 434, 290, 1222, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 444, 8755, 12, 8755, 389, 12869, 13, 7010, 3639, 3903, 7010, 3639, 1338, 5541, 7010, 565, 288, 203, 3639, 6009, 273, 389, 12869, 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 ]