file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
/** * Copyright 2017-2020, bZeroX, LLC <https://bzx.network/>. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; pragma experimental ABIEncoderV2; /** * @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 Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @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"); } } } 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; } } interface IPriceFeeds { function queryRate( address sourceToken, address destToken) external view returns (uint256 rate, uint256 precision); function queryPrecision( address sourceToken, address destToken) external view returns (uint256 precision); function queryReturn( address sourceToken, address destToken, uint256 sourceAmount) external view returns (uint256 destAmount); function checkPriceDisagreement( address sourceToken, address destToken, uint256 sourceAmount, uint256 destAmount, uint256 maxSlippage) external view returns (uint256 sourceToDestSwapRate); function amountInEth( address Token, uint256 amount) external view returns (uint256 ethAmount); function getMaxDrawdown( address loanToken, address collateralToken, uint256 loanAmount, uint256 collateralAmount, uint256 maintenanceMargin) external view returns (uint256); function getCurrentMarginAndCollateralSize( address loanToken, address collateralToken, uint256 loanAmount, uint256 collateralAmount) external view returns (uint256 currentMargin, uint256 collateralInEthAmount); function getCurrentMargin( address loanToken, address collateralToken, uint256 loanAmount, uint256 collateralAmount) external view returns (uint256 currentMargin, uint256 collateralToLoanRate); function shouldLiquidate( address loanToken, address collateralToken, uint256 loanAmount, uint256 collateralAmount, uint256 maintenanceMargin) external view returns (bool); function getFastGasPrice( address payToken) external view returns (uint256); } contract IVestingToken is IERC20 { function claim() external; function vestedBalanceOf( address _owner) external view returns (uint256); function claimedBalanceOf( address _owner) external view returns (uint256); } /** * @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; } } interface IUniswapV2Router { // 0x38ed1739 function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external returns (uint256[] memory amounts); // 0x8803dbee function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline) external returns (uint256[] memory amounts); // 0x1f00ca74 function getAmountsIn( uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); // 0xd06ca61f function getAmountsOut( uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); } interface ICurve3Pool { function add_liquidity( uint256[3] calldata amounts, uint256 min_mint_amount) external; function get_virtual_price() external view returns (uint256); } //0xd061D61a4d941c39E5453435B6345Dc261C2fcE0 eth mainnet interface ICurveMinter { function mint( address _addr ) external; } //0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A eth mainnet interface ICurve3PoolGauge { function balanceOf( address _addr ) external view returns (uint256); function working_balances(address) external view returns (uint256); function claimable_tokens(address) external returns (uint256); function deposit( uint256 _amount ) external; function deposit( uint256 _amount, address _addr ) external; function withdraw( uint256 _amount ) external; function set_approve_deposit( address _addr, bool can_deposit ) external; } /// @title A proxy interface for The Protocol /// @author bZeroX /// @notice This is just an interface, not to be deployed itself. /// @dev This interface is to be used for the protocol interactions. interface IBZx { ////// Protocol ////// /// @dev adds or replaces existing proxy module /// @param target target proxy module address function replaceContract(address target) external; /// @dev updates all proxy modules addreses and function signatures. /// sigsArr and targetsArr should be of equal length /// @param sigsArr array of function signatures /// @param targetsArr array of target proxy module addresses function setTargets( string[] calldata sigsArr, address[] calldata targetsArr ) external; /// @dev returns protocol module address given a function signature /// @return module address function getTarget(string calldata sig) external view returns (address); ////// Protocol Settings ////// /// @dev sets price feed contract address. The contract on the addres should implement IPriceFeeds interface /// @param newContract module address for the IPriceFeeds implementation function setPriceFeedContract(address newContract) external; /// @dev sets swaps contract address. The contract on the addres should implement ISwapsImpl interface /// @param newContract module address for the ISwapsImpl implementation function setSwapsImplContract(address newContract) external; /// @dev sets loan pool with assets. Accepts two arrays of equal length /// @param pools array of address of pools /// @param assets array of addresses of assets function setLoanPool(address[] calldata pools, address[] calldata assets) external; /// @dev updates list of supported tokens, it can be use also to disable or enable particualr token /// @param addrs array of address of pools /// @param toggles array of addresses of assets /// @param withApprovals resets tokens to unlimited approval with the swaps integration (kyber, etc.) function setSupportedTokens( address[] calldata addrs, bool[] calldata toggles, bool withApprovals ) external; /// @dev sets lending fee with WEI_PERCENT_PRECISION /// @param newValue lending fee percent function setLendingFeePercent(uint256 newValue) external; /// @dev sets trading fee with WEI_PERCENT_PRECISION /// @param newValue trading fee percent function setTradingFeePercent(uint256 newValue) external; /// @dev sets borrowing fee with WEI_PERCENT_PRECISION /// @param newValue borrowing fee percent function setBorrowingFeePercent(uint256 newValue) external; /// @dev sets affiliate fee with WEI_PERCENT_PRECISION /// @param newValue affiliate fee percent function setAffiliateFeePercent(uint256 newValue) external; /// @dev sets liquidation inncetive percent per loan per token. This is the profit percent /// that liquidator gets in the process of liquidating. /// @param loanTokens array list of loan tokens /// @param collateralTokens array list of collateral tokens /// @param amounts array list of liquidation inncetive amount function setLiquidationIncentivePercent( address[] calldata loanTokens, address[] calldata collateralTokens, uint256[] calldata amounts ) external; /// @dev sets max swap rate slippage percent. /// @param newAmount max swap rate slippage percent. function setMaxDisagreement(uint256 newAmount) external; /// TODO function setSourceBufferPercent(uint256 newAmount) external; /// @dev sets maximum supported swap size in ETH /// @param newAmount max swap size in ETH. function setMaxSwapSize(uint256 newAmount) external; /// @dev sets fee controller address /// @param newController address of the new fees controller function setFeesController(address newController) external; /// @dev withdraws lending fees to receiver. Only can be called by feesController address /// @param tokens array of token addresses. /// @param receiver fees receiver address /// @return amounts array of amounts withdrawn function withdrawFees( address[] calldata tokens, address receiver, FeeClaimType feeType ) external returns (uint256[] memory amounts); /// @dev withdraw protocol token (BZRX) from vesting contract vBZRX /// @param receiver address of BZRX tokens claimed /// @param amount of BZRX token to be claimed. max is claimed if amount is greater than balance. /// @return rewardToken reward token address /// @return withdrawAmount amount function withdrawProtocolToken(address receiver, uint256 amount) external returns (address rewardToken, uint256 withdrawAmount); /// @dev depozit protocol token (BZRX) /// @param amount address of BZRX tokens to deposit function depositProtocolToken(uint256 amount) external; function grantRewards(address[] calldata users, uint256[] calldata amounts) external returns (uint256 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); function priceFeeds() external view returns (address); function swapsImpl() external view returns (address); function logicTargets(bytes4) external view returns (address); function loans(bytes32) external view returns (Loan memory); function loanParams(bytes32) external view returns (LoanParams memory); // we don't use this yet // function lenderOrders(address, bytes32) external returns (Order memory); // function borrowerOrders(address, bytes32) external returns (Order memory); function delegatedManagers(bytes32, address) external view returns (bool); function lenderInterest(address, address) external view returns (LenderInterest memory); function loanInterest(bytes32) external view returns (LoanInterest memory); function feesController() external view returns (address); function lendingFeePercent() external view returns (uint256); function lendingFeeTokensHeld(address) external view returns (uint256); function lendingFeeTokensPaid(address) external view returns (uint256); function borrowingFeePercent() external view returns (uint256); function borrowingFeeTokensHeld(address) external view returns (uint256); function borrowingFeeTokensPaid(address) external view returns (uint256); function protocolTokenHeld() external view returns (uint256); function protocolTokenPaid() external view returns (uint256); function affiliateFeePercent() external view returns (uint256); function liquidationIncentivePercent(address, address) external view returns (uint256); function loanPoolToUnderlying(address) external view returns (address); function underlyingToLoanPool(address) external view returns (address); function supportedTokens(address) external view returns (bool); function maxDisagreement() external view returns (uint256); function sourceBufferPercent() external view returns (uint256); function maxSwapSize() external view returns (uint256); /// @dev get list of loan pools in the system. Ordering is not guaranteed /// @param start start index /// @param count number of pools to return /// @return loanPoolsList array of loan pools function getLoanPoolsList(uint256 start, uint256 count) external view returns (address[] memory loanPoolsList); /// @dev checks whether addreess is a loan pool address /// @return boolean function isLoanPool(address loanPool) external view returns (bool); ////// Loan Settings ////// /// @dev creates new loan param settings /// @param loanParamsList array of LoanParams /// @return loanParamsIdList array of loan ids created function setupLoanParams(LoanParams[] calldata loanParamsList) external returns (bytes32[] memory loanParamsIdList); /// @dev Deactivates LoanParams for future loans. Active loans using it are unaffected. /// @param loanParamsIdList array of loan ids function disableLoanParams(bytes32[] calldata loanParamsIdList) external; /// @dev gets array of LoanParams by given ids /// @param loanParamsIdList array of loan ids /// @return loanParamsList array of LoanParams function getLoanParams(bytes32[] calldata loanParamsIdList) external view returns (LoanParams[] memory loanParamsList); /// @dev Enumerates LoanParams in the system by owner /// @param owner of the loan params /// @param start number of loans to return /// @param count total number of the items /// @return loanParamsList array of LoanParams function getLoanParamsList( address owner, uint256 start, uint256 count ) external view returns (bytes32[] memory loanParamsList); /// @dev returns total loan principal for token address /// @param lender address /// @param loanToken address /// @return total principal of the loan function getTotalPrincipal(address lender, address loanToken) external view returns (uint256); ////// Loan Openings ////// /// @dev This is THE function that borrows or trades on the protocol /// @param loanParamsId id of the LoanParam created beforehand by setupLoanParams function /// @param loanId id of existing loan, if 0, start a new loan /// @param isTorqueLoan boolean whether it is toreque or non torque loan /// @param initialMargin in WEI_PERCENT_PRECISION /// @param sentAddresses array of size 4: /// lender: must match loan if loanId provided /// borrower: must match loan if loanId provided /// receiver: receiver of funds (address(0) assumes borrower address) /// manager: delegated manager of loan unless address(0) /// @param sentValues array of size 5: /// newRate: new loan interest rate /// newPrincipal: new loan size (borrowAmount + any borrowed interest) /// torqueInterest: new amount of interest to escrow for Torque loan (determines initial loan length) /// loanTokenReceived: total loanToken deposit (amount not sent to borrower in the case of Torque loans) /// collateralTokenReceived: total collateralToken deposit /// @param loanDataBytes required when sending ether /// @return principal of the loan and collateral amount function borrowOrTradeFromPool( bytes32 loanParamsId, bytes32 loanId, bool isTorqueLoan, uint256 initialMargin, address[4] calldata sentAddresses, uint256[5] calldata sentValues, bytes calldata loanDataBytes ) external payable returns (LoanOpenData memory); /// @dev sets/disables/enables the delegated manager for the loan /// @param loanId id of the loan /// @param delegated delegated manager address /// @param toggle boolean set enabled or disabled function setDelegatedManager( bytes32 loanId, address delegated, bool toggle ) external; /// @dev estimates margin exposure for simulated position /// @param loanToken address of the loan token /// @param collateralToken address of collateral token /// @param loanTokenSent amout of loan token sent /// @param collateralTokenSent amount of collateral token sent /// @param interestRate yearly interest rate /// @param newPrincipal principal amount of the loan /// @return estimated margin exposure amount function getEstimatedMarginExposure( address loanToken, address collateralToken, uint256 loanTokenSent, uint256 collateralTokenSent, uint256 interestRate, uint256 newPrincipal ) external view returns (uint256); /// @dev calculates required collateral for simulated position /// @param loanToken address of loan token /// @param collateralToken address of collateral token /// @param newPrincipal principal amount of the loan /// @param marginAmount margin amount of the loan /// @param isTorqueLoan boolean torque or non torque loan /// @return collateralAmountRequired amount required function getRequiredCollateral( address loanToken, address collateralToken, uint256 newPrincipal, uint256 marginAmount, bool isTorqueLoan ) external view returns (uint256 collateralAmountRequired); function getRequiredCollateralByParams( bytes32 loanParamsId, uint256 newPrincipal ) external view returns (uint256 collateralAmountRequired); /// @dev calculates borrow amount for simulated position /// @param loanToken address of loan token /// @param collateralToken address of collateral token /// @param collateralTokenAmount amount of collateral token sent /// @param marginAmount margin amount /// @param isTorqueLoan boolean torque or non torque loan /// @return borrowAmount possible borrow amount function getBorrowAmount( address loanToken, address collateralToken, uint256 collateralTokenAmount, uint256 marginAmount, bool isTorqueLoan ) external view returns (uint256 borrowAmount); function getBorrowAmountByParams( bytes32 loanParamsId, uint256 collateralTokenAmount ) external view returns (uint256 borrowAmount); ////// Loan Closings ////// /// @dev liquidates unhealty loans /// @param loanId id of the loan /// @param receiver address receiving liquidated loan collateral /// @param closeAmount amount to close denominated in loanToken /// @return loanCloseAmount amount of the collateral token of the loan /// @return seizedAmount sezied amount in the collateral token /// @return seizedToken loan token address function liquidate( bytes32 loanId, address receiver, uint256 closeAmount ) external payable returns ( uint256 loanCloseAmount, uint256 seizedAmount, address seizedToken ); /// @dev rollover loan /// @param loanId id of the loan /// @param loanDataBytes reserved for future use. function rollover(bytes32 loanId, bytes calldata loanDataBytes) external returns (address rebateToken, uint256 gasRebate); /// @dev close position with loan token deposit /// @param loanId id of the loan /// @param receiver collateral token reciever address /// @param depositAmount amount of loan token to deposit /// @return loanCloseAmount loan close amount /// @return withdrawAmount loan token withdraw amount /// @return withdrawToken loan token address function closeWithDeposit( bytes32 loanId, address receiver, uint256 depositAmount // denominated in loanToken ) external payable returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ); /// @dev close position with swap /// @param loanId id of the loan /// @param receiver collateral token reciever address /// @param swapAmount amount of loan token to swap /// @param returnTokenIsCollateral boolean whether to return tokens is collateral /// @param loanDataBytes reserved for future use /// @return loanCloseAmount loan close amount /// @return withdrawAmount loan token withdraw amount /// @return withdrawToken loan token address function closeWithSwap( bytes32 loanId, address receiver, uint256 swapAmount, // denominated in collateralToken bool returnTokenIsCollateral, // true: withdraws collateralToken, false: withdraws loanToken bytes calldata loanDataBytes ) external returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ); ////// Loan Closings With Gas Token ////// /// @dev liquidates unhealty loans by using Gas token /// @param loanId id of the loan /// @param receiver address receiving liquidated loan collateral /// @param gasTokenUser user address of the GAS token /// @param closeAmount amount to close denominated in loanToken /// @return loanCloseAmount loan close amount /// @return seizedAmount loan token withdraw amount /// @return seizedToken loan token address function liquidateWithGasToken( bytes32 loanId, address receiver, address gasTokenUser, uint256 closeAmount // denominated in loanToken ) external payable returns ( uint256 loanCloseAmount, uint256 seizedAmount, address seizedToken ); /// @dev rollover loan /// @param loanId id of the loan /// @param gasTokenUser user address of the GAS token function rolloverWithGasToken( bytes32 loanId, address gasTokenUser, bytes calldata /*loanDataBytes*/ ) external returns (address rebateToken, uint256 gasRebate); /// @dev close position with loan token deposit /// @param loanId id of the loan /// @param receiver collateral token reciever address /// @param gasTokenUser user address of the GAS token /// @param depositAmount amount of loan token to deposit denominated in loanToken /// @return loanCloseAmount loan close amount /// @return withdrawAmount loan token withdraw amount /// @return withdrawToken loan token address function closeWithDepositWithGasToken( bytes32 loanId, address receiver, address gasTokenUser, uint256 depositAmount ) external payable returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ); /// @dev close position with swap /// @param loanId id of the loan /// @param receiver collateral token reciever address /// @param gasTokenUser user address of the GAS token /// @param swapAmount amount of loan token to swap denominated in collateralToken /// @param returnTokenIsCollateral true: withdraws collateralToken, false: withdraws loanToken /// @return loanCloseAmount loan close amount /// @return withdrawAmount loan token withdraw amount /// @return withdrawToken loan token address function closeWithSwapWithGasToken( bytes32 loanId, address receiver, address gasTokenUser, uint256 swapAmount, bool returnTokenIsCollateral, bytes calldata loanDataBytes ) external returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ); ////// Loan Maintenance ////// /// @dev deposit collateral to existing loan /// @param loanId existing loan id /// @param depositAmount amount to deposit which must match msg.value if ether is sent function depositCollateral(bytes32 loanId, uint256 depositAmount) external payable; /// @dev withdraw collateral from existing loan /// @param loanId existing lona id /// @param receiver address of withdrawn tokens /// @param withdrawAmount amount to withdraw /// @return actualWithdrawAmount actual amount withdrawn function withdrawCollateral( bytes32 loanId, address receiver, uint256 withdrawAmount ) external returns (uint256 actualWithdrawAmount); /// @dev withdraw accrued interest rate for a loan given token address /// @param loanToken loan token address function withdrawAccruedInterest(address loanToken) external; /// @dev extends loan duration by depositing more collateral /// @param loanId id of the existing loan /// @param depositAmount amount to deposit /// @param useCollateral boolean whether to extend using collateral or deposit amount /// @return secondsExtended by that number of seconds loan duration was extended function extendLoanDuration( bytes32 loanId, uint256 depositAmount, bool useCollateral, bytes calldata // for future use /*loanDataBytes*/ ) external payable returns (uint256 secondsExtended); /// @dev reduces loan duration by withdrawing collateral /// @param loanId id of the existing loan /// @param receiver address to receive tokens /// @param withdrawAmount amount to withdraw /// @return secondsReduced by that number of seconds loan duration was extended function reduceLoanDuration( bytes32 loanId, address receiver, uint256 withdrawAmount ) external returns (uint256 secondsReduced); function setDepositAmount( bytes32 loanId, uint256 depositValueAsLoanToken, uint256 depositValueAsCollateralToken ) external; function claimRewards(address receiver) external returns (uint256 claimAmount); function transferLoan(bytes32 loanId, address newOwner) external; function rewardsBalanceOf(address user) external view returns (uint256 rewardsBalance); /// @dev Gets current lender interest data totals for all loans with a specific oracle and interest token /// @param lender The lender address /// @param loanToken The loan token address /// @return interestPaid The total amount of interest that has been paid to a lender so far /// @return interestPaidDate The date of the last interest pay out, or 0 if no interest has been withdrawn yet /// @return interestOwedPerDay The amount of interest the lender is earning per day /// @return interestUnPaid The total amount of interest the lender is owned and not yet withdrawn /// @return interestFeePercent The fee retained by the protocol before interest is paid to the lender /// @return principalTotal The total amount of outstading principal the lender has loaned function getLenderInterestData(address lender, address loanToken) external view returns ( uint256 interestPaid, uint256 interestPaidDate, uint256 interestOwedPerDay, uint256 interestUnPaid, uint256 interestFeePercent, uint256 principalTotal ); /// @dev Gets current interest data for a loan /// @param loanId A unique id representing the loan /// @return loanToken The loan token that interest is paid in /// @return interestOwedPerDay The amount of interest the borrower is paying per day /// @return interestDepositTotal The total amount of interest the borrower has deposited /// @return interestDepositRemaining The amount of deposited interest that is not yet owed to a lender function getLoanInterestData(bytes32 loanId) external view returns ( address loanToken, uint256 interestOwedPerDay, uint256 interestDepositTotal, uint256 interestDepositRemaining ); /// @dev gets list of loans of particular user address /// @param user address of the loans /// @param start of the index /// @param count number of loans to return /// @param loanType type of the loan: All(0), Margin(1), NonMargin(2) /// @param isLender whether to list lender loans or borrower loans /// @param unsafeOnly booleat if true return only unsafe loans that are open for liquidation /// @return loansData LoanReturnData array of loans function getUserLoans( address user, uint256 start, uint256 count, LoanType loanType, bool isLender, bool unsafeOnly ) external view returns (LoanReturnData[] memory loansData); function getUserLoansCount(address user, bool isLender) external view returns (uint256); /// @dev gets existing loan /// @param loanId id of existing loan /// @return loanData array of loans function getLoan(bytes32 loanId) external view returns (LoanReturnData memory loanData); /// @dev get current active loans in the system /// @param start of the index /// @param count number of loans to return /// @param unsafeOnly boolean if true return unsafe loan only (open for liquidation) function getActiveLoans( uint256 start, uint256 count, bool unsafeOnly ) external view returns (LoanReturnData[] memory loansData); /// @dev get current active loans in the system /// @param start of the index /// @param count number of loans to return /// @param unsafeOnly boolean if true return unsafe loan only (open for liquidation) /// @param isLiquidatable boolean if true return liquidatable loans only function getActiveLoansAdvanced( uint256 start, uint256 count, bool unsafeOnly, bool isLiquidatable ) external view returns (LoanReturnData[] memory loansData); function getActiveLoansCount() external view returns (uint256); ////// Swap External ////// /// @dev swap thru external integration /// @param sourceToken source token address /// @param destToken destintaion token address /// @param receiver address to receive tokens /// @param returnToSender TODO /// @param sourceTokenAmount source token amount /// @param requiredDestTokenAmount destination token amount /// @param swapData TODO /// @return destTokenAmountReceived destination token received /// @return sourceTokenAmountUsed source token amount used function swapExternal( address sourceToken, address destToken, address receiver, address returnToSender, uint256 sourceTokenAmount, uint256 requiredDestTokenAmount, bytes calldata swapData ) external payable returns ( uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed ); /// @dev swap thru external integration using GAS /// @param sourceToken source token address /// @param destToken destintaion token address /// @param receiver address to receive tokens /// @param returnToSender TODO /// @param gasTokenUser user address of the GAS token /// @param sourceTokenAmount source token amount /// @param requiredDestTokenAmount destination token amount /// @param swapData TODO /// @return destTokenAmountReceived destination token received /// @return sourceTokenAmountUsed source token amount used function swapExternalWithGasToken( address sourceToken, address destToken, address receiver, address returnToSender, address gasTokenUser, uint256 sourceTokenAmount, uint256 requiredDestTokenAmount, bytes calldata swapData ) external payable returns ( uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed ); /// @dev calculate simulated return of swap /// @param sourceToken source token address /// @param destToken destination token address /// @param sourceTokenAmount source token amount /// @return amoun denominated in destination token function getSwapExpectedReturn( address sourceToken, address destToken, uint256 sourceTokenAmount ) external view returns (uint256); function owner() external view returns (address); function transferOwnership(address newOwner) external; /// Guardian Interface function _isPaused(bytes4 sig) external view returns (bool isPaused); function toggleFunctionPause(bytes4 sig) external; function toggleFunctionUnPause(bytes4 sig) external; function changeGuardian(address newGuardian) external; function getGuardian() external view returns (address guardian); /// Loan Cleanup Interface function cleanupLoans( address loanToken, bytes32[] calldata loanIds) external payable returns (uint256 totalPrincipalIn); struct LoanParams { bytes32 id; bool active; address owner; address loanToken; address collateralToken; uint256 minInitialMargin; uint256 maintenanceMargin; uint256 maxLoanTerm; } struct LoanOpenData { bytes32 loanId; uint256 principal; uint256 collateral; } enum LoanType { All, Margin, NonMargin } struct LoanReturnData { bytes32 loanId; uint96 endTimestamp; address loanToken; address collateralToken; uint256 principal; uint256 collateral; uint256 interestOwedPerDay; uint256 interestDepositRemaining; uint256 startRate; uint256 startMargin; uint256 maintenanceMargin; uint256 currentMargin; uint256 maxLoanTerm; uint256 maxLiquidatable; uint256 maxSeizable; uint256 depositValueAsLoanToken; uint256 depositValueAsCollateralToken; } enum FeeClaimType { All, Lending, Trading, Borrowing } 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 } 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 } struct LoanInterest { uint256 owedPerDay; // interest owed per day for loan uint256 depositTotal; // total escrowed interest for loan uint256 updatedTimestamp; // last update } } /* * @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(), "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; } } interface IMasterChefSushi { struct UserInfo { uint256 amount; uint256 rewardDebt; } function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; // Info of each user that stakes LP tokens. function userInfo(uint256, address) external view returns (UserInfo memory); function pendingSushi(uint256 _pid, address _user) external view returns (uint256); } interface IStaking { struct ProposalState { uint256 proposalTime; uint256 iBZRXWeight; uint256 lpBZRXBalance; uint256 lpTotalSupply; } struct AltRewardsUserInfo { uint256 rewardsPerShare; uint256 pendingRewards; } function getCurrentFeeTokens() external view returns (address[] memory); function maxUniswapDisagreement() external view returns (uint256); function isPaused() external view returns (bool); function fundsWallet() external view returns (address); function callerRewardDivisor() external view returns (uint256); function maxCurveDisagreement() external view returns (uint256); function rewardPercent() external view returns (uint256); function addRewards(uint256 newBZRX, uint256 newStableCoin) external; function stake( address[] calldata tokens, uint256[] calldata values ) external; function unstake( address[] calldata tokens, uint256[] calldata values ) external; function earned(address account) external view returns ( uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting, uint256 sushiRewardsEarned ); function pendingCrvRewards(address account) external view returns ( uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting, uint256 sushiRewardsEarned ); function getVariableWeights() external view returns (uint256 vBZRXWeight, uint256 iBZRXWeight, uint256 LPTokenWeight); function balanceOfByAsset( address token, address account) external view returns (uint256 balance); function balanceOfByAssets( address account) external view returns ( uint256 bzrxBalance, uint256 iBZRXBalance, uint256 vBZRXBalance, uint256 LPTokenBalance, uint256 LPTokenBalanceOld ); function balanceOfStored( address account) external view returns (uint256 vestedBalance, uint256 vestingBalance); function totalSupplyStored() external view returns (uint256 supply); function vestedBalanceForAmount( uint256 tokenBalance, uint256 lastUpdate, uint256 vestingEndTime) external view returns (uint256 vested); function votingBalanceOf( address account, uint256 proposalId) external view returns (uint256 totalVotes); function votingBalanceOfNow( address account) external view returns (uint256 totalVotes); function votingFromStakedBalanceOf( address account) external view returns (uint256 totalVotes); function _setProposalVals( address account, uint256 proposalId) external returns (uint256); function exit() external; function addAltRewards(address token, uint256 amount) external; function governor() external view returns(address); } contract StakingConstants { address public constant BZRX = 0x56d811088235F11C8920698a204A5010a788f4b3; address public constant vBZRX = 0xB72B31907C1C95F3650b64b2469e08EdACeE5e8F; address public constant iBZRX = 0x18240BD9C07fA6156Ce3F3f61921cC82b2619157; address public constant LPToken = 0xa30911e072A0C88D55B5D0A0984B66b0D04569d0; // sushiswap address public constant LPTokenOld = 0xe26A220a341EAca116bDa64cF9D5638A935ae629; // balancer IERC20 public constant curve3Crv = IERC20(0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490); address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address public constant SUSHI = 0x6B3595068778DD592e39A122f4f5a5cF09C90fE2; IUniswapV2Router public constant uniswapRouter = IUniswapV2Router(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // sushiswap ICurve3Pool public constant curve3pool = ICurve3Pool(0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7); IBZx public constant bZx = IBZx(0xD8Ee69652E4e4838f2531732a46d1f7F584F0b7f); uint256 public constant cliffDuration = 15768000; // 86400 * 365 * 0.5 uint256 public constant vestingDuration = 126144000; // 86400 * 365 * 4 uint256 internal constant vestingDurationAfterCliff = 110376000; // 86400 * 365 * 3.5 uint256 internal constant vestingStartTimestamp = 1594648800; // start_time uint256 internal constant vestingCliffTimestamp = vestingStartTimestamp + cliffDuration; uint256 internal constant vestingEndTimestamp = vestingStartTimestamp + vestingDuration; uint256 internal constant _startingVBZRXBalance = 889389933e18; // 889,389,933 BZRX address internal constant SUSHI_MASTERCHEF = 0xc2EdaD668740f1aA35E4D8f227fB8E17dcA888Cd; uint256 internal constant BZRX_ETH_SUSHI_MASTERCHEF_PID = 188; uint256 public constant BZRXWeightStored = 1e18; ICurveMinter public constant curveMinter = ICurveMinter(0xd061D61a4d941c39E5453435B6345Dc261C2fcE0); ICurve3PoolGauge public constant curve3PoolGauge = ICurve3PoolGauge(0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A); address public constant CRV = 0xD533a949740bb3306d119CC777fa900bA034cd52; struct DelegatedTokens { address user; uint256 BZRX; uint256 vBZRX; uint256 iBZRX; uint256 LPToken; uint256 totalVotes; } event Stake( address indexed user, address indexed token, address indexed delegate, uint256 amount ); event Unstake( address indexed user, address indexed token, address indexed delegate, uint256 amount ); event AddRewards( address indexed sender, uint256 bzrxAmount, uint256 stableCoinAmount ); event Claim( address indexed user, uint256 bzrxAmount, uint256 stableCoinAmount ); event ChangeDelegate( address indexed user, address indexed oldDelegate, address indexed newDelegate ); event WithdrawFees( address indexed sender ); event ConvertFees( address indexed sender, uint256 bzrxOutput, uint256 stableCoinOutput ); event DistributeFees( address indexed sender, uint256 bzrxRewards, uint256 stableCoinRewards ); event AddAltRewards( address indexed sender, address indexed token, uint256 amount ); event ClaimAltRewards( address indexed user, address indexed token, uint256 amount ); } contract StakingUpgradeable is Ownable { address public implementation; } contract StakingState is StakingUpgradeable { using SafeMath for uint256; using SafeERC20 for IERC20; using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set; uint256 public constant initialCirculatingSupply = 1030000000e18 - 889389933e18; address internal constant ZERO_ADDRESS = address(0); bool public isPaused; address public fundsWallet; mapping(address => uint256) internal _totalSupplyPerToken; // token => value mapping(address => mapping(address => uint256)) internal _balancesPerToken; // token => account => value mapping(address => address) internal delegate; // user => delegate (DEPRECIATED) mapping(address => mapping(address => uint256)) internal delegatedPerToken; // token => user => value (DEPRECIATED) uint256 public bzrxPerTokenStored; mapping(address => uint256) public bzrxRewardsPerTokenPaid; // user => value mapping(address => uint256) public bzrxRewards; // user => value mapping(address => uint256) public bzrxVesting; // user => value uint256 public stableCoinPerTokenStored; mapping(address => uint256) public stableCoinRewardsPerTokenPaid; // user => value mapping(address => uint256) public stableCoinRewards; // user => value mapping(address => uint256) public stableCoinVesting; // user => value uint256 public vBZRXWeightStored; uint256 public iBZRXWeightStored; uint256 public LPTokenWeightStored; EnumerableBytes32Set.Bytes32Set internal _delegatedSet; uint256 public lastRewardsAddTime; mapping(address => uint256) public vestingLastSync; mapping(address => address[]) public swapPaths; mapping(address => uint256) public stakingRewards; uint256 public rewardPercent = 50e18; uint256 public maxUniswapDisagreement = 3e18; uint256 public maxCurveDisagreement = 3e18; uint256 public callerRewardDivisor = 100; address[] public currentFeeTokens; struct ProposalState { uint256 proposalTime; uint256 iBZRXWeight; uint256 lpBZRXBalance; uint256 lpTotalSupply; } address public governor; mapping(uint256 => ProposalState) internal _proposalState; mapping(address => uint256[]) public altRewardsRounds; // depreciated mapping(address => uint256) public altRewardsPerShare; // token => value // Token => (User => Info) mapping(address => mapping(address => IStaking.AltRewardsUserInfo)) public userAltRewardsPerShare; address public voteDelegator; } contract PausableGuardian is Ownable { // keccak256("Pausable_FunctionPause") bytes32 internal constant Pausable_FunctionPause = 0xa7143c84d793a15503da6f19bf9119a2dac94448ca45d77c8bf08f57b2e91047; // keccak256("Pausable_GuardianAddress") bytes32 internal constant Pausable_GuardianAddress = 0x80e6706973d0c59541550537fd6a33b971efad732635e6c3b99fb01006803cdf; modifier pausable { require(!_isPaused(msg.sig), "paused"); _; } function _isPaused(bytes4 sig) public view returns (bool isPaused) { bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause)); assembly { isPaused := sload(slot) } } function toggleFunctionPause(bytes4 sig) public { require(msg.sender == getGuardian() || msg.sender == owner(), "unauthorized"); bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause)); assembly { sstore(slot, 1) } } function toggleFunctionUnPause(bytes4 sig) public { // only DAO can unpause, and adding guardian temporarily require(msg.sender == getGuardian() || msg.sender == owner(), "unauthorized"); bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause)); assembly { sstore(slot, 0) } } function changeGuardian(address newGuardian) public { require(msg.sender == getGuardian() || msg.sender == owner(), "unauthorized"); assembly { sstore(Pausable_GuardianAddress, newGuardian) } } function getGuardian() public view returns (address guardian) { assembly { guardian := sload(Pausable_GuardianAddress) } } } contract GovernorBravoEvents { /// @notice An event emitted when a new proposal is created event ProposalCreated(uint id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description); /// @notice An event emitted when a vote has been cast on a proposal /// @param voter The address which casted a vote /// @param proposalId The proposal id which was voted on /// @param support Support value for the vote. 0=against, 1=for, 2=abstain /// @param votes Number of votes which were cast by the voter /// @param reason The reason given for the vote by the voter event VoteCast(address indexed voter, uint proposalId, uint8 support, uint votes, string reason); /// @notice An event emitted when a proposal has been canceled event ProposalCanceled(uint id); /// @notice An event emitted when a proposal has been queued in the Timelock event ProposalQueued(uint id, uint eta); /// @notice An event emitted when a proposal has been executed in the Timelock event ProposalExecuted(uint id); /// @notice An event emitted when the voting delay is set event VotingDelaySet(uint oldVotingDelay, uint newVotingDelay); /// @notice An event emitted when the voting period is set event VotingPeriodSet(uint oldVotingPeriod, uint newVotingPeriod); /// @notice Emitted when implementation is changed event NewImplementation(address oldImplementation, address newImplementation); /// @notice Emitted when proposal threshold is set event ProposalThresholdSet(uint oldProposalThreshold, uint newProposalThreshold); /// @notice Emitted when pendingAdmin is changed event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /// @notice Emitted when pendingAdmin is accepted, which means admin is updated event NewAdmin(address oldAdmin, address newAdmin); } contract GovernorBravoDelegatorStorage { /// @notice Administrator for this contract address public admin; /// @notice Pending administrator for this contract address public pendingAdmin; /// @notice Active brains of Governor address public implementation; /// @notice The address of the Governor Guardian address public guardian; } /** * @title Storage for Governor Bravo Delegate * @notice For future upgrades, do not change GovernorBravoDelegateStorageV1. Create a new * contract which implements GovernorBravoDelegateStorageV1 and following the naming convention * GovernorBravoDelegateStorageVX. */ contract GovernorBravoDelegateStorageV1 is GovernorBravoDelegatorStorage { /// @notice The delay before voting on a proposal may take place, once proposed, in blocks uint public votingDelay; /// @notice The duration of voting on a proposal, in blocks uint public votingPeriod; /// @notice The number of votes required in order for a voter to become a proposer uint public proposalThreshold; /// @notice Initial proposal id set at become uint public initialProposalId; /// @notice The total number of proposals uint public proposalCount; /// @notice The address of the bZx Protocol Timelock TimelockInterface public timelock; /// @notice The address of the bZx governance token StakingInterface public staking; /// @notice The official record of all proposals ever proposed mapping (uint => Proposal) public proposals; /// @notice The latest proposal for each proposer mapping (address => uint) public latestProposalIds; struct Proposal { /// @notice Unique id for looking up a proposal uint id; /// @notice Creator of the proposal address proposer; /// @notice The timestamp that the proposal will be available for execution, set once the vote succeeds uint eta; /// @notice the ordered list of target addresses for calls to be made address[] targets; /// @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made uint[] values; /// @notice The ordered list of function signatures to be called string[] signatures; /// @notice The ordered list of calldata to be passed to each call bytes[] calldatas; /// @notice The block at which voting begins: holders must delegate their votes prior to this block uint startBlock; /// @notice The block at which voting ends: votes must be cast prior to this block uint endBlock; /// @notice Current number of votes in favor of this proposal uint forVotes; /// @notice Current number of votes in opposition to this proposal uint againstVotes; /// @notice Current number of votes for abstaining for this proposal uint abstainVotes; /// @notice Flag marking whether the proposal has been canceled bool canceled; /// @notice Flag marking whether the proposal has been executed bool executed; /// @notice Receipts of ballots for the entire set of voters mapping (address => Receipt) receipts; } /// @notice Ballot receipt record for a voter struct Receipt { /// @notice Whether or not a vote has been cast bool hasVoted; /// @notice Whether or not the voter supports the proposal or abstains uint8 support; /// @notice The number of votes the voter had, which were cast uint96 votes; } /// @notice Possible states that a proposal may be in enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } } interface TimelockInterface { function delay() external view returns (uint); function GRACE_PERIOD() external view returns (uint); function acceptAdmin() external; function queuedTransactions(bytes32 hash) external view returns (bool); function queueTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external returns (bytes32); function cancelTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external; function executeTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external payable returns (bytes memory); } interface StakingInterface { function votingBalanceOf( address account, uint proposalCount) external view returns (uint totalVotes); function votingBalanceOfNow( address account) external view returns (uint totalVotes); function _setProposalVals( address account, uint proposalCount) external returns (uint); } interface GovernorAlpha { /// @notice The total number of proposals function proposalCount() external returns (uint); } contract GovernorBravoDelegate is GovernorBravoDelegateStorageV1, GovernorBravoEvents { /// @notice The name of this contract string public constant name = "bZx Governor Bravo"; /// @notice The minimum setable proposal threshold uint public constant MIN_PROPOSAL_THRESHOLD = 5150000e18; // 5,150,000 = 0.5% of BZRX /// @notice The maximum setable proposal threshold uint public constant MAX_PROPOSAL_THRESHOLD = 20600000e18; // 20,600,000 = 2% of BZRX /// @notice The minimum setable voting period uint public constant MIN_VOTING_PERIOD = 5760; // About 24 hours /// @notice The max setable voting period uint public constant MAX_VOTING_PERIOD = 80640; // About 2 weeks /// @notice The min setable voting delay uint public constant MIN_VOTING_DELAY = 1; /// @notice The max setable voting delay uint public constant MAX_VOTING_DELAY = 40320; // About 1 week /// @notice The maximum number of actions that can be included in a proposal uint public constant proposalMaxOperations = 100; // 100 actions /// @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 ballot struct used by the contract bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)"); mapping (uint => uint) public quorumVotesForProposal; // proposalId => quorum votes required /** * @notice Used to initialize the contract during delegator contructor * @param timelock_ The address of the Timelock * @param staking_ The address of the STAKING * @param votingPeriod_ The initial voting period * @param votingDelay_ The initial voting delay * @param proposalThreshold_ The initial proposal threshold */ function initialize(address timelock_, address staking_, uint votingPeriod_, uint votingDelay_, uint proposalThreshold_) public { require(address(timelock) == address(0), "GovernorBravo::initialize: can only initialize once"); require(msg.sender == admin, "GovernorBravo::initialize: admin only"); require(timelock_ != address(0), "GovernorBravo::initialize: invalid timelock address"); require(staking_ != address(0), "GovernorBravo::initialize: invalid STAKING address"); require(votingPeriod_ >= MIN_VOTING_PERIOD && votingPeriod_ <= MAX_VOTING_PERIOD, "GovernorBravo::initialize: invalid voting period"); require(votingDelay_ >= MIN_VOTING_DELAY && votingDelay_ <= MAX_VOTING_DELAY, "GovernorBravo::initialize: invalid voting delay"); require(proposalThreshold_ >= MIN_PROPOSAL_THRESHOLD && proposalThreshold_ <= MAX_PROPOSAL_THRESHOLD, "GovernorBravo::initialize: invalid proposal threshold"); timelock = TimelockInterface(timelock_); staking = StakingInterface(staking_); votingPeriod = votingPeriod_; votingDelay = votingDelay_; proposalThreshold = proposalThreshold_; guardian = msg.sender; } /** * @notice Function used to propose a new proposal. Sender must have delegates above the proposal threshold * @param targets Target addresses for proposal calls * @param values Eth values for proposal calls * @param signatures Function signatures for proposal calls * @param calldatas Calldatas for proposal calls * @param description String description of the proposal * @return Proposal id of new proposal */ function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) { require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorBravo::propose: proposal function information arity mismatch"); require(targets.length != 0, "GovernorBravo::propose: must provide actions"); require(targets.length <= proposalMaxOperations, "GovernorBravo::propose: too many actions"); uint latestProposalId = latestProposalIds[msg.sender]; if (latestProposalId != 0) { ProposalState proposersLatestProposalState = state(latestProposalId); require(proposersLatestProposalState != ProposalState.Active, "GovernorBravo::propose: one live proposal per proposer, found an already active proposal"); require(proposersLatestProposalState != ProposalState.Pending, "GovernorBravo::propose: one live proposal per proposer, found an already pending proposal"); } uint proposalId = proposalCount + 1; require(staking._setProposalVals(msg.sender, proposalId) > proposalThreshold, "GovernorBravo::propose: proposer votes below proposal threshold"); proposalCount = proposalId; uint startBlock = add256(block.number, votingDelay); uint endBlock = add256(startBlock, votingPeriod); Proposal memory newProposal = Proposal({ id: proposalId, proposer: msg.sender, eta: 0, targets: targets, values: values, signatures: signatures, calldatas: calldatas, startBlock: startBlock, endBlock: endBlock, forVotes: 0, againstVotes: 0, abstainVotes: 0, canceled: false, executed: false }); proposals[proposalId] = newProposal; latestProposalIds[msg.sender] = proposalId; quorumVotesForProposal[proposalId] = quorumVotes(); emit ProposalCreated(proposalId, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description); return proposalId; } /** * @notice Queues a proposal of state succeeded * @param proposalId The id of the proposal to queue */ function queue(uint proposalId) external { require(state(proposalId) == ProposalState.Succeeded, "GovernorBravo::queue: proposal can only be queued if it is succeeded"); Proposal storage proposal = proposals[proposalId]; uint eta = add256(block.timestamp, timelock.delay()); for (uint i = 0; i < proposal.targets.length; i++) { queueOrRevertInternal(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta); } proposal.eta = eta; emit ProposalQueued(proposalId, eta); } function queueOrRevertInternal(address target, uint value, string memory signature, bytes memory data, uint eta) internal { require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorBravo::queueOrRevertInternal: identical proposal action already queued at eta"); timelock.queueTransaction(target, value, signature, data, eta); } /** * @notice Executes a queued proposal if eta has passed * @param proposalId The id of the proposal to execute */ function execute(uint proposalId) external payable { require(state(proposalId) == ProposalState.Queued, "GovernorBravo::execute: proposal can only be executed if it is queued"); Proposal storage proposal = proposals[proposalId]; proposal.executed = true; for (uint i = 0; i < proposal.targets.length; i++) { timelock.executeTransaction.value(proposal.values[i])(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalExecuted(proposalId); } /** * @notice Cancels a proposal only if sender is the proposer, or proposer delegates dropped below proposal threshold * @param proposalId The id of the proposal to cancel */ function cancel(uint proposalId) external { require(state(proposalId) != ProposalState.Executed, "GovernorBravo::cancel: cannot cancel executed proposal"); Proposal storage proposal = proposals[proposalId]; require(msg.sender == proposal.proposer || staking.votingBalanceOfNow(proposal.proposer) < proposalThreshold || msg.sender == guardian, "GovernorBravo::cancel: proposer above threshold"); proposal.canceled = true; for (uint i = 0; i < proposal.targets.length; i++) { timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalCanceled(proposalId); } /** * @notice Gets the current voting quroum * @return The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed */ // TODO: Update for OOKI. Handle OOKI surplus mint function quorumVotes() public view returns (uint256) { uint256 vestingSupply = IERC20(0x56d811088235F11C8920698a204A5010a788f4b3) // BZRX .balanceOf(0xB72B31907C1C95F3650b64b2469e08EdACeE5e8F); // vBZRX uint256 circulatingSupply = 1030000000e18 - vestingSupply; // no overflow uint256 quorum = circulatingSupply * 4 / 100; if (quorum < 15450000e18) { // min quorum is 1.5% of totalSupply quorum = 15450000e18; } return quorum; } /** * @notice Gets actions of a proposal * @param proposalId the id of the proposal * @return Targets, values, signatures, and calldatas of the proposal actions */ function getActions(uint proposalId) external view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) { Proposal storage p = proposals[proposalId]; return (p.targets, p.values, p.signatures, p.calldatas); } /** * @notice Gets the receipt for a voter on a given proposal * @param proposalId the id of proposal * @param voter The address of the voter * @return The voting receipt */ function getReceipt(uint proposalId, address voter) external view returns (Receipt memory) { return proposals[proposalId].receipts[voter]; } /** * @notice Gets the state of a proposal * @param proposalId The id of the proposal * @return Proposal state */ function state(uint proposalId) public view returns (ProposalState) { require(proposalCount >= proposalId && proposalId > initialProposalId, "GovernorBravo::state: invalid proposal id"); Proposal storage proposal = proposals[proposalId]; if (proposal.canceled) { return ProposalState.Canceled; } else if (block.number <= proposal.startBlock) { return ProposalState.Pending; } else if (block.number <= proposal.endBlock) { return ProposalState.Active; } else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotesForProposal[proposalId]) { return ProposalState.Defeated; } else if (proposal.eta == 0) { return ProposalState.Succeeded; } else if (proposal.executed) { return ProposalState.Executed; } else if (block.timestamp >= add256(proposal.eta, timelock.GRACE_PERIOD())) { return ProposalState.Expired; } else { return ProposalState.Queued; } } /** * @notice Cast a vote for a proposal * @param proposalId The id of the proposal to vote on * @param support The support value for the vote. 0=against, 1=for, 2=abstain */ function castVote(uint proposalId, uint8 support) external { emit VoteCast(msg.sender, proposalId, support, castVoteInternal(msg.sender, proposalId, support), ""); } /** * @notice Cast a vote for a proposal with a reason * @param proposalId The id of the proposal to vote on * @param support The support value for the vote. 0=against, 1=for, 2=abstain * @param reason The reason given for the vote by the voter */ function castVoteWithReason(uint proposalId, uint8 support, string calldata reason) external { emit VoteCast(msg.sender, proposalId, support, castVoteInternal(msg.sender, proposalId, support), reason); } /** * @notice Cast a vote for a proposal by signature * @dev External function that accepts EIP-712 signatures for voting on proposals. */ function castVoteBySig(uint proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainIdInternal(), address(this))); bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "GovernorBravo::castVoteBySig: invalid signature"); emit VoteCast(signatory, proposalId, support, castVoteInternal(signatory, proposalId, support), ""); } /** * @dev Allows batching to castVote function */ function castVotes(uint[] calldata proposalIds, uint8[] calldata supportVals) external { require(proposalIds.length == supportVals.length, "count mismatch"); for (uint256 i = 0; i < proposalIds.length; i++) { emit VoteCast(msg.sender, proposalIds[i], supportVals[i], castVoteInternal(msg.sender, proposalIds[i], supportVals[i]), ""); } } /** * @dev Allows batching to castVoteWithReason function */ function castVotesWithReason(uint[] calldata proposalIds, uint8[] calldata supportVals, string[] calldata reasons) external { require(proposalIds.length == supportVals.length && proposalIds.length == reasons.length, "count mismatch"); for (uint256 i = 0; i < proposalIds.length; i++) { emit VoteCast(msg.sender, proposalIds[i], supportVals[i], castVoteInternal(msg.sender, proposalIds[i], supportVals[i]), reasons[i]); } } /** * @dev Allows batching to castVoteBySig function */ function castVotesBySig(uint[] calldata proposalIds, uint8[] calldata supportVals, uint8[] calldata vs, bytes32[] calldata rs, bytes32[] calldata ss) external { require(proposalIds.length == supportVals.length && proposalIds.length == vs.length && proposalIds.length == rs.length && proposalIds.length == ss.length, "count mismatch"); for (uint256 i = 0; i < proposalIds.length; i++) { castVoteBySig(proposalIds[i], supportVals[i], vs[i], rs[i], ss[i]); } } /** * @notice Internal function that caries out voting logic * @param voter The voter that is casting their vote * @param proposalId The id of the proposal to vote on * @param support The support value for the vote. 0=against, 1=for, 2=abstain * @return The number of votes cast */ function castVoteInternal(address voter, uint proposalId, uint8 support) internal returns (uint96) { require(state(proposalId) == ProposalState.Active, "GovernorBravo::castVoteInternal: voting is closed"); require(support <= 2, "GovernorBravo::castVoteInternal: invalid vote type"); Proposal storage proposal = proposals[proposalId]; Receipt storage receipt = proposal.receipts[voter]; require(receipt.hasVoted == false, "GovernorBravo::castVoteInternal: voter already voted"); // 2**96-1 is greater than total supply of bzrx 1.3b*1e18 thus guaranteeing it won't ever overflow uint96 votes = uint96(staking.votingBalanceOf(voter, proposalId)); if (support == 0) { proposal.againstVotes = add256(proposal.againstVotes, votes); } else if (support == 1) { proposal.forVotes = add256(proposal.forVotes, votes); } else if (support == 2) { proposal.abstainVotes = add256(proposal.abstainVotes, votes); } receipt.hasVoted = true; receipt.support = support; receipt.votes = votes; return votes; } /** * @notice Admin function for setting the voting delay * @param newVotingDelay new voting delay, in blocks */ function __setVotingDelay(uint newVotingDelay) external { require(msg.sender == admin, "GovernorBravo::__setVotingDelay: admin only"); require(newVotingDelay >= MIN_VOTING_DELAY && newVotingDelay <= MAX_VOTING_DELAY, "GovernorBravo::__setVotingDelay: invalid voting delay"); uint oldVotingDelay = votingDelay; votingDelay = newVotingDelay; emit VotingDelaySet(oldVotingDelay,votingDelay); } /** * @notice Admin function for setting the voting period * @param newVotingPeriod new voting period, in blocks */ function __setVotingPeriod(uint newVotingPeriod) external { require(msg.sender == admin, "GovernorBravo::__setVotingPeriod: admin only"); require(newVotingPeriod >= MIN_VOTING_PERIOD && newVotingPeriod <= MAX_VOTING_PERIOD, "GovernorBravo::__setVotingPeriod: invalid voting period"); uint oldVotingPeriod = votingPeriod; votingPeriod = newVotingPeriod; emit VotingPeriodSet(oldVotingPeriod, votingPeriod); } /** * @notice Admin function for setting the proposal threshold * @dev newProposalThreshold must be greater than the hardcoded min * @param newProposalThreshold new proposal threshold */ function __setProposalThreshold(uint newProposalThreshold) external { require(msg.sender == admin, "GovernorBravo::__setProposalThreshold: admin only"); require(newProposalThreshold >= MIN_PROPOSAL_THRESHOLD && newProposalThreshold <= MAX_PROPOSAL_THRESHOLD, "GovernorBravo::__setProposalThreshold: invalid proposal threshold"); uint oldProposalThreshold = proposalThreshold; proposalThreshold = newProposalThreshold; emit ProposalThresholdSet(oldProposalThreshold, proposalThreshold); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `__acceptLocalAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `__acceptLocalAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. */ function __setPendingLocalAdmin(address newPendingAdmin) external { // Check caller = admin require(msg.sender == admin, "GovernorBravo:__setPendingLocalAdmin: admin only"); // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin */ function __acceptLocalAdmin() external { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) require(msg.sender == pendingAdmin && msg.sender != address(0), "GovernorBravo:__acceptLocalAdmin: pending admin only"); // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); } function __changeGuardian(address guardian_) public { require(msg.sender == guardian, "GovernorBravo::__changeGuardian: sender must be gov guardian"); require(guardian_ != address(0), "GovernorBravo::__changeGuardian: not allowed"); guardian = guardian_; } function __acceptAdmin() public { require(msg.sender == guardian, "GovernorBravo::__acceptAdmin: sender must be gov guardian"); timelock.acceptAdmin(); } function __abdicate() public { require(msg.sender == guardian, "GovernorBravo::__abdicate: sender must be gov guardian"); guardian = address(0); } function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public { require(msg.sender == guardian, "GovernorBravo::__queueSetTimelockPendingAdmin: sender must be gov guardian"); timelock.queueTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta); } function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public { require(msg.sender == guardian, "GovernorBravo::__executeSetTimelockPendingAdmin: sender must be gov guardian"); timelock.executeTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta); } function add256(uint256 a, uint256 b) internal pure returns (uint) { uint c = a + b; require(c >= a, "addition overflow"); return c; } function sub256(uint256 a, uint256 b) internal pure returns (uint) { require(b <= a, "subtraction underflow"); return a - b; } function getChainIdInternal() internal pure returns (uint) { uint chainId; assembly { chainId := chainid() } return chainId; } } contract StakingVoteDelegatorState is StakingUpgradeable { // A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; } contract StakingVoteDelegatorConstants { address constant internal ZERO_ADDRESS = address(0); IStaking constant staking = IStaking(0xe95Ebce2B02Ee07dEF5Ed6B53289801F7Fc137A4); /// @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); } contract StakingVoteDelegator is StakingVoteDelegatorState, StakingVoteDelegatorConstants { using SafeMath for uint256; using SafeERC20 for IERC20; /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { if(delegatee == ZERO_ADDRESS){ delegatee = msg.sender; } 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) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes("STAKING")), 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), "Staking::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Staking::delegateBySig: invalid nonce"); require(now <= expiry, "Staking::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint256) { require(blockNumber < block.number, "Staking::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = staking.votingFromStakedBalanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function moveDelegates(address srcRep, address dstRep, uint256 amount) public { require(msg.sender == address(staking), "unauthorized"); _moveDelegates(srcRep, dstRep, amount); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub((amount > srcRepOld)? srcRepOld : amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal { uint32 blockNumber = safe32(block.number, "Staking::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } contract StakingV1_1 is StakingState, StakingConstants, PausableGuardian { using MathUtil for uint256; modifier onlyEOA() { require(msg.sender == tx.origin, "unauthorized"); _; } function getCurrentFeeTokens() external view returns (address[] memory) { return currentFeeTokens; } function _pendingSushiRewards(address _user) internal view returns (uint256) { uint256 pendingSushi = IMasterChefSushi(SUSHI_MASTERCHEF) .pendingSushi(BZRX_ETH_SUSHI_MASTERCHEF_PID, address(this)); uint256 totalSupply = _totalSupplyPerToken[LPToken]; return _pendingAltRewards( SUSHI, _user, balanceOfByAsset(LPToken, _user), totalSupply != 0 ? pendingSushi.mul(1e12).div(totalSupply) : 0 ); } function pendingCrvRewards(address account) external returns(uint256){ (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting) = _earned( account, bzrxPerTokenStored, stableCoinPerTokenStored ); (,stableCoinRewardsEarned) = _syncVesting( account, bzrxRewardsEarned, stableCoinRewardsEarned, bzrxRewardsVesting, stableCoinRewardsVesting ); return _pendingCrvRewards(account, stableCoinRewardsEarned); } function _pendingCrvRewards(address _user, uint256 stableCoinRewardsEarned) internal returns (uint256) { uint256 totalSupply = curve3PoolGauge.balanceOf(address(this)); uint256 pendingCrv = curve3PoolGauge.claimable_tokens(address(this)); return _pendingAltRewards( CRV, _user, stableCoinRewardsEarned, (totalSupply != 0) ? pendingCrv.mul(1e12).div(totalSupply) : 0 ); } function _pendingAltRewards(address token, address _user, uint256 userSupply, uint256 extraRewardsPerShare) internal view returns (uint256) { uint256 _altRewardsPerShare = altRewardsPerShare[token].add(extraRewardsPerShare); if (_altRewardsPerShare == 0) return 0; IStaking.AltRewardsUserInfo memory altRewardsUserInfo = userAltRewardsPerShare[_user][token]; return altRewardsUserInfo.pendingRewards.add( (_altRewardsPerShare.sub(altRewardsUserInfo.rewardsPerShare)).mul(userSupply).div(1e12) ); } function _depositToSushiMasterchef(uint256 amount) internal { uint256 sushiBalanceBefore = IERC20(SUSHI).balanceOf(address(this)); IMasterChefSushi(SUSHI_MASTERCHEF).deposit( BZRX_ETH_SUSHI_MASTERCHEF_PID, amount ); uint256 sushiRewards = IERC20(SUSHI).balanceOf(address(this)) - sushiBalanceBefore; if (sushiRewards != 0) { _addAltRewards(SUSHI, sushiRewards); } } function _withdrawFromSushiMasterchef(uint256 amount) internal { uint256 sushiBalanceBefore = IERC20(SUSHI).balanceOf(address(this)); IMasterChefSushi(SUSHI_MASTERCHEF).withdraw( BZRX_ETH_SUSHI_MASTERCHEF_PID, amount ); uint256 sushiRewards = IERC20(SUSHI).balanceOf(address(this)) - sushiBalanceBefore; if (sushiRewards != 0) { _addAltRewards(SUSHI, sushiRewards); } } function _depositTo3Pool( uint256 amount) internal { if(amount == 0) curve3PoolGauge.deposit(curve3Crv.balanceOf(address(this))); // Trigger claim rewards from curve pool uint256 crvBalanceBefore = IERC20(CRV).balanceOf(address(this)); curveMinter.mint(address(curve3PoolGauge)); uint256 crvBalanceAfter = IERC20(CRV).balanceOf(address(this)) - crvBalanceBefore; if(crvBalanceAfter != 0){ _addAltRewards(CRV, crvBalanceAfter); } } function _withdrawFrom3Pool(uint256 amount) internal { if(amount != 0) curve3PoolGauge.withdraw(amount); //Trigger claim rewards from curve pool uint256 crvBalanceBefore = IERC20(CRV).balanceOf(address(this)); curveMinter.mint(address(curve3PoolGauge)); uint256 crvBalanceAfter = IERC20(CRV).balanceOf(address(this)) - crvBalanceBefore; if(crvBalanceAfter != 0){ _addAltRewards(CRV, crvBalanceAfter); } } function stake( address[] memory tokens, uint256[] memory values ) public pausable updateRewards(msg.sender) { require(tokens.length == values.length, "count mismatch"); StakingVoteDelegator _voteDelegator = StakingVoteDelegator(voteDelegator); address currentDelegate = _voteDelegator.delegates(msg.sender); ProposalState memory _proposalState = _getProposalState(); uint256 votingBalanceBefore = _votingFromStakedBalanceOf(msg.sender, _proposalState, true); for (uint256 i = 0; i < tokens.length; i++) { address token = tokens[i]; require(token == BZRX || token == vBZRX || token == iBZRX || token == LPToken, "invalid token"); uint256 stakeAmount = values[i]; if (stakeAmount == 0) { continue; } uint256 pendingBefore = (token == LPToken) ? _pendingSushiRewards(msg.sender) : 0; _balancesPerToken[token][msg.sender] = _balancesPerToken[token][msg.sender].add(stakeAmount); _totalSupplyPerToken[token] = _totalSupplyPerToken[token].add(stakeAmount); IERC20(token).safeTransferFrom(msg.sender, address(this), stakeAmount); // Deposit to sushi masterchef if (token == LPToken) { _depositToSushiMasterchef( IERC20(LPToken).balanceOf(address(this)) ); userAltRewardsPerShare[msg.sender][SUSHI] = IStaking.AltRewardsUserInfo({ rewardsPerShare: altRewardsPerShare[SUSHI], pendingRewards: pendingBefore } ); } emit Stake( msg.sender, token, currentDelegate, stakeAmount ); } _voteDelegator.moveDelegates(ZERO_ADDRESS, currentDelegate, _votingFromStakedBalanceOf(msg.sender, _proposalState, true).sub(votingBalanceBefore)); } function unstake( address[] memory tokens, uint256[] memory values ) public pausable updateRewards(msg.sender) { require(tokens.length == values.length, "count mismatch"); StakingVoteDelegator _voteDelegator = StakingVoteDelegator(voteDelegator); address currentDelegate = _voteDelegator.delegates(msg.sender); ProposalState memory _proposalState = _getProposalState(); uint256 votingBalanceBefore = _votingFromStakedBalanceOf(msg.sender, _proposalState, true); for (uint256 i = 0; i < tokens.length; i++) { address token = tokens[i]; require(token == BZRX || token == vBZRX || token == iBZRX || token == LPToken || token == LPTokenOld, "invalid token"); uint256 unstakeAmount = values[i]; uint256 stakedAmount = _balancesPerToken[token][msg.sender]; if (unstakeAmount == 0 || stakedAmount == 0) { continue; } if (unstakeAmount > stakedAmount) { unstakeAmount = stakedAmount; } uint256 pendingBefore = (token == LPToken) ? _pendingSushiRewards(msg.sender) : 0; _balancesPerToken[token][msg.sender] = stakedAmount - unstakeAmount; // will not overflow _totalSupplyPerToken[token] = _totalSupplyPerToken[token] - unstakeAmount; // will not overflow if (token == BZRX && IERC20(BZRX).balanceOf(address(this)) < unstakeAmount) { // settle vested BZRX only if needed IVestingToken(vBZRX).claim(); } // Withdraw to sushi masterchef if (token == LPToken) { _withdrawFromSushiMasterchef(unstakeAmount); userAltRewardsPerShare[msg.sender][SUSHI] = IStaking.AltRewardsUserInfo({ rewardsPerShare: altRewardsPerShare[SUSHI], pendingRewards: pendingBefore } ); } IERC20(token).safeTransfer(msg.sender, unstakeAmount); emit Unstake( msg.sender, token, currentDelegate, unstakeAmount ); } _voteDelegator.moveDelegates(currentDelegate, ZERO_ADDRESS, votingBalanceBefore.sub(_votingFromStakedBalanceOf(msg.sender, _proposalState, true))); } function claim( bool restake) external pausable updateRewards(msg.sender) returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned) { return _claim(restake); } function claimAltRewards() external pausable returns (uint256 sushiRewardsEarned, uint256 crvRewardsEarned) { sushiRewardsEarned = _claimSushi(); crvRewardsEarned = _claimCrv(); if(sushiRewardsEarned != 0){ emit ClaimAltRewards(msg.sender, SUSHI, sushiRewardsEarned); } if(crvRewardsEarned != 0){ emit ClaimAltRewards(msg.sender, CRV, crvRewardsEarned); } } function claimBzrx() external pausable updateRewards(msg.sender) returns (uint256 bzrxRewardsEarned) { bzrxRewardsEarned = _claimBzrx(false); emit Claim( msg.sender, bzrxRewardsEarned, 0 ); } function claim3Crv() external pausable updateRewards(msg.sender) returns (uint256 stableCoinRewardsEarned) { stableCoinRewardsEarned = _claim3Crv(); emit Claim( msg.sender, 0, stableCoinRewardsEarned ); } function claimSushi() external pausable returns (uint256 sushiRewardsEarned) { sushiRewardsEarned = _claimSushi(); if(sushiRewardsEarned != 0){ emit ClaimAltRewards(msg.sender, SUSHI, sushiRewardsEarned); } } function claimCrv() external pausable returns (uint256 crvRewardsEarned) { crvRewardsEarned = _claimCrv(); if(crvRewardsEarned != 0){ emit ClaimAltRewards(msg.sender, CRV, crvRewardsEarned); } } function _claim( bool restake) internal returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned) { bzrxRewardsEarned = _claimBzrx(restake); stableCoinRewardsEarned = _claim3Crv(); emit Claim( msg.sender, bzrxRewardsEarned, stableCoinRewardsEarned ); } function _claimBzrx( bool restake) internal returns (uint256 bzrxRewardsEarned) { bzrxRewardsEarned = bzrxRewards[msg.sender]; if (bzrxRewardsEarned != 0) { bzrxRewards[msg.sender] = 0; if (restake) { _restakeBZRX( msg.sender, bzrxRewardsEarned ); } else { if (IERC20(BZRX).balanceOf(address(this)) < bzrxRewardsEarned) { // settle vested BZRX only if needed IVestingToken(vBZRX).claim(); } IERC20(BZRX).transfer(msg.sender, bzrxRewardsEarned); } } } function _claim3Crv() internal returns (uint256 stableCoinRewardsEarned) { stableCoinRewardsEarned = stableCoinRewards[msg.sender]; if (stableCoinRewardsEarned != 0) { uint256 pendingCrv = _pendingCrvRewards(msg.sender, stableCoinRewardsEarned); uint256 curve3CrvBalance = curve3Crv.balanceOf(address(this)); _withdrawFrom3Pool(stableCoinRewardsEarned); userAltRewardsPerShare[msg.sender][CRV] = IStaking.AltRewardsUserInfo({ rewardsPerShare: altRewardsPerShare[CRV], pendingRewards: pendingCrv } ); stableCoinRewards[msg.sender] = 0; curve3Crv.transfer(msg.sender, stableCoinRewardsEarned); } } function _claimSushi() internal returns (uint256) { address _user = msg.sender; uint256 lptUserSupply = balanceOfByAsset(LPToken, _user); //This will trigger claim rewards from sushi masterchef _depositToSushiMasterchef( IERC20(LPToken).balanceOf(address(this)) ); uint256 pendingSushi = _pendingAltRewards(SUSHI, _user, lptUserSupply, 0); userAltRewardsPerShare[_user][SUSHI] = IStaking.AltRewardsUserInfo({ rewardsPerShare: altRewardsPerShare[SUSHI], pendingRewards: 0 } ); if (pendingSushi != 0) { IERC20(SUSHI).safeTransfer(_user, pendingSushi); } return pendingSushi; } function _claimCrv() internal returns (uint256) { address _user = msg.sender; _depositTo3Pool(0); (,uint256 stableCoinRewardsEarned,,) = _earned(_user, bzrxPerTokenStored, stableCoinPerTokenStored); uint256 pendingCrv = _pendingCrvRewards(_user, stableCoinRewardsEarned); userAltRewardsPerShare[_user][CRV] = IStaking.AltRewardsUserInfo({ rewardsPerShare: altRewardsPerShare[CRV], pendingRewards: 0 } ); if (pendingCrv != 0) { IERC20(CRV).safeTransfer(_user, pendingCrv); } return pendingCrv; } function _restakeBZRX( address account, uint256 amount) internal { StakingVoteDelegator _voteDelegator = StakingVoteDelegator(voteDelegator); address currentDelegate = _voteDelegator.delegates(msg.sender); ProposalState memory _proposalState = _getProposalState(); uint256 votingBalanceBefore = _votingFromStakedBalanceOf(msg.sender, _proposalState, true); _balancesPerToken[BZRX][account] = _balancesPerToken[BZRX][account] .add(amount); _totalSupplyPerToken[BZRX] = _totalSupplyPerToken[BZRX] .add(amount); emit Stake( account, BZRX, currentDelegate, amount ); _voteDelegator.moveDelegates(ZERO_ADDRESS, currentDelegate, _votingFromStakedBalanceOf(msg.sender, _proposalState, true).sub(votingBalanceBefore)); } function exit() public // unstake() does check pausable { address[] memory tokens = new address[](4); uint256[] memory values = new uint256[](4); tokens[0] = iBZRX; tokens[1] = LPToken; tokens[2] = vBZRX; tokens[3] = BZRX; values[0] = uint256(-1); values[1] = uint256(-1); values[2] = uint256(-1); values[3] = uint256(-1); unstake(tokens, values); // calls updateRewards _claim(false); } modifier updateRewards(address account) { uint256 _bzrxPerTokenStored = bzrxPerTokenStored; uint256 _stableCoinPerTokenStored = stableCoinPerTokenStored; (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting) = _earned( account, _bzrxPerTokenStored, _stableCoinPerTokenStored ); bzrxRewardsPerTokenPaid[account] = _bzrxPerTokenStored; stableCoinRewardsPerTokenPaid[account] = _stableCoinPerTokenStored; // vesting amounts get updated before sync bzrxVesting[account] = bzrxRewardsVesting; stableCoinVesting[account] = stableCoinRewardsVesting; (bzrxRewards[account], stableCoinRewards[account]) = _syncVesting( account, bzrxRewardsEarned, stableCoinRewardsEarned, bzrxRewardsVesting, stableCoinRewardsVesting ); vestingLastSync[account] = block.timestamp; _; } function earned( address account) external view returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting, uint256 sushiRewardsEarned) { (bzrxRewardsEarned, stableCoinRewardsEarned, bzrxRewardsVesting, stableCoinRewardsVesting) = _earned( account, bzrxPerTokenStored, stableCoinPerTokenStored ); (bzrxRewardsEarned, stableCoinRewardsEarned) = _syncVesting( account, bzrxRewardsEarned, stableCoinRewardsEarned, bzrxRewardsVesting, stableCoinRewardsVesting ); // discount vesting amounts for vesting time uint256 multiplier = vestedBalanceForAmount( 1e36, 0, block.timestamp ); bzrxRewardsVesting = bzrxRewardsVesting .sub(bzrxRewardsVesting .mul(multiplier) .div(1e36) ); stableCoinRewardsVesting = stableCoinRewardsVesting .sub(stableCoinRewardsVesting .mul(multiplier) .div(1e36) ); uint256 pendingSushi = IMasterChefSushi(SUSHI_MASTERCHEF) .pendingSushi(BZRX_ETH_SUSHI_MASTERCHEF_PID, address(this)); sushiRewardsEarned = _pendingAltRewards( SUSHI, account, balanceOfByAsset(LPToken, account), (_totalSupplyPerToken[LPToken] != 0) ? pendingSushi.mul(1e12).div(_totalSupplyPerToken[LPToken]) : 0 ); } function _earned( address account, uint256 _bzrxPerToken, uint256 _stableCoinPerToken) internal view returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting) { uint256 bzrxPerTokenUnpaid = _bzrxPerToken.sub(bzrxRewardsPerTokenPaid[account]); uint256 stableCoinPerTokenUnpaid = _stableCoinPerToken.sub(stableCoinRewardsPerTokenPaid[account]); bzrxRewardsEarned = bzrxRewards[account]; stableCoinRewardsEarned = stableCoinRewards[account]; bzrxRewardsVesting = bzrxVesting[account]; stableCoinRewardsVesting = stableCoinVesting[account]; if (bzrxPerTokenUnpaid != 0 || stableCoinPerTokenUnpaid != 0) { uint256 value; uint256 multiplier; uint256 lastSync; (uint256 vestedBalance, uint256 vestingBalance) = balanceOfStored(account); value = vestedBalance .mul(bzrxPerTokenUnpaid); value /= 1e36; bzrxRewardsEarned = value .add(bzrxRewardsEarned); value = vestedBalance .mul(stableCoinPerTokenUnpaid); value /= 1e36; stableCoinRewardsEarned = value .add(stableCoinRewardsEarned); if (vestingBalance != 0 && bzrxPerTokenUnpaid != 0) { // add new vesting amount for BZRX value = vestingBalance .mul(bzrxPerTokenUnpaid); value /= 1e36; bzrxRewardsVesting = bzrxRewardsVesting .add(value); // true up earned amount to vBZRX vesting schedule lastSync = vestingLastSync[account]; multiplier = vestedBalanceForAmount( 1e36, 0, lastSync ); value = value .mul(multiplier); value /= 1e36; bzrxRewardsEarned = bzrxRewardsEarned .add(value); } if (vestingBalance != 0 && stableCoinPerTokenUnpaid != 0) { // add new vesting amount for 3crv value = vestingBalance .mul(stableCoinPerTokenUnpaid); value /= 1e36; stableCoinRewardsVesting = stableCoinRewardsVesting .add(value); // true up earned amount to vBZRX vesting schedule if (lastSync == 0) { lastSync = vestingLastSync[account]; multiplier = vestedBalanceForAmount( 1e36, 0, lastSync ); } value = value .mul(multiplier); value /= 1e36; stableCoinRewardsEarned = stableCoinRewardsEarned .add(value); } } } function _syncVesting( address account, uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting) internal view returns (uint256, uint256) { uint256 lastVestingSync = vestingLastSync[account]; if (lastVestingSync != block.timestamp) { uint256 rewardsVested; uint256 multiplier = vestedBalanceForAmount( 1e36, lastVestingSync, block.timestamp ); if (bzrxRewardsVesting != 0) { rewardsVested = bzrxRewardsVesting .mul(multiplier) .div(1e36); bzrxRewardsEarned += rewardsVested; } if (stableCoinRewardsVesting != 0) { rewardsVested = stableCoinRewardsVesting .mul(multiplier) .div(1e36); stableCoinRewardsEarned += rewardsVested; } uint256 vBZRXBalance = _balancesPerToken[vBZRX][account]; if (vBZRXBalance != 0) { // add vested BZRX to rewards balance rewardsVested = vBZRXBalance .mul(multiplier) .div(1e36); bzrxRewardsEarned += rewardsVested; } } return (bzrxRewardsEarned, stableCoinRewardsEarned); } // note: anyone can contribute rewards to the contract function addDirectRewards( address[] calldata accounts, uint256[] calldata bzrxAmounts, uint256[] calldata stableCoinAmounts) external pausable returns (uint256 bzrxTotal, uint256 stableCoinTotal) { require(accounts.length == bzrxAmounts.length && accounts.length == stableCoinAmounts.length, "count mismatch"); for (uint256 i = 0; i < accounts.length; i++) { bzrxRewards[accounts[i]] = bzrxRewards[accounts[i]].add(bzrxAmounts[i]); bzrxTotal = bzrxTotal.add(bzrxAmounts[i]); stableCoinRewards[accounts[i]] = stableCoinRewards[accounts[i]].add(stableCoinAmounts[i]); stableCoinTotal = stableCoinTotal.add(stableCoinAmounts[i]); } if (bzrxTotal != 0) { IERC20(BZRX).transferFrom(msg.sender, address(this), bzrxTotal); } if (stableCoinTotal != 0) { curve3Crv.transferFrom(msg.sender, address(this), stableCoinTotal); _depositTo3Pool(stableCoinTotal); } } // note: anyone can contribute rewards to the contract function addRewards( uint256 newBZRX, uint256 newStableCoin) external pausable { if (newBZRX != 0 || newStableCoin != 0) { _addRewards(newBZRX, newStableCoin); if (newBZRX != 0) { IERC20(BZRX).transferFrom(msg.sender, address(this), newBZRX); } if (newStableCoin != 0) { curve3Crv.transferFrom(msg.sender, address(this), newStableCoin); _depositTo3Pool(newStableCoin); } } } function _addRewards( uint256 newBZRX, uint256 newStableCoin) internal { (vBZRXWeightStored, iBZRXWeightStored, LPTokenWeightStored) = getVariableWeights(); uint256 totalTokens = totalSupplyStored(); require(totalTokens != 0, "nothing staked"); bzrxPerTokenStored = newBZRX .mul(1e36) .div(totalTokens) .add(bzrxPerTokenStored); stableCoinPerTokenStored = newStableCoin .mul(1e36) .div(totalTokens) .add(stableCoinPerTokenStored); lastRewardsAddTime = block.timestamp; emit AddRewards( msg.sender, newBZRX, newStableCoin ); } function addAltRewards(address token, uint256 amount) public { if (amount != 0) { _addAltRewards(token, amount); IERC20(token).transferFrom(msg.sender, address(this), amount); } } function _addAltRewards(address token, uint256 amount) internal { address poolAddress = token == SUSHI ? LPToken : token; uint256 totalSupply = (token == CRV) ? curve3PoolGauge.balanceOf(address(this)) :_totalSupplyPerToken[poolAddress]; require(totalSupply != 0, "no deposits"); altRewardsPerShare[token] = altRewardsPerShare[token] .add(amount.mul(1e12).div(totalSupply)); emit AddAltRewards(msg.sender, token, amount); } function getVariableWeights() public view returns (uint256 vBZRXWeight, uint256 iBZRXWeight, uint256 LPTokenWeight) { uint256 totalVested = vestedBalanceForAmount( _startingVBZRXBalance, 0, block.timestamp ); vBZRXWeight = SafeMath.mul(_startingVBZRXBalance - totalVested, 1e18) // overflow not possible .div(_startingVBZRXBalance); iBZRXWeight = _calcIBZRXWeight(); uint256 lpTokenSupply = _totalSupplyPerToken[LPToken]; if (lpTokenSupply != 0) { // staked LP tokens are assumed to represent the total unstaked supply (circulated supply - staked BZRX) uint256 normalizedLPTokenSupply = initialCirculatingSupply + totalVested - _totalSupplyPerToken[BZRX]; LPTokenWeight = normalizedLPTokenSupply .mul(1e18) .div(lpTokenSupply); } } function _calcIBZRXWeight() internal view returns (uint256) { return IERC20(BZRX).balanceOf(iBZRX) .mul(1e50) .div(IERC20(iBZRX).totalSupply()); } function balanceOfByAsset( address token, address account) public view returns (uint256 balance) { balance = _balancesPerToken[token][account]; } function balanceOfByAssets( address account) external view returns ( uint256 bzrxBalance, uint256 iBZRXBalance, uint256 vBZRXBalance, uint256 LPTokenBalance, uint256 LPTokenBalanceOld ) { return ( balanceOfByAsset(BZRX, account), balanceOfByAsset(iBZRX, account), balanceOfByAsset(vBZRX, account), balanceOfByAsset(LPToken, account), balanceOfByAsset(LPTokenOld, account) ); } function balanceOfStored( address account) public view returns (uint256 vestedBalance, uint256 vestingBalance) { uint256 balance = _balancesPerToken[vBZRX][account]; if (balance != 0) { vestingBalance = balance .mul(vBZRXWeightStored) .div(1e18); } vestedBalance = _balancesPerToken[BZRX][account]; balance = _balancesPerToken[iBZRX][account]; if (balance != 0) { vestedBalance = balance .mul(iBZRXWeightStored) .div(1e50) .add(vestedBalance); } balance = _balancesPerToken[LPToken][account]; if (balance != 0) { vestedBalance = balance .mul(LPTokenWeightStored) .div(1e18) .add(vestedBalance); } } function totalSupplyByAsset( address token) external view returns (uint256) { return _totalSupplyPerToken[token]; } function totalSupplyStored() public view returns (uint256 supply) { supply = _totalSupplyPerToken[vBZRX] .mul(vBZRXWeightStored) .div(1e18); supply = _totalSupplyPerToken[BZRX] .add(supply); supply = _totalSupplyPerToken[iBZRX] .mul(iBZRXWeightStored) .div(1e50) .add(supply); supply = _totalSupplyPerToken[LPToken] .mul(LPTokenWeightStored) .div(1e18) .add(supply); } function vestedBalanceForAmount( uint256 tokenBalance, uint256 lastUpdate, uint256 vestingEndTime) public view returns (uint256 vested) { vestingEndTime = vestingEndTime.min256(block.timestamp); if (vestingEndTime > lastUpdate) { if (vestingEndTime <= vestingCliffTimestamp || lastUpdate >= vestingEndTimestamp) { // time cannot be before vesting starts // OR all vested token has already been claimed return 0; } if (lastUpdate < vestingCliffTimestamp) { // vesting starts at the cliff timestamp lastUpdate = vestingCliffTimestamp; } if (vestingEndTime > vestingEndTimestamp) { // vesting ends at the end timestamp vestingEndTime = vestingEndTimestamp; } uint256 timeSinceClaim = vestingEndTime.sub(lastUpdate); vested = tokenBalance.mul(timeSinceClaim) / vestingDurationAfterCliff; // will never divide by 0 } } function votingFromStakedBalanceOf( address account) external view returns (uint256 totalVotes) { return _votingFromStakedBalanceOf(account, _getProposalState(), true); } function votingBalanceOf( address account, uint256 proposalId) external view returns (uint256 totalVotes) { (,,,uint256 startBlock,,,,,,) = GovernorBravoDelegateStorageV1(governor).proposals(proposalId); if (startBlock == 0) return 0; return _votingBalanceOf(account, _proposalState[proposalId], startBlock - 1); } function votingBalanceOfNow( address account) external view returns (uint256 totalVotes) { return _votingBalanceOf(account, _getProposalState(), block.number - 1); } function _setProposalVals( address account, uint256 proposalId) public returns (uint256) { require(msg.sender == governor, "unauthorized"); require(_proposalState[proposalId].proposalTime == 0, "proposal exists"); ProposalState memory newProposal = _getProposalState(); _proposalState[proposalId] = newProposal; return _votingBalanceOf(account, newProposal, block.number - 1); } function _getProposalState() internal view returns (ProposalState memory) { return ProposalState({ proposalTime: block.timestamp - 1, iBZRXWeight: _calcIBZRXWeight(), lpBZRXBalance: 0, // IERC20(BZRX).balanceOf(LPToken), lpTotalSupply: 0 //IERC20(LPToken).totalSupply() }); } // Voting balance not including delegated votes function _votingFromStakedBalanceOf( address account, ProposalState memory proposal, bool skipVestingLastSyncCheck) internal view returns (uint256 totalVotes) { uint256 _vestingLastSync = vestingLastSync[account]; if (proposal.proposalTime == 0 || (!skipVestingLastSyncCheck && _vestingLastSync > proposal.proposalTime - 1)) { return 0; } // user is attributed a staked balance of vested BZRX, from their last update to the present totalVotes = vestedBalanceForAmount( _balancesPerToken[vBZRX][account], _vestingLastSync, proposal.proposalTime ); totalVotes = _balancesPerToken[BZRX][account] .add(bzrxRewards[account]) // unclaimed BZRX rewards count as votes .add(totalVotes); totalVotes = _balancesPerToken[iBZRX][account] .mul(proposal.iBZRXWeight) .div(1e50) .add(totalVotes); } // Voting balance including delegated votes function _votingBalanceOf( address account, ProposalState memory proposal, uint blocknumber) internal view returns (uint256 totalVotes) { StakingVoteDelegator _voteDelegator = StakingVoteDelegator(voteDelegator); address _delegate = _voteDelegator.delegates(account); if(_delegate == ZERO_ADDRESS) { // has not delegated yet return _voteDelegator.getPriorVotes(account, blocknumber).add(_votingFromStakedBalanceOf(account, proposal, false)); } return _voteDelegator.getPriorVotes(account, blocknumber); } // OnlyOwner functions function updateSettings( address settingsTarget, bytes memory callData) public onlyOwner returns(bytes memory) { (bool result,) = settingsTarget.delegatecall(callData); assembly { let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) if eq(result, 0) { revert(ptr, size) } return(ptr, size) } } }
Info of each user that stakes LP tokens.
interface IStaking { function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function userInfo(uint256, address) external view returns (UserInfo memory); function pendingSushi(uint256 _pid, address _user) external view returns (uint256); } struct ProposalState { uint256 proposalTime; uint256 iBZRXWeight; uint256 lpBZRXBalance; uint256 lpTotalSupply; } struct AltRewardsUserInfo { uint256 rewardsPerShare; uint256 pendingRewards; } }
260,243
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "../../interfaces/decentraland/IDecentralandFacet.sol"; import "../../interfaces/decentraland/IDecentralandRegistry.sol"; import "../../libraries/LibOwnership.sol"; import "../../libraries/marketplace/LibRent.sol"; import "../../libraries/marketplace/LibDecentraland.sol"; contract DecentralandFacet is IDecentralandFacet { /// @notice Rents Decentraland Estate/LAND. /// @param _assetId The target asset /// @param _period The target period of the rental /// @param _maxRentStart The maximum rent start allowed for the given rent /// @param _operator The target operator, which will be set as operator once the rent is active /// @param _paymentToken The current payment token for the asset /// @param _amount The target amount to be paid for the rent function rentDecentraland( uint256 _assetId, uint256 _period, uint256 _maxRentStart, address _operator, address _paymentToken, uint256 _amount ) external payable { require(_operator != address(0), "_operator must not be 0x0"); (uint256 rentId, bool rentStartsNow) = LibRent.rent( LibRent.RentParams({ _assetId: _assetId, _period: _period, _maxRentStart: _maxRentStart, _paymentToken: _paymentToken, _amount: _amount }) ); LibDecentraland.setOperator(_assetId, rentId, _operator); emit UpdateOperator(_assetId, rentId, _operator); if (rentStartsNow) { updateState(_assetId, rentId); } } /// @notice Updates the corresponding Estate/LAND operator from the given rent. /// When the rent becomes active (the current block.timestamp is between the rent's start and end), /// this function should be executed to set the provided rent operator to the Estate/LAND scene operator. /// @param _assetId The target asset which will map to its corresponding Estate/LAND /// @param _rentId The target rent function updateState(uint256 _assetId, uint256 _rentId) public { LibMarketplace.MarketplaceStorage storage ms = LibMarketplace .marketplaceStorage(); require(LibERC721.exists(_assetId), "_assetId not found"); LibMarketplace.Rent memory rent = ms.rents[_assetId][_rentId]; require( block.timestamp >= rent.start, "block timestamp less than rent start" ); require( block.timestamp < rent.end, "block timestamp more than or equal to rent end" ); LibMarketplace.Asset memory asset = ms.assets[_assetId]; address operator = LibDecentraland.decentralandStorage().operators[ _assetId ][_rentId]; IDecentralandRegistry(asset.metaverseRegistry).setUpdateOperator( asset.metaverseAssetId, operator ); emit UpdateState(_assetId, _rentId, operator); } /// @notice Updates the corresponding Estate/LAND operator with the administrative operator /// @param _assetId The target asset which will map to its corresponding Estate/LAND function updateAdministrativeState(uint256 _assetId) external { LibMarketplace.MarketplaceStorage storage ms = LibMarketplace .marketplaceStorage(); require(LibERC721.exists(_assetId), "_assetId not found"); LibMarketplace.Asset memory asset = ms.assets[_assetId]; require( block.timestamp > ms.rents[_assetId][asset.totalRents].end, "_assetId has an active rent" ); address operator = LibDecentraland .decentralandStorage() .administrativeOperator; IDecentralandRegistry(asset.metaverseRegistry).setUpdateOperator( asset.metaverseAssetId, operator ); emit UpdateAdministrativeState(_assetId, operator); } /// @notice Updates the operator for the given rent of an asset /// @param _assetId The target asset /// @param _rentId The target rent for the asset /// @param _newOperator The to-be-set new operator function updateOperator( uint256 _assetId, uint256 _rentId, address _newOperator ) external { require(_newOperator != address(0), "_newOperator must not be 0x0"); LibMarketplace.MarketplaceStorage storage ms = LibMarketplace .marketplaceStorage(); require(LibERC721.exists(_assetId), "_assetId not found"); require( msg.sender == ms.rents[_assetId][_rentId].renter, "caller is not renter" ); LibDecentraland.setOperator(_assetId, _rentId, _newOperator); emit UpdateOperator(_assetId, _rentId, _newOperator); } /// @notice Updates the administrative operator /// @param _administrativeOperator The to-be-set administrative operator function updateAdministrativeOperator(address _administrativeOperator) external { require( _administrativeOperator != address(0), "_administrativeOperator must not be 0x0" ); LibOwnership.enforceIsContractOwner(); LibDecentraland.setAdministrativeOperator(_administrativeOperator); emit UpdateAdministrativeOperator(_administrativeOperator); } /// @notice Gets the administrative operator function administrativeOperator() external view returns (address) { return LibDecentraland.administrativeOperator(); } /// @notice Gets the operator of the rent for the an asset /// @param _assetId The target asset /// @param _rentId The target rentId function operatorFor(uint256 _assetId, uint256 _rentId) external view returns (address) { return LibDecentraland.operatorFor(_assetId, _rentId); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "../IRentable.sol"; interface IDecentralandFacet is IRentable { event UpdateState( uint256 indexed _assetId, uint256 _rentId, address indexed _operator ); event UpdateAdministrativeState( uint256 indexed _assetId, address indexed _operator ); event UpdateOperator( uint256 indexed _assetId, uint256 _rentId, address indexed _operator ); event UpdateAdministrativeOperator(address _administrativeOperator); /// @notice Rents Decentraland Estate/LAND. /// @param _assetId The target asset /// @param _period The target period of the rental /// @param _maxRentStart The maximum rent start allowed for the given rent /// @param _operator The target operator, which will be set as operator once the rent is active /// @param _paymentToken The current payment token for the asset /// @param _amount The target amount to be paid for the rent function rentDecentraland( uint256 _assetId, uint256 _period, uint256 _maxRentStart, address _operator, address _paymentToken, uint256 _amount ) external payable; /// @notice Updates the corresponding Estate/LAND operator from the given rent. /// When the rent becomes active (the current block.timestamp is between the rent's start and end), /// this function should be executed to set the provided rent operator to the Estate/LAND scene operator. /// @param _assetId The target asset which will map to its corresponding Estate/LAND /// @param _rentId The target rent function updateState(uint256 _assetId, uint256 _rentId) external; /// @notice Updates the corresponding Estate/LAND operator with the administrative operator /// @param _assetId The target asset which will map to its corresponding Estate/LAND function updateAdministrativeState(uint256 _assetId) external; /// @notice Updates the operator for the given rent of an asset /// @param _assetId The target asset /// @param _rentId The target rent for the asset /// @param _newOperator The to-be-set new operator function updateOperator( uint256 _assetId, uint256 _rentId, address _newOperator ) external; /// @notice Updates the administrative operator /// @param _administrativeOperator The to-be-set administrative operator function updateAdministrativeOperator(address _administrativeOperator) external; /// @notice Gets the administrative operator function administrativeOperator() external view returns (address); /// @notice Gets the operator of the rent for the an asset /// @param _assetId The target asset /// @param _rentId The target rentId function operatorFor(uint256 _assetId, uint256 _rentId) external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; interface IDecentralandRegistry { /// @notice Set Estate/LAND updateOperator /// @param _assetId - Estate/LAND id /// @param _operator - the to-be-set as operator function setUpdateOperator(uint256 _assetId, address _operator) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "./LibDiamond.sol"; library LibOwnership { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function setContractOwner(address _newOwner) internal { LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage(); address previousOwner = ds.contractOwner; require(previousOwner != _newOwner, "Previous owner and new owner must be different"); ds.contractOwner = _newOwner; emit OwnershipTransferred(previousOwner, _newOwner); } function contractOwner() internal view returns (address contractOwner_) { contractOwner_ = LibDiamond.diamondStorage().contractOwner; } function enforceIsContractOwner() view internal { require(msg.sender == LibDiamond.diamondStorage().contractOwner, "Must be contract owner"); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "../LibERC721.sol"; import "../LibFee.sol"; import "../LibTransfer.sol"; import "../marketplace/LibMarketplace.sol"; library LibRent { using SafeERC20 for IERC20; address constant ETHEREUM_PAYMENT_TOKEN = address(1); event Rent( uint256 indexed _assetId, uint256 _rentId, address indexed _renter, uint256 _start, uint256 _end, address indexed _paymentToken, uint256 _rent, uint256 _protocolFee ); struct RentParams { uint256 _assetId; uint256 _period; uint256 _maxRentStart; address _paymentToken; uint256 _amount; } /// @dev Rents asset for a given period (in seconds) /// Rent is added to the queue of pending rents. /// Rent start will begin from the last rented timestamp. /// If no active rents are found, rents starts from the current timestamp. function rent(RentParams memory rentParams) internal returns (uint256, bool) { LibMarketplace.MarketplaceStorage storage ms = LibMarketplace .marketplaceStorage(); require(LibERC721.exists(rentParams._assetId), "_assetId not found"); LibMarketplace.Asset memory asset = ms.assets[rentParams._assetId]; require( asset.status == LibMarketplace.AssetStatus.Listed, "_assetId not listed" ); require( rentParams._period >= asset.minPeriod, "_period less than minPeriod" ); require( rentParams._period <= asset.maxPeriod, "_period more than maxPeriod" ); require( rentParams._paymentToken == asset.paymentToken, "invalid _paymentToken" ); bool rentStartsNow = true; uint256 rentStart = block.timestamp; uint256 lastRentEnd = ms .rents[rentParams._assetId][asset.totalRents].end; if (lastRentEnd > rentStart) { rentStart = lastRentEnd; rentStartsNow = false; } require( rentStart <= rentParams._maxRentStart, "rent start exceeds maxRentStart" ); uint256 rentEnd = rentStart + rentParams._period; require( block.timestamp + asset.maxFutureTime >= rentEnd, "rent more than current maxFutureTime" ); uint256 rentPayment = rentParams._period * asset.pricePerSecond; require(rentParams._amount == rentPayment, "invalid _amount"); if (asset.paymentToken == ETHEREUM_PAYMENT_TOKEN) { require(msg.value == rentPayment, "invalid msg.value"); } else { require(msg.value == 0, "invalid token msg.value"); } (uint256 rentFee, uint256 protocolFee) = LibFee.distributeFees( rentParams._assetId, asset.paymentToken, rentPayment ); uint256 rentId = LibMarketplace.addRent( rentParams._assetId, msg.sender, rentStart, rentEnd ); if (asset.paymentToken != ETHEREUM_PAYMENT_TOKEN) { LibTransfer.safeTransferFrom( asset.paymentToken, msg.sender, address(this), rentPayment ); } emit Rent( rentParams._assetId, rentId, msg.sender, rentStart, rentEnd, asset.paymentToken, rentFee, protocolFee ); return (rentId, rentStartsNow); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; library LibDecentraland { bytes32 constant DECENTRALAND_MARKETPLACE_STORAGE_POSITION = keccak256("com.enterdao.landworks.marketplace.decentraland"); struct DecentralandStorage { // Administrative Operator to Estate/LANDs, when no rents are active address administrativeOperator; // Stores the operators for each asset's rentals mapping(uint256 => mapping(uint256 => address)) operators; } function decentralandStorage() internal pure returns (DecentralandStorage storage ds) { bytes32 position = DECENTRALAND_MARKETPLACE_STORAGE_POSITION; assembly { ds.slot := position } } function setOperator( uint256 _assetId, uint256 _rentId, address _operator ) internal { decentralandStorage().operators[_assetId][_rentId] = _operator; } function setAdministrativeOperator(address _administrativeOperator) internal { decentralandStorage().administrativeOperator = _administrativeOperator; } function administrativeOperator() internal view returns (address) { return decentralandStorage().administrativeOperator; } function operatorFor(uint256 _assetId, uint256 _rentId) internal view returns (address) { return decentralandStorage().operators[_assetId][_rentId]; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; interface IRentable { /// @notice Emitted once a given asset has been rented event Rent( uint256 indexed _assetId, uint256 _rentId, address indexed _renter, uint256 _start, uint256 _end, address indexed _paymentToken, uint256 _rent, uint256 _protocolFee ); } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * EIP-2535 Diamond Standard: https://eips.ethereum.org/EIPS/eip-2535 /******************************************************************************/ import { IDiamondCut } from "../interfaces/IDiamondCut.sol"; library LibDiamond { bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("com.enterdao.landworks.storage"); struct FacetAddressAndPosition { address facetAddress; uint96 functionSelectorPosition; // position in facetFunctionSelectors.functionSelectors array } struct FacetFunctionSelectors { bytes4[] functionSelectors; uint256 facetAddressPosition; // position of facetAddress in facetAddresses array } struct DiamondStorage { // maps function selector to the facet address and // the position of the selector in the facetFunctionSelectors.selectors array mapping(bytes4 => FacetAddressAndPosition) selectorToFacetAndPosition; // maps facet addresses to function selectors mapping(address => FacetFunctionSelectors) facetFunctionSelectors; // facet addresses address[] facetAddresses; // Used to query if a contract implements an interface. // Used to implement ERC-165. mapping(bytes4 => bool) supportedInterfaces; // owner of the contract address contractOwner; } function diamondStorage() internal pure returns (DiamondStorage storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION; assembly { ds.slot := position } } event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata); // Internal function version of diamondCut function diamondCut( IDiamondCut.FacetCut[] memory _diamondCut, address _init, bytes memory _calldata ) internal { for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) { IDiamondCut.FacetCutAction action = _diamondCut[facetIndex].action; if (action == IDiamondCut.FacetCutAction.Add) { addFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors); } else if (action == IDiamondCut.FacetCutAction.Replace) { replaceFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors); } else if (action == IDiamondCut.FacetCutAction.Remove) { removeFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors); } else { revert("LibDiamondCut: Incorrect FacetCutAction"); } } emit DiamondCut(_diamondCut, _init, _calldata); initializeDiamondCut(_init, _calldata); } function addFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal { require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut"); DiamondStorage storage ds = diamondStorage(); require(_facetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)"); uint96 selectorPosition = uint96(ds.facetFunctionSelectors[_facetAddress].functionSelectors.length); // add new facet address if it does not exist if (selectorPosition == 0) { addFacet(ds, _facetAddress); } for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) { bytes4 selector = _functionSelectors[selectorIndex]; address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress; require(oldFacetAddress == address(0), "LibDiamondCut: Can't add function that already exists"); addFunction(ds, selector, selectorPosition, _facetAddress); selectorPosition++; } } function replaceFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal { require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut"); DiamondStorage storage ds = diamondStorage(); require(_facetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)"); uint96 selectorPosition = uint96(ds.facetFunctionSelectors[_facetAddress].functionSelectors.length); // add new facet address if it does not exist if (selectorPosition == 0) { addFacet(ds, _facetAddress); } for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) { bytes4 selector = _functionSelectors[selectorIndex]; address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress; require(oldFacetAddress != _facetAddress, "LibDiamondCut: Can't replace function with same function"); removeFunction(ds, oldFacetAddress, selector); addFunction(ds, selector, selectorPosition, _facetAddress); selectorPosition++; } } function removeFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal { require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut"); DiamondStorage storage ds = diamondStorage(); // if function does not exist then do nothing and return require(_facetAddress == address(0), "LibDiamondCut: Remove facet address must be address(0)"); for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) { bytes4 selector = _functionSelectors[selectorIndex]; address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress; removeFunction(ds, oldFacetAddress, selector); } } function addFacet(DiamondStorage storage ds, address _facetAddress) internal { enforceHasContractCode(_facetAddress, "LibDiamondCut: New facet has no code"); ds.facetFunctionSelectors[_facetAddress].facetAddressPosition = ds.facetAddresses.length; ds.facetAddresses.push(_facetAddress); } function addFunction(DiamondStorage storage ds, bytes4 _selector, uint96 _selectorPosition, address _facetAddress) internal { ds.selectorToFacetAndPosition[_selector].functionSelectorPosition = _selectorPosition; ds.facetFunctionSelectors[_facetAddress].functionSelectors.push(_selector); ds.selectorToFacetAndPosition[_selector].facetAddress = _facetAddress; } function removeFunction(DiamondStorage storage ds, address _facetAddress, bytes4 _selector) internal { require(_facetAddress != address(0), "LibDiamondCut: Can't remove function that doesn't exist"); // an immutable function is a function defined directly in a diamond require(_facetAddress != address(this), "LibDiamondCut: Can't remove immutable function"); // replace selector with last selector, then delete last selector uint256 selectorPosition = ds.selectorToFacetAndPosition[_selector].functionSelectorPosition; uint256 lastSelectorPosition = ds.facetFunctionSelectors[_facetAddress].functionSelectors.length - 1; // if not the same then replace _selector with lastSelector if (selectorPosition != lastSelectorPosition) { bytes4 lastSelector = ds.facetFunctionSelectors[_facetAddress].functionSelectors[lastSelectorPosition]; ds.facetFunctionSelectors[_facetAddress].functionSelectors[selectorPosition] = lastSelector; ds.selectorToFacetAndPosition[lastSelector].functionSelectorPosition = uint96(selectorPosition); } // delete the last selector ds.facetFunctionSelectors[_facetAddress].functionSelectors.pop(); delete ds.selectorToFacetAndPosition[_selector]; // if no more selectors for facet address then delete the facet address if (lastSelectorPosition == 0) { // replace facet address with last facet address and delete last facet address uint256 lastFacetAddressPosition = ds.facetAddresses.length - 1; uint256 facetAddressPosition = ds.facetFunctionSelectors[_facetAddress].facetAddressPosition; if (facetAddressPosition != lastFacetAddressPosition) { address lastFacetAddress = ds.facetAddresses[lastFacetAddressPosition]; ds.facetAddresses[facetAddressPosition] = lastFacetAddress; ds.facetFunctionSelectors[lastFacetAddress].facetAddressPosition = facetAddressPosition; } ds.facetAddresses.pop(); delete ds.facetFunctionSelectors[_facetAddress].facetAddressPosition; } } function initializeDiamondCut(address _init, bytes memory _calldata) internal { if (_init == address(0)) { require(_calldata.length == 0, "LibDiamondCut: _init is address(0) but_calldata is not empty"); } else { require(_calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)"); if (_init != address(this)) { enforceHasContractCode(_init, "LibDiamondCut: _init address has no code"); } (bool success, bytes memory error) = _init.delegatecall(_calldata); if (!success) { if (error.length > 0) { // bubble up the error revert(string(error)); } else { revert("LibDiamondCut: _init function reverted"); } } } } function enforceHasContractCode(address _contract, string memory _errorMessage) internal view { uint256 contractSize; assembly { contractSize := extcodesize(_contract) } require(contractSize > 0, _errorMessage); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * EIP-2535 Diamond Standard: https://eips.ethereum.org/EIPS/eip-2535 /******************************************************************************/ interface IDiamondCut { enum FacetCutAction {Add, Replace, Remove} // Add=0, Replace=1, Remove=2 struct FacetCut { address facetAddress; FacetCutAction action; bytes4[] functionSelectors; } /// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and arguments /// _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external; event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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/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 pragma solidity 0.8.10; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; library LibERC721 { using Address for address; using Counters for Counters.Counter; bytes32 constant ERC721_STORAGE_POSITION = keccak256("com.enterdao.landworks.erc721"); struct ERC721Storage { bool initialized; // Token name string name; // Token symbol string symbol; // Token base URI string baseURI; // Tracks the total tokens minted. Counters.Counter totalMinted; // Mapping from token ID to owner address mapping(uint256 => address) owners; // Mapping owner address to token count mapping(address => uint256) balances; // Mapping from token ID to approved address mapping(uint256 => address) tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) operatorApprovals; // Mapping from tokenID to consumer mapping(uint256 => address) tokenConsumers; // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) allTokensIndex; } /** * @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 See {IERC721Consumable-ConsumerChanged} */ event ConsumerChanged( address indexed owner, address indexed consumer, uint256 indexed tokenId ); /** * @dev Emiited when `baseURI` is set */ event SetBaseURI(string _baseURI); function erc721Storage() internal pure returns (ERC721Storage storage erc721) { bytes32 position = ERC721_STORAGE_POSITION; assembly { erc721.slot := position } } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal { transfer(from, to, tokenId); require( checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function exists(uint256 tokenId) internal view returns (bool) { return LibERC721.erc721Storage().owners[tokenId] != address(0); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) internal view returns (address) { address owner = erc721Storage().owners[tokenId]; require( owner != address(0), "ERC721: owner query for nonexistent token" ); return owner; } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return erc721Storage().balances[owner]; } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) internal view returns (address) { require( exists(tokenId), "ERC721: approved query for nonexistent token" ); return erc721Storage().tokenApprovals[tokenId]; } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) internal view returns (bool) { return erc721Storage().operatorApprovals[owner][operator]; } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require( exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * Returns `tokenId`. * * Its `tokenId` will be automatically assigned (available on the emitted {IERC721-Transfer} event). * * See {xref-LibERC721-safeMint-address-uint256-}[`safeMint`] */ function safeMint(address to) internal returns (uint256) { ERC721Storage storage erc721 = erc721Storage(); uint256 tokenId = erc721.totalMinted.current(); erc721.totalMinted.increment(); safeMint(to, tokenId, ""); return tokenId; } /** * @dev Same as {xref-LibERC721-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 { mint(to, tokenId); require( checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!exists(tokenId), "ERC721: token already minted"); beforeTokenTransfer(address(0), to, tokenId); ERC721Storage storage erc721 = erc721Storage(); erc721.balances[to] += 1; erc721.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 { address owner = ownerOf(tokenId); beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals approve(address(0), tokenId); ERC721Storage storage erc721 = LibERC721.erc721Storage(); erc721.balances[owner] -= 1; delete erc721.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 { require( ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner approve(address(0), tokenId); ERC721Storage storage erc721 = LibERC721.erc721Storage(); erc721.balances[from] -= 1; erc721.balances[to] += 1; erc721.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 { erc721Storage().tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Changes the consumer of `tokenId` to `consumer`. * * Emits a {ConsumerChanged} event. */ function changeConsumer( address owner, address consumer, uint256 tokenId ) internal { ERC721Storage storage erc721 = erc721Storage(); erc721.tokenConsumers[tokenId] = consumer; emit ConsumerChanged(owner, consumer, tokenId); } /** * @dev See {IERC721Consumable-consumerOf}. */ function consumerOf(uint256 tokenId) internal view returns (address) { require( exists(tokenId), "ERC721Consumer: consumer query for nonexistent token" ); return erc721Storage().tokenConsumers[tokenId]; } /** * @dev Returns whether `spender` is allowed to consume `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function isConsumerOf(address spender, uint256 tokenId) internal view returns (bool) { return spender == consumerOf(tokenId); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function beforeTokenTransfer( address from, address to, uint256 tokenId ) internal { if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } changeConsumer(from, address(0), 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 = balanceOf(to); ERC721Storage storage erc721 = LibERC721.erc721Storage(); erc721.ownedTokens[to][length] = tokenId; erc721.ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { ERC721Storage storage erc721 = LibERC721.erc721Storage(); erc721.allTokensIndex[tokenId] = erc721.allTokens.length; erc721.allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = balanceOf(from) - 1; ERC721Storage storage erc721 = LibERC721.erc721Storage(); uint256 tokenIndex = erc721.ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = erc721.ownedTokens[from][lastTokenIndex]; erc721.ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token erc721.ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete erc721.ownedTokensIndex[tokenId]; delete erc721.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). ERC721Storage storage erc721 = LibERC721.erc721Storage(); uint256 lastTokenIndex = erc721.allTokens.length - 1; uint256 tokenIndex = erc721.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 = erc721.allTokens[lastTokenIndex]; erc721.allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token erc721.allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete erc721.allTokensIndex[tokenId]; erc721.allTokens.pop(); } /** * @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 ) internal returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC721: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; library LibFee { using EnumerableSet for EnumerableSet.AddressSet; uint256 constant FEE_PRECISION = 100_000; bytes32 constant FEE_STORAGE_POSITION = keccak256("com.enterdao.landworks.fee"); event SetTokenPayment(address indexed _token, bool _status); event SetFee(address indexed _token, uint256 _fee); struct FeeStorage { // Supported tokens as a form of payment EnumerableSet.AddressSet tokenPayments; // Protocol fee percentages for tokens mapping(address => uint256) feePercentages; // Assets' rent fees mapping(uint256 => mapping(address => uint256)) assetRentFees; // Protocol fees for tokens mapping(address => uint256) protocolFees; } function feeStorage() internal pure returns (FeeStorage storage fs) { bytes32 position = FEE_STORAGE_POSITION; assembly { fs.slot := position } } function distributeFees( uint256 _assetId, address _token, uint256 _amount ) internal returns(uint256, uint256) { LibFee.FeeStorage storage fs = feeStorage(); uint256 protocolFee = (_amount * fs.feePercentages[_token]) / FEE_PRECISION; uint256 rentFee = _amount - protocolFee; fs.assetRentFees[_assetId][_token] += rentFee; fs.protocolFees[_token] += protocolFee; return (rentFee, protocolFee); } function clearAccumulatedRent(uint256 _assetId, address _token) internal returns (uint256) { LibFee.FeeStorage storage fs = feeStorage(); uint256 amount = fs.assetRentFees[_assetId][_token]; fs.assetRentFees[_assetId][_token] = 0; return amount; } function clearAccumulatedProtocolFee(address _token) internal returns (uint256) { LibFee.FeeStorage storage fs = feeStorage(); uint256 amount = fs.protocolFees[_token]; fs.protocolFees[_token] = 0; return amount; } function setFeePercentage(address _token, uint256 _feePercentage) internal { LibFee.FeeStorage storage fs = feeStorage(); require( _feePercentage < FEE_PRECISION, "_feePercentage exceeds or equal to feePrecision" ); fs.feePercentages[_token] = _feePercentage; emit SetFee(_token, _feePercentage); } function setTokenPayment(address _token, bool _status) internal { FeeStorage storage fs = feeStorage(); if (_status) { require(fs.tokenPayments.add(_token), "_token already added"); } else { require(fs.tokenPayments.remove(_token), "_token not found"); } emit SetTokenPayment(_token, _status); } function supportsTokenPayment(address _token) internal view returns (bool) { return feeStorage().tokenPayments.contains(_token); } function totalTokenPayments() internal view returns (uint256) { return feeStorage().tokenPayments.length(); } function tokenPaymentAt(uint256 _index) internal view returns (address) { return feeStorage().tokenPayments.at(_index); } function protocolFeeFor(address _token) internal view returns (uint256) { return feeStorage().protocolFees[_token]; } function assetRentFeesFor(uint256 _assetId, address _token) internal view returns (uint256) { return feeStorage().assetRentFees[_assetId][_token]; } function feePercentage(address _token) internal view returns (uint256) { return feeStorage().feePercentages[_token]; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; /// @title LibTransfer /// @notice Contains helper methods for interacting with ETH, /// ERC-20 and ERC-721 transfers. Serves as a wrapper for all /// transfers. library LibTransfer { using SafeERC20 for IERC20; address constant ETHEREUM_PAYMENT_TOKEN = address(1); /// @notice Transfers tokens from contract to a recipient /// @dev If token is 0x0000000000000000000000000000000000000001, an ETH transfer is done /// @param _token The target token /// @param _recipient The recipient of the transfer /// @param _amount The amount of the transfer function safeTransfer( address _token, address _recipient, uint256 _amount ) internal { if (_token == ETHEREUM_PAYMENT_TOKEN) { payable(_recipient).transfer(_amount); } else { IERC20(_token).safeTransfer(_recipient, _amount); } } function safeTransferFrom( address _token, address _from, address _to, uint256 _amount ) internal { IERC20(_token).safeTransferFrom(_from, _to, _amount); } function erc721SafeTransferFrom( address _token, address _from, address _to, uint256 _tokenId ) internal { IERC721(_token).safeTransferFrom(_from, _to, _tokenId); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; library LibMarketplace { using EnumerableSet for EnumerableSet.AddressSet; bytes32 constant MARKETPLACE_STORAGE_POSITION = keccak256("com.enterdao.landworks.marketplace"); enum AssetStatus { Listed, Delisted } struct Asset { uint256 metaverseId; address metaverseRegistry; uint256 metaverseAssetId; address paymentToken; uint256 minPeriod; uint256 maxPeriod; uint256 maxFutureTime; uint256 pricePerSecond; uint256 totalRents; AssetStatus status; } struct Rent { address renter; uint256 start; uint256 end; } struct MetaverseRegistry { // Name of the Metaverse string name; // Supported registries EnumerableSet.AddressSet registries; } struct MarketplaceStorage { // Supported metaverse registries mapping(uint256 => MetaverseRegistry) metaverseRegistries; // Assets by ID mapping(uint256 => Asset) assets; // Rents by asset ID mapping(uint256 => mapping(uint256 => Rent)) rents; } function marketplaceStorage() internal pure returns (MarketplaceStorage storage ms) { bytes32 position = MARKETPLACE_STORAGE_POSITION; assembly { ms.slot := position } } function setMetaverseName(uint256 _metaverseId, string memory _name) internal { marketplaceStorage().metaverseRegistries[_metaverseId].name = _name; } function metaverseName(uint256 _metaverseId) internal view returns (string memory) { return marketplaceStorage().metaverseRegistries[_metaverseId].name; } function setRegistry( uint256 _metaverseId, address _registry, bool _status ) internal { LibMarketplace.MetaverseRegistry storage mr = marketplaceStorage() .metaverseRegistries[_metaverseId]; if (_status) { require(mr.registries.add(_registry), "_registry already added"); } else { require(mr.registries.remove(_registry), "_registry not found"); } } function supportsRegistry(uint256 _metaverseId, address _registry) internal view returns (bool) { return marketplaceStorage() .metaverseRegistries[_metaverseId] .registries .contains(_registry); } function totalRegistries(uint256 _metaverseId) internal view returns (uint256) { return marketplaceStorage() .metaverseRegistries[_metaverseId] .registries .length(); } function registryAt(uint256 _metaverseId, uint256 _index) internal view returns (address) { return marketplaceStorage() .metaverseRegistries[_metaverseId] .registries .at(_index); } function addRent( uint256 _assetId, address _renter, uint256 _start, uint256 _end ) internal returns (uint256) { LibMarketplace.MarketplaceStorage storage ms = marketplaceStorage(); uint256 newRentId = ms.assets[_assetId].totalRents + 1; ms.assets[_assetId].totalRents = newRentId; ms.rents[_assetId][newRentId] = LibMarketplace.Rent({ renter: _renter, start: _start, end: _end }); return newRentId; } function assetAt(uint256 _assetId) internal view returns (Asset memory) { return marketplaceStorage().assets[_assetId]; } function rentAt(uint256 _assetId, uint256 _rentId) internal view returns (Rent memory) { return marketplaceStorage().rents[_assetId][_rentId]; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library 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.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface 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.0 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface 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.0 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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; } }
Updates the operator for the given rent of an asset _assetId The target asset _rentId The target rent for the asset _newOperator The to-be-set new operator
function updateOperator( uint256 _assetId, uint256 _rentId, address _newOperator ) external { require(_newOperator != address(0), "_newOperator must not be 0x0"); LibMarketplace.MarketplaceStorage storage ms = LibMarketplace .marketplaceStorage(); require(LibERC721.exists(_assetId), "_assetId not found"); require( msg.sender == ms.rents[_assetId][_rentId].renter, "caller is not renter" ); LibDecentraland.setOperator(_assetId, _rentId, _newOperator); emit UpdateOperator(_assetId, _rentId, _newOperator); }
224,236
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./spec_interfaces/IElections.sol"; import "./spec_interfaces/IDelegations.sol"; import "./spec_interfaces/IGuardiansRegistration.sol"; import "./spec_interfaces/ICommittee.sol"; import "./spec_interfaces/ICertification.sol"; import "./ManagedContract.sol"; /// @title Elections contract contract Elections is IElections, ManagedContract { using SafeMath for uint256; uint32 constant PERCENT_MILLIE_BASE = 100000; mapping(address => mapping(address => uint256)) voteUnreadyVotes; // by => to => expiration mapping(address => uint256) public votersStake; mapping(address => address) voteOutVotes; // by => to mapping(address => uint256) accumulatedStakesForVoteOut; // addr => total stake mapping(address => bool) votedOutGuardians; struct Settings { uint32 minSelfStakePercentMille; uint32 voteUnreadyPercentMilleThreshold; uint32 voteOutPercentMilleThreshold; } Settings settings; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param minSelfStakePercentMille is the minimum self stake in percent-mille (0-100,000) /// @param voteUnreadyPercentMilleThreshold is the minimum vote-unready threshold in percent-mille (0-100,000) /// @param voteOutPercentMilleThreshold is the minimum vote-out threshold in percent-mille (0-100,000) constructor(IContractRegistry _contractRegistry, address _registryAdmin, uint32 minSelfStakePercentMille, uint32 voteUnreadyPercentMilleThreshold, uint32 voteOutPercentMilleThreshold) ManagedContract(_contractRegistry, _registryAdmin) public { setMinSelfStakePercentMille(minSelfStakePercentMille); setVoteOutPercentMilleThreshold(voteOutPercentMilleThreshold); setVoteUnreadyPercentMilleThreshold(voteUnreadyPercentMilleThreshold); } modifier onlyDelegationsContract() { require(msg.sender == address(delegationsContract), "caller is not the delegations contract"); _; } modifier onlyGuardiansRegistrationContract() { require(msg.sender == address(guardianRegistrationContract), "caller is not the guardian registrations contract"); _; } modifier onlyCertificationContract() { require(msg.sender == address(certificationContract), "caller is not the certification contract"); _; } /* * External functions */ /// Notifies that the guardian is ready to sync with other nodes /// @dev ready to sync state is not managed in the contract that only emits an event /// @dev readyToSync clears the readyForCommittee state function readyToSync() external override onlyWhenActive { address guardian = guardianRegistrationContract.resolveGuardianAddress(msg.sender); // this validates registration require(!isVotedOut(guardian), "caller is voted-out"); emit GuardianStatusUpdated(guardian, true, false); committeeContract.removeMember(guardian); } /// Notifies that the guardian is ready to join the committee /// @dev a qualified guardian calling readyForCommittee is added to the committee function readyForCommittee() external override onlyWhenActive { _readyForCommittee(msg.sender); } /// Checks if a guardian is qualified to join the committee /// @dev when true, calling readyForCommittee() will result in adding the guardian to the committee /// @dev called periodically by guardians to check if they are qualified to join the committee /// @param guardian is the guardian to check /// @return canJoin indicating that the guardian can join the current committee function canJoinCommittee(address guardian) external view override returns (bool) { guardian = guardianRegistrationContract.resolveGuardianAddress(guardian); // this validates registration if (isVotedOut(guardian)) { return false; } uint256 effectiveStake = getGuardianEffectiveStake(guardian, settings); return committeeContract.checkAddMember(guardian, effectiveStake); } /// Returns an address effective stake /// The effective stake is derived from a guardian delegate stake and selfs stake /// @return effectiveStake is the guardian's effective stake function getEffectiveStake(address guardian) external override view returns (uint effectiveStake) { return getGuardianEffectiveStake(guardian, settings); } /// Returns the current committee along with the guardians' Orbs address and IP /// @return committee is a list of the committee members' guardian addresses /// @return weights is a list of the committee members' weight (effective stake) /// @return orbsAddrs is a list of the committee members' orbs address /// @return certification is a list of bool indicating the committee members certification /// @return ips is a list of the committee members' ip function getCommittee() external override view returns (address[] memory committee, uint256[] memory weights, address[] memory orbsAddrs, bool[] memory certification, bytes4[] memory ips) { IGuardiansRegistration _guardianRegistrationContract = guardianRegistrationContract; (committee, weights, certification) = committeeContract.getCommittee(); orbsAddrs = _guardianRegistrationContract.getGuardiansOrbsAddress(committee); ips = _guardianRegistrationContract.getGuardianIps(committee); } // Vote-unready /// Casts an unready vote on a subject guardian /// @dev Called by a guardian as part of the automatic vote-unready flow /// @dev The transaction may be sent from the guardian or orbs address. /// @param subject is the subject guardian to vote out /// @param voteExpiration is the expiration time of the vote unready to prevent counting of a vote that is already irrelevant. function voteUnready(address subject, uint voteExpiration) external override onlyWhenActive { require(voteExpiration >= block.timestamp, "vote expiration time must not be in the past"); address voter = guardianRegistrationContract.resolveGuardianAddress(msg.sender); voteUnreadyVotes[voter][subject] = voteExpiration; emit VoteUnreadyCasted(voter, subject, voteExpiration); (address[] memory generalCommittee, uint256[] memory generalWeights, bool[] memory certification) = committeeContract.getCommittee(); bool votedUnready = isCommitteeVoteUnreadyThresholdReached(generalCommittee, generalWeights, certification, subject); if (votedUnready) { clearCommitteeUnreadyVotes(generalCommittee, subject); emit GuardianVotedUnready(subject); emit GuardianStatusUpdated(subject, false, false); committeeContract.removeMember(subject); } } /// Returns the current vote unready vote for a voter and a subject pair /// @param voter is the voting guardian address /// @param subject is the subject guardian address /// @return valid indicates whether there is a valid vote /// @return expiration returns the votes expiration time function getVoteUnreadyVote(address voter, address subject) public override view returns (bool valid, uint256 expiration) { expiration = voteUnreadyVotes[voter][subject]; valid = expiration != 0 && block.timestamp < expiration; } /// Returns the current vote-unready status of a subject guardian. /// @dev the committee and certification data is used to check the certified and committee threshold /// @param subject is the subject guardian address /// @return committee is a list of the current committee members /// @return weights is a list of the current committee members weight /// @return certification is a list of bool indicating the committee members certification /// @return votes is a list of bool indicating the members that votes the subject unready /// @return subjectInCommittee indicates that the subject is in the committee /// @return subjectInCertifiedCommittee indicates that the subject is in the certified committee function getVoteUnreadyStatus(address subject) external override view returns (address[] memory committee, uint256[] memory weights, bool[] memory certification, bool[] memory votes, bool subjectInCommittee, bool subjectInCertifiedCommittee) { (committee, weights, certification) = committeeContract.getCommittee(); votes = new bool[](committee.length); for (uint i = 0; i < committee.length; i++) { address memberAddr = committee[i]; if (block.timestamp < voteUnreadyVotes[memberAddr][subject]) { votes[i] = true; } if (memberAddr == subject) { subjectInCommittee = true; subjectInCertifiedCommittee = certification[i]; } } } // Vote-out /// Casts a voteOut vote by the sender to the given address /// @dev the transaction is sent from the guardian address /// @param subject is the subject guardian address function voteOut(address subject) external override onlyWhenActive { Settings memory _settings = settings; address voter = msg.sender; address prevSubject = voteOutVotes[voter]; voteOutVotes[voter] = subject; emit VoteOutCasted(voter, subject); uint256 voterStake = delegationsContract.getDelegatedStake(voter); if (prevSubject == address(0)) { votersStake[voter] = voterStake; } if (subject == address(0)) { delete votersStake[voter]; } uint totalStake = delegationsContract.getTotalDelegatedStake(); if (prevSubject != address(0) && prevSubject != subject) { applyVoteOutVotesFor(prevSubject, 0, voterStake, totalStake, _settings); } if (subject != address(0)) { uint voteStakeAdded = prevSubject != subject ? voterStake : 0; applyVoteOutVotesFor(subject, voteStakeAdded, 0, totalStake, _settings); // recheck also if not new } } /// Returns the subject address the addr has voted-out against /// @param voter is the voting guardian address /// @return subject is the subject the voter has voted out function getVoteOutVote(address voter) external override view returns (address) { return voteOutVotes[voter]; } /// Returns the governance voteOut status of a guardian. /// @dev A guardian is voted out if votedStake / totalDelegatedStake (in percent mille) > threshold /// @param subject is the subject guardian address /// @return votedOut indicates whether the subject was voted out /// @return votedStake is the total stake voting against the subject /// @return totalDelegatedStake is the total delegated stake function getVoteOutStatus(address subject) external override view returns (bool votedOut, uint votedStake, uint totalDelegatedStake) { votedOut = isVotedOut(subject); votedStake = accumulatedStakesForVoteOut[subject]; totalDelegatedStake = delegationsContract.getTotalDelegatedStake(); } /* * Notification functions from other PoS contracts */ /// Notifies a delegated stake change event /// @dev Called by: delegation contract /// @param delegate is the delegate to update /// @param selfDelegatedStake is the delegate self stake (0 if not self-delegating) /// @param delegatedStake is the delegate delegated stake (0 if not self-delegating) /// @param totalDelegatedStake is the total delegated stake function delegatedStakeChange(address delegate, uint256 selfDelegatedStake, uint256 delegatedStake, uint256 totalDelegatedStake) external override onlyDelegationsContract onlyWhenActive { Settings memory _settings = settings; uint effectiveStake = calcEffectiveStake(selfDelegatedStake, delegatedStake, _settings); emit StakeChanged(delegate, selfDelegatedStake, delegatedStake, effectiveStake); committeeContract.memberWeightChange(delegate, effectiveStake); applyStakesToVoteOutBy(delegate, delegatedStake, totalDelegatedStake, _settings); } /// Notifies a new guardian was unregistered /// @dev Called by: guardian registration contract /// @dev when a guardian unregisters its status is updated to not ready to sync and is removed from the committee /// @param guardian is the address of the guardian that unregistered function guardianUnregistered(address guardian) external override onlyGuardiansRegistrationContract onlyWhenActive { emit GuardianStatusUpdated(guardian, false, false); committeeContract.removeMember(guardian); } /// Notifies on a guardian certification change /// @dev Called by: guardian registration contract /// @param guardian is the address of the guardian to update /// @param isCertified indicates whether the guardian is certified function guardianCertificationChanged(address guardian, bool isCertified) external override onlyCertificationContract onlyWhenActive { committeeContract.memberCertificationChange(guardian, isCertified); } /* * Governance functions */ /// Sets the minimum self stake requirement for the effective stake /// @dev governance function called only by the functional manager /// @param minSelfStakePercentMille is the minimum self stake in percent-mille (0-100,000) function setMinSelfStakePercentMille(uint32 minSelfStakePercentMille) public override onlyFunctionalManager { require(minSelfStakePercentMille <= PERCENT_MILLIE_BASE, "minSelfStakePercentMille must be 100000 at most"); emit MinSelfStakePercentMilleChanged(minSelfStakePercentMille, settings.minSelfStakePercentMille); settings.minSelfStakePercentMille = minSelfStakePercentMille; } /// Returns the minimum self-stake required for the effective stake /// @return minSelfStakePercentMille is the minimum self stake in percent-mille function getMinSelfStakePercentMille() external override view returns (uint32) { return settings.minSelfStakePercentMille; } /// Sets the vote-out threshold /// @dev governance function called only by the functional manager /// @param voteOutPercentMilleThreshold is the minimum threshold in percent-mille (0-100,000) function setVoteOutPercentMilleThreshold(uint32 voteOutPercentMilleThreshold) public override onlyFunctionalManager { require(voteOutPercentMilleThreshold <= PERCENT_MILLIE_BASE, "voteOutPercentMilleThreshold must not be larger than 100000"); emit VoteOutPercentMilleThresholdChanged(voteOutPercentMilleThreshold, settings.voteOutPercentMilleThreshold); settings.voteOutPercentMilleThreshold = voteOutPercentMilleThreshold; } /// Returns the vote-out threshold /// @return voteOutPercentMilleThreshold is the minimum threshold in percent-mille function getVoteOutPercentMilleThreshold() external override view returns (uint32) { return settings.voteOutPercentMilleThreshold; } /// Sets the vote-unready threshold /// @dev governance function called only by the functional manager /// @param voteUnreadyPercentMilleThreshold is the minimum threshold in percent-mille (0-100,000) function setVoteUnreadyPercentMilleThreshold(uint32 voteUnreadyPercentMilleThreshold) public override onlyFunctionalManager { require(voteUnreadyPercentMilleThreshold <= PERCENT_MILLIE_BASE, "voteUnreadyPercentMilleThreshold must not be larger than 100000"); emit VoteUnreadyPercentMilleThresholdChanged(voteUnreadyPercentMilleThreshold, settings.voteUnreadyPercentMilleThreshold); settings.voteUnreadyPercentMilleThreshold = voteUnreadyPercentMilleThreshold; } /// Returns the vote-unready threshold /// @return voteUnreadyPercentMilleThreshold is the minimum threshold in percent-mille function getVoteUnreadyPercentMilleThreshold() external override view returns (uint32) { return settings.voteUnreadyPercentMilleThreshold; } /// Returns the contract's settings /// @return minSelfStakePercentMille is the minimum self stake in percent-mille /// @return voteUnreadyPercentMilleThreshold is the minimum threshold in percent-mille /// @return voteOutPercentMilleThreshold is the minimum threshold in percent-mille function getSettings() external override view returns ( uint32 minSelfStakePercentMille, uint32 voteUnreadyPercentMilleThreshold, uint32 voteOutPercentMilleThreshold ) { Settings memory _settings = settings; minSelfStakePercentMille = _settings.minSelfStakePercentMille; voteUnreadyPercentMilleThreshold = _settings.voteUnreadyPercentMilleThreshold; voteOutPercentMilleThreshold = _settings.voteOutPercentMilleThreshold; } /// Initializes the ready for committee notification for the committee guardians /// @dev governance function called only by the initialization admin during migration /// @dev identical behaviour as if each guardian sent readyForCommittee() /// @param guardians a list of guardians addresses to update function initReadyForCommittee(address[] calldata guardians) external override onlyInitializationAdmin { for (uint i = 0; i < guardians.length; i++) { _readyForCommittee(guardians[i]); } } /* * Private functions */ /// Handles a readyForCommittee notification /// @dev may be called with either the guardian address or the guardian's orbs address /// @dev notifies the committee contract that will add the guardian if qualified /// @param guardian is the guardian ready for committee function _readyForCommittee(address guardian) private { guardian = guardianRegistrationContract.resolveGuardianAddress(guardian); // this validates registration require(!isVotedOut(guardian), "caller is voted-out"); emit GuardianStatusUpdated(guardian, true, true); uint256 effectiveStake = getGuardianEffectiveStake(guardian, settings); committeeContract.addMember(guardian, effectiveStake, certificationContract.isGuardianCertified(guardian)); } /// Calculates a guardian effective stake based on its self-stake and delegated stake function calcEffectiveStake(uint256 selfStake, uint256 delegatedStake, Settings memory _settings) private pure returns (uint256) { if (selfStake.mul(PERCENT_MILLIE_BASE) >= delegatedStake.mul(_settings.minSelfStakePercentMille)) { return delegatedStake; } return selfStake.mul(PERCENT_MILLIE_BASE).div(_settings.minSelfStakePercentMille); // never overflows or divides by zero } /// Returns the effective state of a guardian /// @dev calls the delegation contract to retrieve the guardian current stake and delegated stake /// @param guardian is the guardian to query /// @param _settings is the contract settings struct /// @return effectiveStake is the guardian's effective stake function getGuardianEffectiveStake(address guardian, Settings memory _settings) private view returns (uint256 effectiveStake) { IDelegations _delegationsContract = delegationsContract; (,uint256 selfStake) = _delegationsContract.getDelegationInfo(guardian); uint256 delegatedStake = _delegationsContract.getDelegatedStake(guardian); return calcEffectiveStake(selfStake, delegatedStake, _settings); } // Vote-unready /// Checks if the vote unready threshold was reached for a given subject /// @dev a subject is voted-unready if either it reaches the threshold in the general committee or a certified subject reaches the threshold in the certified committee /// @param committee is a list of the current committee members /// @param weights is a list of the current committee members weight /// @param certification is a list of bool indicating the committee members certification /// @param subject is the subject guardian address /// @return thresholdReached is a bool indicating that the threshold was reached function isCommitteeVoteUnreadyThresholdReached(address[] memory committee, uint256[] memory weights, bool[] memory certification, address subject) private returns (bool) { Settings memory _settings = settings; uint256 totalCommitteeStake = 0; uint256 totalVoteUnreadyStake = 0; uint256 totalCertifiedStake = 0; uint256 totalCertifiedVoteUnreadyStake = 0; address member; uint256 memberStake; bool isSubjectCertified; for (uint i = 0; i < committee.length; i++) { member = committee[i]; memberStake = weights[i]; if (member == subject && certification[i]) { isSubjectCertified = true; } totalCommitteeStake = totalCommitteeStake.add(memberStake); if (certification[i]) { totalCertifiedStake = totalCertifiedStake.add(memberStake); } (bool valid, uint256 expiration) = getVoteUnreadyVote(member, subject); if (valid) { totalVoteUnreadyStake = totalVoteUnreadyStake.add(memberStake); if (certification[i]) { totalCertifiedVoteUnreadyStake = totalCertifiedVoteUnreadyStake.add(memberStake); } } else if (expiration != 0) { // Vote is stale, delete from state delete voteUnreadyVotes[member][subject]; } } return ( totalCommitteeStake > 0 && totalVoteUnreadyStake.mul(PERCENT_MILLIE_BASE) >= uint256(_settings.voteUnreadyPercentMilleThreshold).mul(totalCommitteeStake) ) || ( isSubjectCertified && totalCertifiedStake > 0 && totalCertifiedVoteUnreadyStake.mul(PERCENT_MILLIE_BASE) >= uint256(_settings.voteUnreadyPercentMilleThreshold).mul(totalCertifiedStake) ); } /// Clears the committee members vote-unready state upon declaring a guardian unready /// @param committee is a list of the current committee members /// @param subject is the subject guardian address function clearCommitteeUnreadyVotes(address[] memory committee, address subject) private { for (uint i = 0; i < committee.length; i++) { voteUnreadyVotes[committee[i]][subject] = 0; // clear vote-outs } } // Vote-out /// Updates the vote-out state upon a stake change notification /// @param voter is the voter address /// @param currentVoterStake is the voter delegated stake /// @param totalDelegatedStake is the total delegated stake /// @param _settings is the contract settings struct function applyStakesToVoteOutBy(address voter, uint256 currentVoterStake, uint256 totalDelegatedStake, Settings memory _settings) private { address subject = voteOutVotes[voter]; if (subject == address(0)) return; uint256 prevVoterStake = votersStake[voter]; votersStake[voter] = currentVoterStake; applyVoteOutVotesFor(subject, currentVoterStake, prevVoterStake, totalDelegatedStake, _settings); } /// Applies updates in a vote-out subject state and checks whether its threshold was reached /// @param subject is the vote-out subject /// @param voteOutStakeAdded is the added votes against the subject /// @param voteOutStakeRemoved is the removed votes against the subject /// @param totalDelegatedStake is the total delegated stake used to check the vote-out threshold /// @param _settings is the contract settings struct function applyVoteOutVotesFor(address subject, uint256 voteOutStakeAdded, uint256 voteOutStakeRemoved, uint256 totalDelegatedStake, Settings memory _settings) private { if (isVotedOut(subject)) { return; } uint256 accumulated = accumulatedStakesForVoteOut[subject]. sub(voteOutStakeRemoved). add(voteOutStakeAdded); bool shouldBeVotedOut = totalDelegatedStake > 0 && accumulated.mul(PERCENT_MILLIE_BASE) >= uint256(_settings.voteOutPercentMilleThreshold).mul(totalDelegatedStake); if (shouldBeVotedOut) { votedOutGuardians[subject] = true; emit GuardianVotedOut(subject); emit GuardianStatusUpdated(subject, false, false); committeeContract.removeMember(subject); } accumulatedStakesForVoteOut[subject] = accumulated; } /// Checks whether a guardian was voted out function isVotedOut(address guardian) private view returns (bool) { return votedOutGuardians[guardian]; } /* * Contracts topology / registry interface */ ICommittee committeeContract; IDelegations delegationsContract; IGuardiansRegistration guardianRegistrationContract; ICertification certificationContract; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); delegationsContract = IDelegations(getDelegationsContract()); guardianRegistrationContract = IGuardiansRegistration(getGuardiansRegistrationContract()); certificationContract = ICertification(getCertificationContract()); } }
Clears the committee members vote-unready state upon declaring a guardian unready committee is a list of the current committee members subject is the subject guardian address
function clearCommitteeUnreadyVotes(address[] memory committee, address subject) private { for (uint i = 0; i < committee.length; i++) { } }
7,296,663
./full_match/1/0x9b2Dc6e830320C48044a555263cBA4CdeB0FB201/sources/contracts/DeHiveTokensale.sol
Checks if currently purchased amount does not reach cap per wallet. purchaseAmount DHV tokens currently purchased/
function _checkCapReached(uint256 purchaseAmount) private view { if (_isPreSale()) { require(purchaseAmount.add(purchased[msg.sender]) <= maxTokensAmount, "Maximum allowed exceeded"); } else { require(purchaseAmount.add(purchasedPublic[msg.sender]) <= maxTokensAmount, "Maximum allowed exceeded"); } }
3,125,542
./full_match/570/0x8C9A3194F9392A86F22eD68A7755fB785854b8Bb/sources/contracts/tokens/ERC1155/ERC1155Private.sol
Internal function to set changeability of BaseURI for NFT drops./initializing base minters list
function _setInitialMinters(address[] memory minters) internal virtual { for (uint256 i = 0; i < minters.length; i++) { approvedMinters[minters[i]] = true; } }
16,382,019
./partial_match/1/0x49a3237C9Ae578B0165559dA6a18717fA1Ca1F68/sources/SeedIcoRound.sol
the actual ETH/USD conversation rate, after adjusting the extra 0s.
function convertEthToUsd(uint256 ethAmount) public view returns (uint256) { uint256 ethPrice = ethPriceInUSD(); uint256 ethAmountInUsd = (ethPrice * ethAmount) / 1000000000000000000; return ethAmountInUsd; }
4,431,928
./full_match/4/0x2d55d6715e838239DDEd1AD1027C4B0024dd2694/sources/contracts/interfaces/IUniswapV2Pair.sol
event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value);
interface IUniswapV2Paisr { 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.7.0 <0.9.0; }
12,305,724
./full_match/1/0x91A6194F1278f6Cf25ae51B604029075695A74E5/sources/contracts/Vault.sol
@inheritdoc IVault disinvest
function updateInvested() external override(IVault) onlyKeeper { if (address(strategy) == address(0)) revert VaultStrategyNotSet(); (uint256 maxInvestableAmount, uint256 alreadyInvested) = investState(); if (maxInvestableAmount == alreadyInvested) revert VaultNothingToDo(); if (alreadyInvested > maxInvestableAmount) { uint256 disinvestAmount = alreadyInvested - maxInvestableAmount; if (disinvestAmount < rebalanceMinimum) revert VaultNotEnoughToRebalance(); strategy.withdrawToVault(disinvestAmount); emit Disinvested(disinvestAmount); return; } if (investAmount < rebalanceMinimum) revert VaultNotEnoughToRebalance(); underlying.safeTransfer(address(strategy), investAmount); strategy.invest(); emit Invested(investAmount); }
4,864,815
pragma solidity 0.6.12; interface IERC20 { function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD659(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB877(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB877(a, b, "SafeMath: subtraction overflow"); } function SUB877(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL487(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV156(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV156(a, b, "SafeMath: division by zero"); } function DIV156(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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; } function MOD860(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD860(a, b, "SafeMath: modulo by zero"); } function MOD860(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT107(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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); } function SENDVALUE513(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING 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"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER239(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFER353.selector, to, value)); } function SAFETRANSFERFROM64(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFERFROM954.selector, from, to, value)); } function SAFEAPPROVE765(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // 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.ALLOWANCE946(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, value)); } function SAFEINCREASEALLOWANCE134(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE946(address(this), spender).ADD659(value); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE546(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE946(address(this), spender).SUB877(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN137(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // 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).ISCONTRACT107(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } library 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; } function _ADD286(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING if (!_CONTAINS837(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; } } function _REMOVE863(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING // 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; } } function _CONTAINS837(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING return set._indexes[value] != 0; } function _LENGTH639(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING return set._values.length; } function _AT524(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } function ADD659(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD286(set._inner, bytes32(uint256(value))); } function REMOVE976(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE863(set._inner, bytes32(uint256(value))); } function CONTAINS600(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS837(set._inner, bytes32(uint256(value))); } function LENGTH659(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH639(set._inner); } function AT450(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING return address(uint256(_AT524(set._inner, index))); } // UintSet struct UintSet { Set _inner; } function ADD659(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD286(set._inner, bytes32(value)); } function REMOVE976(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE863(set._inner, bytes32(value)); } function CONTAINS600(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS837(set._inner, bytes32(value)); } function LENGTH659(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH639(set._inner); } function AT450(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING return uint256(_AT524(set._inner, index)); } } contract Initializable { bool private initialized; bool private initializing; modifier INITIALIZER933() { //inject NONSTANDARD NAMING require(initializing || ISCONSTRUCTOR543() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } function ISCONSTRUCTOR543() private view returns (bool) { //inject NONSTANDARD NAMING // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __CONTEXT_INIT408() internal INITIALIZER933 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED28(); } function __CONTEXT_INIT_UNCHAINED28() internal INITIALIZER933 { //inject NONSTANDARD NAMING } function _MSGSENDER195() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA356() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OWNERSHIPTRANSFERRED637(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function __OWNABLE_INIT503() internal INITIALIZER933 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED28(); __OWNABLE_INIT_UNCHAINED19(); } function __OWNABLE_INIT_UNCHAINED19() internal INITIALIZER933 { //inject NONSTANDARD NAMING address msgSender = _MSGSENDER195(); _owner = msgSender; emit OWNERSHIPTRANSFERRED637(address(0), msgSender); } function OWNER330() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER691() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER195(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP236() public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED637(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP889(address newOwner) public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED637(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } interface INBUNIERC20 { function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING event LOG470(string log); //inject NONSTANDARD NAMING } library console { address constant console_address243 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING function _SENDLOGPAYLOAD647(bytes memory payload) private view { //inject NONSTANDARD NAMING uint256 payloadLength = payload.length; address consoleAddress = console_address243; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function LOG714() internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log()")); } function LOGINT241(int p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(int)", p0)); } function LOGUINT442(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0)); } function LOGSTRING55(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0)); } function LOGBOOL721(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0)); } function LOGADDRESS713(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0)); } function LOGBYTES271(bytes memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes)", p0)); } function LOGBYTE944(byte p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(byte)", p0)); } function LOGBYTES1701(bytes1 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes1)", p0)); } function LOGBYTES2946(bytes2 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes2)", p0)); } function LOGBYTES314(bytes3 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes3)", p0)); } function LOGBYTES4424(bytes4 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes4)", p0)); } function LOGBYTES566(bytes5 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes5)", p0)); } function LOGBYTES6220(bytes6 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes6)", p0)); } function LOGBYTES7640(bytes7 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes7)", p0)); } function LOGBYTES8995(bytes8 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes8)", p0)); } function LOGBYTES9199(bytes9 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes9)", p0)); } function LOGBYTES10336(bytes10 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes10)", p0)); } function LOGBYTES11706(bytes11 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes11)", p0)); } function LOGBYTES12632(bytes12 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes12)", p0)); } function LOGBYTES13554(bytes13 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes13)", p0)); } function LOGBYTES14593(bytes14 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes14)", p0)); } function LOGBYTES15340(bytes15 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes15)", p0)); } function LOGBYTES16538(bytes16 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes16)", p0)); } function LOGBYTES17699(bytes17 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes17)", p0)); } function LOGBYTES18607(bytes18 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes18)", p0)); } function LOGBYTES19918(bytes19 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes19)", p0)); } function LOGBYTES20388(bytes20 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes20)", p0)); } function LOGBYTES21100(bytes21 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes21)", p0)); } function LOGBYTES22420(bytes22 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes22)", p0)); } function LOGBYTES238(bytes23 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes23)", p0)); } function LOGBYTES24936(bytes24 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes24)", p0)); } function LOGBYTES25750(bytes25 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes25)", p0)); } function LOGBYTES26888(bytes26 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes26)", p0)); } function LOGBYTES2749(bytes27 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes27)", p0)); } function LOGBYTES28446(bytes28 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes28)", p0)); } function LOGBYTES29383(bytes29 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes29)", p0)); } function LOGBYTES30451(bytes30 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes30)", p0)); } function LOGBYTES31456(bytes31 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes31)", p0)); } function LOGBYTES32174(bytes32 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes32)", p0)); } function LOG714(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0)); } function LOG714(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0)); } function LOG714(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0)); } function LOG714(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0)); } function LOG714(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function LOG714(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function LOG714(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function LOG714(uint p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function LOG714(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function LOG714(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string)", p0, p1)); } function LOG714(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function LOG714(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address)", p0, p1)); } function LOG714(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function LOG714(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function LOG714(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function LOG714(bool p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function LOG714(address p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function LOG714(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string)", p0, p1)); } function LOG714(address p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function LOG714(address p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address)", p0, p1)); } function LOG714(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function LOG714(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function LOG714(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function LOG714(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function LOG714(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function LOG714(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function LOG714(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function LOG714(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function LOG714(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function LOG714(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function LOG714(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function LOG714(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function LOG714(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function LOG714(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function LOG714(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function LOG714(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function LOG714(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function LOG714(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function LOG714(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function LOG714(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function LOG714(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function LOG714(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function LOG714(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function LOG714(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function LOG714(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function LOG714(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function LOG714(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function LOG714(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function LOG714(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function LOG714(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function LOG714(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function LOG714(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function LOG714(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function LOG714(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function LOG714(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function LOG714(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function LOG714(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function LOG714(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function LOG714(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function LOG714(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function LOG714(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function LOG714(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function LOG714(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function LOG714(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function LOG714(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // HDCore Vault distributes fees equally amongst staked pools // Have fun reading it. Hopefully it's bug-free. God bless. contract HdcoreVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of HdCOREs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accHdcorePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accHdcorePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. HDCOREs to distribute per block. uint256 accHdcorePerShare; // Accumulated HDCOREs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // The HDCORE TOKEN! INBUNIERC20 public hdcore; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Returns fees generated since start of this contract function AVERAGEFEESPERBLOCKSINCESTART533() external view returns (uint averagePerBlock) { //inject NONSTANDARD NAMING averagePerBlock = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch).DIV156(block.number.SUB877(contractStartBlock)); } // Returns averge fees in this epoch function AVERAGEFEESPERBLOCKEPOCH880() external view returns (uint256 averagePerBlock) { //inject NONSTANDARD NAMING averagePerBlock = rewardsInThisEpoch.DIV156(block.number.SUB877(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function STARTNEWEPOCH403() public { //inject NONSTANDARD NAMING require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event DEPOSIT941(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event WITHDRAW483(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event EMERGENCYWITHDRAW770( //inject NONSTANDARD NAMING address indexed user, uint256 indexed pid, uint256 amount ); event APPROVAL172(address indexed owner, address indexed spender, uint256 _pid, uint256 value); //inject NONSTANDARD NAMING function INITIALIZE896( //inject NONSTANDARD NAMING INBUNIERC20 _hdcore ) public INITIALIZER933 { OwnableUpgradeSafe.__OWNABLE_INIT503(); DEV_FEE = 724; hdcore = _hdcore; devaddr = msg.sender; contractStartBlock = block.number; _superAdmin = msg.sender; } function POOLLENGTH724() external view returns (uint256) { //inject NONSTANDARD NAMING return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function ADD659( //inject NONSTANDARD NAMING uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public ONLYOWNER691 { if (_withUpdate) { MASSUPDATEPOOLS941(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.ADD659(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accHdcorePerShare: 0, withdrawable : _withdrawable }) ); } // Update the given pool's HDCOREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function SET408( //inject NONSTANDARD NAMING uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public ONLYOWNER691 { if (_withUpdate) { MASSUPDATEPOOLS941(); } totalAllocPoint = totalAllocPoint.SUB877(poolInfo[_pid].allocPoint).ADD659( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function SETPOOLWITHDRAWABLE817( //inject NONSTANDARD NAMING uint256 _pid, bool _withdrawable ) public ONLYOWNER691 { poolInfo[_pid].withdrawable = _withdrawable; } // Sets the dev fee for this contract // defaults at 7.24% // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus uint16 DEV_FEE; function SETDEVFEE755(uint16 _DEV_FEE) public ONLYOWNER691 { //inject NONSTANDARD NAMING require(_DEV_FEE <= 1000, 'Dev fee clamped at 10%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // View function to see pending HDCOREs on frontend. function PENDINGHDCORE546(uint256 _pid, address _user) //inject NONSTANDARD NAMING external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accHdcorePerShare = pool.accHdcorePerShare; return user.amount.MUL487(accHdcorePerShare).DIV156(1e12).SUB877(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function MASSUPDATEPOOLS941() public { //inject NONSTANDARD NAMING console.LOG714("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.ADD659(UPDATEPOOL374(pid)); } pendingRewards = pendingRewards.SUB877(allRewards); } // ---- // Function that adds pending rewards, called by the HDCORE token. // ---- uint256 private hdcoreBalance; function ADDPENDINGREWARDS319(uint256 _) public { //inject NONSTANDARD NAMING uint256 newRewards = hdcore.BALANCEOF536(address(this)).SUB877(hdcoreBalance); if(newRewards > 0) { hdcoreBalance = hdcore.BALANCEOF536(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.ADD659(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.ADD659(newRewards); } } // Update reward variables of the given pool to be up-to-date. function UPDATEPOOL374(uint256 _pid) internal returns (uint256 hdcoreRewardWhole) { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.BALANCEOF536(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } hdcoreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .MUL487(pool.allocPoint) // getting the percent of total pending rewards this pool should get .DIV156(totalAllocPoint); // we can do this because pools are only mass updated uint256 hdcoreRewardFee = hdcoreRewardWhole.MUL487(DEV_FEE).DIV156(10000); uint256 hdcoreRewardToDistribute = hdcoreRewardWhole.SUB877(hdcoreRewardFee); pending_DEV_rewards = pending_DEV_rewards.ADD659(hdcoreRewardFee); pool.accHdcorePerShare = pool.accHdcorePerShare.ADD659( hdcoreRewardToDistribute.MUL487(1e12).DIV156(tokenSupply) ); } // Deposit tokens to HdcoreVault for HDCORE allocation. function DEPOSIT767(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; MASSUPDATEPOOLS941(); // Transfer pending tokens // to user UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD659(_amount); } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit DEPOSIT941(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function DEPOSITFOR318(address depositFor, uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; MASSUPDATEPOOLS941(); // Transfer pending tokens // to user UPDATEANDPAYOUTPENDING193(_pid, pool, user, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD659(_amount); // This is depositedFor address } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit DEPOSIT941(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function SETALLOWANCEFORPOOLTOKEN927(address spender, uint256 _pid, uint256 value) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit APPROVAL172(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function WITHDRAWFROM678(address owner, uint256 _pid, uint256 _amount) public{ //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].SUB877(_amount); _WITHDRAW26(_pid, _amount, owner, msg.sender); } // Withdraw tokens from HdcoreVault. function WITHDRAW844(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING _WITHDRAW26(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _WITHDRAW26(uint256 _pid, uint256 _amount, address from, address to) internal { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); MASSUPDATEPOOLS941(); UPDATEANDPAYOUTPENDING193(_pid, pool, user, from); // Update balances of from this is not withdrawal but claiming HDCORE farmed if(_amount > 0) { user.amount = user.amount.SUB877(_amount); pool.token.SAFETRANSFER239(address(to), _amount); } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit WITHDRAW483(to, _pid, _amount); } function CLAIM95(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; MASSUPDATEPOOLS941(); UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender); } function UPDATEANDPAYOUTPENDING193(uint256 _pid, PoolInfo storage pool, UserInfo storage user, address from) internal { //inject NONSTANDARD NAMING if(user.amount == 0) return; uint256 pending = user .amount .MUL487(pool.accHdcorePerShare) .DIV156(1e12) .SUB877(user.rewardDebt); if(pending > 0) { SAFEHDCORETRANSFER939(from, pending); } } // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will use this function to manage and farm yield on value locked function SETSTRATEGYCONTRACTORDISTRIBUTIONCONTRACTALLOWANCE131(address tokenAddress, uint256 _amount, address contractAddress) public ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING require(ISCONTRACT107(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.ADD659(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).APPROVE926(contractAddress, _amount); } function ISCONTRACT107(address addr) public returns (bool) { //inject NONSTANDARD NAMING uint size; assembly { size := extcodesize(addr) } return size > 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function EMERGENCYWITHDRAW608(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.SAFETRANSFER239(address(msg.sender), user.amount); emit EMERGENCYWITHDRAW770(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // Safe hdcore transfer function, just in case if rounding error causes pool to not have enough HDCOREs. function SAFEHDCORETRANSFER939(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING if(_amount == 0) return; uint256 hdcoreBal = hdcore.BALANCEOF536(address(this)); if (_amount > hdcoreBal) { console.LOG714("transfering out for to person:", _amount); console.LOG714("Balance of this address is :", hdcoreBal); hdcore.TRANSFER353(_to, hdcoreBal); hdcoreBalance = hdcore.BALANCEOF536(address(this)); } else { hdcore.TRANSFER353(_to, _amount); hdcoreBalance = hdcore.BALANCEOF536(address(this)); } if(pending_DEV_rewards > 0) { uint256 devSend = pending_DEV_rewards; // Avoid recursive loop pending_DEV_rewards = 0; SAFEHDCORETRANSFER939(devaddr, devSend); } } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing HDCORE governance token holders to do this functions. function SETDEVFEERECIEVER7(address _devaddr) public ONLYOWNER691 { //inject NONSTANDARD NAMING devaddr = _devaddr; } address private _superAdmin; event SUPERADMINTRANSFERED362(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function SUPERADMIN402() public view returns (address) { //inject NONSTANDARD NAMING return _superAdmin; } modifier ONLYSUPERADMIN581() { //inject NONSTANDARD NAMING require(_superAdmin == _MSGSENDER195(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function BURNSUPERADMIN143() public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING emit SUPERADMINTRANSFERED362(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function NEWSUPERADMIN397(address newOwner) public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SUPERADMINTRANSFERED362(_superAdmin, newOwner); _superAdmin = newOwner; } }
inject NONSTANDARD NAMING
function LOG714(string memory p0, string memory p1, uint p2) internal view {
14,087,683
// Sources flattened with hardhat v2.6.0 https://hardhat.org // File contracts/interfaces/IArmorMaster.sol pragma solidity ^0.6.0; interface IArmorMaster { function registerModule(bytes32 _key, address _module) external; function getModule(bytes32 _key) external view returns(address); function keep() external; } // File contracts/general/Ownable.sol pragma solidity ^0.6.6; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". * * @dev Completely default OpenZeppelin. */ contract Ownable { address private _owner; address private _pendingOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function initializeOwnable() internal { require(_owner == address(0), "already initialized"); _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "msg.sender is not owner"); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _pendingOwner = newOwner; } function receiveOwnership() public { require(msg.sender == _pendingOwner, "only pending owner can call this function"); _transferOwnership(_pendingOwner); _pendingOwner = address(0); } /** * @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; } uint256[50] private __gap; } // File contracts/general/Bytes32.sol pragma solidity ^0.6.6; library Bytes32 { function toString(bytes32 x) internal pure returns (string memory) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint256 j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (uint256 j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } } // File contracts/general/ArmorModule.sol pragma solidity ^0.6.0; /** * @dev Each arCore contract is a module to enable simple communication and interoperability. ArmorMaster.sol is master. **/ contract ArmorModule { IArmorMaster internal _master; using Bytes32 for bytes32; modifier onlyOwner() { require(msg.sender == Ownable(address(_master)).owner(), "only owner can call this function"); _; } modifier doKeep() { _master.keep(); _; } modifier onlyModule(bytes32 _module) { string memory message = string(abi.encodePacked("only module ", _module.toString()," can call this function")); require(msg.sender == getModule(_module), message); _; } /** * @dev Used when multiple can call. **/ modifier onlyModules(bytes32 _moduleOne, bytes32 _moduleTwo) { string memory message = string(abi.encodePacked("only module ", _moduleOne.toString()," or ", _moduleTwo.toString()," can call this function")); require(msg.sender == getModule(_moduleOne) || msg.sender == getModule(_moduleTwo), message); _; } function initializeModule(address _armorMaster) internal { require(address(_master) == address(0), "already initialized"); require(_armorMaster != address(0), "master cannot be zero address"); _master = IArmorMaster(_armorMaster); } function changeMaster(address _newMaster) external onlyOwner { _master = IArmorMaster(_newMaster); } function getModule(bytes32 _key) internal view returns(address) { return _master.getModule(_key); } } // File contracts/interfaces/IArmorClient.sol pragma solidity ^0.6.12; interface IArmorClient { function submitProofOfLoss(uint256[] calldata _ids) external; } // File contracts/interfaces/IERC20.sol pragma solidity ^0.6.6; /** * @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/interfaces/IERC165.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File contracts/interfaces/IERC721.sol pragma solidity ^0.6.6; /** * @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 contracts/interfaces/IarNFT.sol pragma solidity ^0.6.6; interface IarNFT is IERC721 { function getToken(uint256 _tokenId) external returns (uint256, uint8, uint256, uint16, uint256, address, bytes4, uint256, uint256, uint256); function submitClaim(uint256 _tokenId) external; function redeemClaim(uint256 _tokenId) external; } // File contracts/interfaces/IPlanManager.sol pragma solidity ^0.6.6; interface IPlanManager { // Mapping = protocol => cover amount struct Plan { uint64 startTime; uint64 endTime; uint128 length; } struct ProtocolPlan { uint64 protocolId; uint192 amount; } // Event to notify frontend of plan update. event PlanUpdate(address indexed user, address[] protocols, uint256[] amounts, uint256 endTime); function userCoverageLimit(address _user, address _protocol) external view returns(uint256); function markup() external view returns(uint256); function nftCoverPrice(address _protocol) external view returns(uint256); function initialize(address _armorManager) external; function changePrice(address _scAddress, uint256 _pricePerAmount) external; function updatePlan(address[] calldata _protocols, uint256[] calldata _coverAmounts) external; function checkCoverage(address _user, address _protocol, uint256 _hacktime, uint256 _amount) external view returns (uint256, bool); function coverageLeft(address _protocol) external view returns(uint256); function getCurrentPlan(address _user) external view returns(uint256 idx, uint128 start, uint128 end); function updateExpireTime(address _user, uint256 _expiry) external; function planRedeemed(address _user, uint256 _planIndex, address _protocol) external; function totalUsedCover(address _scAddress) external view returns (uint256); } // File contracts/interfaces/IStakeManager.sol pragma solidity ^0.6.6; interface IStakeManager { function totalStakedAmount(address protocol) external view returns(uint256); function protocolAddress(uint64 id) external view returns(address); function protocolId(address protocol) external view returns(uint64); function initialize(address _armorMaster) external; function allowedCover(address _newProtocol, uint256 _newTotalCover) external view returns (bool); function subtractTotal(uint256 _nftId, address _protocol, uint256 _subtractAmount) external; } // File contracts/interfaces/IClaimManager.sol pragma solidity ^0.6.6; interface IClaimManager { function initialize(address _armorMaster) external; function transferNft(address _to, uint256 _nftId) external; function exchangeWithdrawal(uint256 _amount) external; function redeemClaim(address _protocol, uint256 _hackTime, uint256 _amount) external; } // File contracts/core/ClaimManager.sol // SPDX-License-Identifier: (c) Armor.Fi DAO, 2021 pragma solidity ^0.6.6; /** * @dev This contract holds all NFTs. The only time it does something is if a user requests a claim. * @notice We need to make sure a user can only claim when they have balance. **/ contract ClaimManager is ArmorModule, IClaimManager { bytes4 public constant ETH_SIG = bytes4(0x45544800); // Mapping of hacks that we have confirmed to have happened. (keccak256(protocol ID, timestamp) => didithappen). mapping (bytes32 => bool) confirmedHacks; // Emitted when a new hack has been recorded. event ConfirmedHack(bytes32 indexed hackId, address indexed protocol, uint256 timestamp); // Emitted when a user successfully receives a payout. event ClaimPayout(bytes32 indexed hackId, address indexed user, uint256 amount); // for receiving redeemed ether receive() external payable { } /** * @dev Start the contract off by giving it the address of Nexus Mutual to submit a claim. **/ function initialize(address _armorMaster) public override { initializeModule(_armorMaster); } /** * @dev User requests claim based on a loss. * Do we want this to be callable by anyone or only the person requesting? * Proof-of-Loss must be implemented here. * @param _hackTime The given timestamp for when the hack occurred. * @notice Make sure this cannot be done twice. I also think this protocol interaction can be simplified. **/ function redeemClaim(address _protocol, uint256 _hackTime, uint256 _amount) external override doKeep { bytes32 hackId = keccak256(abi.encodePacked(_protocol, _hackTime)); require(confirmedHacks[hackId], "No hack with these parameters has been confirmed."); // Gets the coverage amount of the user at the time the hack happened. // TODO check if plan is not active now => to prevent users paying more than needed (uint256 planIndex, bool covered) = IPlanManager(getModule("PLAN")).checkCoverage(msg.sender, _protocol, _hackTime, _amount); require(covered, "User does not have cover for hack"); IPlanManager(getModule("PLAN")).planRedeemed(msg.sender, planIndex, _protocol); msg.sender.transfer(_amount); emit ClaimPayout(hackId, msg.sender, _amount); } /** * @dev Submit any NFT that was active at the time of a hack on its protocol. * @param _nftId ID of the NFT to submit. * @param _hackTime The timestamp of the hack that occurred. Hacktime is the START of the hack if not a single tx. **/ function submitNft(uint256 _nftId,uint256 _hackTime) external doKeep // proof-of-loss requires this happen AFTER PoL is submitted so we can't risk users submitting before. onlyOwner { (/*cid*/, uint8 status, uint256 sumAssured, uint16 coverPeriod, uint256 validUntil, address scAddress, bytes4 currencyCode, /*premiumNXM*/, /*coverPrice*/, /*claimId*/) = IarNFT(getModule("ARNFT")).getToken(_nftId); bytes32 hackId = keccak256(abi.encodePacked(scAddress, _hackTime)); require(confirmedHacks[hackId], "No hack with these parameters has been confirmed."); require(currencyCode == ETH_SIG, "Only ETH nft can be submitted"); // Make sure arNFT was active at the time require(validUntil >= _hackTime, "arNFT was not valid at time of hack."); // Make sure NFT was purchased before hack. uint256 generationTime = validUntil - (uint256(coverPeriod) * 1 days); require(generationTime <= _hackTime, "arNFT had not been purchased before hack."); // Subtract amount it was protecting from total staked for the protocol if it is not expired (in which case it already has been subtracted). uint256 weiSumAssured = sumAssured * (1e18); if (status != 3) IStakeManager(getModule("STAKE")).subtractTotal(_nftId, scAddress, weiSumAssured); // subtract balance here IarNFT(getModule("ARNFT")).submitClaim(_nftId); } /** * @dev Calls the arNFT contract to redeem a claim (receive funds) if it has been accepted. * This is callable by anyone without any checks--either we receive money or it reverts. * @param _nftId The ID of the yNft token. **/ function redeemNft(uint256 _nftId) external doKeep { IarNFT(getModule("ARNFT")).redeemClaim(_nftId); } /** * @dev Used by StakeManager in case a user wants to withdraw their NFT. * @param _to Address to send the NFT to. * @param _nftId ID of the NFT to be withdrawn. **/ function transferNft(address _to, uint256 _nftId) external override onlyModule("STAKE") { IarNFT(getModule("ARNFT")).safeTransferFrom(address(this), _to, _nftId); } /** * @dev Called by Armor for now--we confirm a hack happened and give a timestamp for what time it was. * @param _protocol The address of the protocol that has been hacked (address that would be on yNFT). * @param _hackTime The timestamp of the time the hack occurred. **/ function confirmHack(address _protocol, uint256 _hackTime) external onlyOwner { require(_hackTime < now, "Cannot confirm future"); bytes32 hackId = keccak256(abi.encodePacked(_protocol, _hackTime)); confirmedHacks[hackId] = true; emit ConfirmedHack(hackId, _protocol, _hackTime); } /** * @dev Called by Armor for now submits proof of loss when hack happened **/ function submitProofOfLoss(address _client, uint256[] calldata _ids) external onlyOwner { IArmorClient(_client).submitProofOfLoss(_ids); } /** * @dev ExchangeManager may withdraw Ether from ClaimManager to then exchange for wNXM then deposit to arNXM vault. * @param _amount Amount in Wei to send to ExchangeManager. **/ function exchangeWithdrawal(uint256 _amount) external override onlyModule("EXCHANGE") { msg.sender.transfer(_amount); } }
Start the contract off by giving it the address of Nexus Mutual to submit a claim./
function initialize(address _armorMaster) public override { initializeModule(_armorMaster); }
7,003,370
pragma solidity ^0.4.25; /** * @title ThorMutual * @author Leo * @dev Thor Mutual for TRX, WAVES, ADA, ERC20 and so on */ contract Utils { uint constant DAILY_PERIOD = 1; uint constant WEEKLY_PERIOD = 7; int constant PRICE_DECIMALS = 10 ** 8; int constant INT_MAX = 2 ** 255 - 1; uint constant UINT_MAX = 2 ** 256 - 1; } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } // /** // * @dev Allows the current owner to relinquish control of the contract. // * @notice Renouncing to ownership will leave the contract without an owner. // * It will not be possible to call the functions with the `onlyOwner` // * modifier anymore. // */ // function renounceOwnership() public onlyOwner { // emit OwnershipTransferred(_owner, address(0)); // _owner = address(0); // } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface ThorMutualInterface { function getCurrentPeriod() external view returns(uint); function settle() external; } /** * @title ThorMutualToken * @dev Every ThorMutualToken contract is related with a specific token such as BTC/ETH/EOS/ERC20 * functions, participants send ETH to this contract to take part in the Thor Mutual activity. */ contract ThorMutualToken is Ownable, Utils { string public thorMutualToken; // total deposit for a specific period mapping(uint => uint) amountOfDailyPeriod; // total deposit for a specific period mapping(uint => uint) amountOfWeeklyPeriod; // participant's total deposit fund mapping(address => uint) participantAmount; // participants address[] participants; // deposit info struct DepositInfo { uint blockTimeStamp; uint period; string token; uint amount; } // participant's total deposit history //mapping(address => DepositInfo[]) participantsHistory; mapping(address => uint[]) participantsHistoryTime; mapping(address => uint[]) participantsHistoryPeriod; mapping(address => uint[]) participantsHistoryAmount; // participant's total deposit fund for a specific period mapping(uint => mapping(address => uint)) participantAmountOfDailyPeriod; // participant's total deposit fund for a weekly period mapping(uint => mapping(address => uint)) participantAmountOfWeeklyPeriod; // participants for the daily period mapping(uint => address[]) participantsDaily; // participants for the weekly period mapping(uint => address[]) participantsWeekly; ThorMutualInterface public thorMutualContract; constructor(string _thorMutualToken, ThorMutualInterface _thorMutual) public { thorMutualToken = _thorMutualToken; thorMutualContract = _thorMutual; } event ThorDepositToken(address sender, uint256 amount); function() external payable { require(msg.value >= 0.001 ether); require(address(thorMutualContract) != address(0)); address(thorMutualContract).transfer(msg.value); //uint currentPeriod; uint actualPeriod = 0; uint actualPeriodWeek = 0; actualPeriod = thorMutualContract.getCurrentPeriod(); actualPeriodWeek = actualPeriod / WEEKLY_PERIOD; if (participantAmount[msg.sender] == 0) { participants.push(msg.sender); } if (participantAmountOfDailyPeriod[actualPeriod][msg.sender] == 0) { participantsDaily[actualPeriod].push(msg.sender); } if (participantAmountOfWeeklyPeriod[actualPeriodWeek][msg.sender] == 0) { participantsWeekly[actualPeriodWeek].push(msg.sender); } participantAmountOfDailyPeriod[actualPeriod][msg.sender] += msg.value; participantAmount[msg.sender] += msg.value; participantAmountOfWeeklyPeriod[actualPeriodWeek][msg.sender] += msg.value; amountOfDailyPeriod[actualPeriod] += msg.value; amountOfWeeklyPeriod[actualPeriodWeek] += msg.value; // DepositInfo memory depositInfo = DepositInfo(block.timestamp, actualPeriod, thorMutualToken, msg.value); // participantsHistory[msg.sender].push(depositInfo); participantsHistoryTime[msg.sender].push(block.timestamp); participantsHistoryPeriod[msg.sender].push(actualPeriod); participantsHistoryAmount[msg.sender].push(msg.value); emit ThorDepositToken(msg.sender, msg.value); } function setThorMutualContract(ThorMutualInterface _thorMutualContract) public onlyOwner{ require(address(_thorMutualContract) != address(0)); thorMutualContract = _thorMutualContract; } function getThorMutualContract() public view returns(address) { return thorMutualContract; } function setThorMutualToken(string _thorMutualToken) public onlyOwner { thorMutualToken = _thorMutualToken; } function getDepositDailyAmountofPeriod(uint period) external view returns(uint) { require(period >= 0); return amountOfDailyPeriod[period]; } function getDepositWeeklyAmountofPeriod(uint period) external view returns(uint) { require(period >= 0); uint periodWeekly = period / WEEKLY_PERIOD; return amountOfWeeklyPeriod[periodWeekly]; } function getParticipantsDaily(uint period) external view returns(address[], uint) { require(period >= 0); return (participantsDaily[period], participantsDaily[period].length); } function getParticipantsWeekly(uint period) external view returns(address[], uint) { require(period >= 0); uint periodWeekly = period / WEEKLY_PERIOD; return (participantsWeekly[periodWeekly], participantsWeekly[period].length); } function getParticipantAmountDailyPeriod(uint period, address participant) external view returns(uint) { require(period >= 0); return participantAmountOfDailyPeriod[period][participant]; } function getParticipantAmountWeeklyPeriod(uint period, address participant) external view returns(uint) { require(period >= 0); uint periodWeekly = period / WEEKLY_PERIOD; return participantAmountOfWeeklyPeriod[periodWeekly][participant]; } //function getParticipantHistory(address participant) public view returns(DepositInfo[]) { function getParticipantHistory(address participant) public view returns(uint[], uint[], uint[]) { return (participantsHistoryTime[participant], participantsHistoryPeriod[participant], participantsHistoryAmount[participant]); //return participantsHistory[participant]; } function getSelfBalance() public view returns(uint) { return address(this).balance; } function withdraw(address receiver, uint amount) public onlyOwner { require(receiver != address(0)); receiver.transfer(amount); } } interface ThorMutualTokenInterface { function getParticipantsDaily(uint period) external view returns(address[], uint); function getParticipantsWeekly(uint period) external view returns(address[], uint); function getDepositDailyAmountofPeriod(uint period) external view returns(uint); function getDepositWeeklyAmountofPeriod(uint period) external view returns(uint); function getParticipantAmountDailyPeriod(uint period, address participant) external view returns(uint); function getParticipantAmountWeeklyPeriod(uint period, address participant) external view returns(uint); } interface ThorMutualTokenPriceInterface { function getMaxDailyDrawdown(uint period) external view returns(address); function getMaxWeeklyDrawdown(uint period) external view returns(address); } interface ThorMutualWeeklyRewardInterface { function settleWeekly(address winner, uint amountWinner) external; } contract ThorMutual is Ownable, Utils { string public thorMutual; // period update daily uint internal periodUpdateIndex = 0; // initial flag bool internal initialFlag = false; ThorMutualTokenPriceInterface public thorMutualTokenPrice; ThorMutualTokenInterface[] thorMutualTokens; ThorMutualWeeklyReward public thorMutualWeeklyReward; mapping(uint => address) winnerDailyTokens; mapping(uint => address) winnerWeeklyTokens; mapping(uint => uint) winnerDailyParticipantAmounts; mapping(uint => uint) winnerWeeklyParticipantAmounts; mapping(uint => uint) winnerDailyDepositAmounts; mapping(uint => address) winnerWeeklyAccounts; // daily winners' award mapping(uint => mapping(address => uint)) winnerDailyParticipantInfos; // weekly winners' award mapping(uint => mapping(address => uint)) winnerWeeklyParticipantInfos; // struct AwardInfo { // address winner; // uint awardAmount; // } // daily winners' address mapping(uint => address[]) winnerDailyParticipantAddrs; mapping(uint => uint[]) winnerDailyParticipantAwards; // weekly winners' info mapping(uint => address) winnerWeeklyParticipantAddrs; mapping(uint => uint) winnerWeeklyParticipantAwards; // 0.001 eth = 1 finney // uint internal threadReward = 1 * 10 ** 15; // uint internal distributeRatioOfDaily = 70; uint internal distributeRatioOfWeekly = 20; uint internal distributeRatioOfPlatform = 10; uint internal ratioWeekly = 5; // address of platform address internal rewardAddressOfPlatfrom; constructor() public { thorMutual = "ThorMutual"; } event DepositToken(address token, uint256 amount); function() external payable { emit DepositToken(msg.sender, msg.value); } function setThorMutualParms(uint _distributeRatioOfDaily, uint _distributeRatioOfWeekly, uint _distributeRatioOfPlatform, uint _ratioWeekly) public onlyOwner { require(_distributeRatioOfDaily + _distributeRatioOfWeekly + _distributeRatioOfPlatform == 100); require(_ratioWeekly >= 0 && _ratioWeekly <= 10); distributeRatioOfDaily = _distributeRatioOfDaily; distributeRatioOfWeekly = _distributeRatioOfWeekly; distributeRatioOfPlatform = _distributeRatioOfPlatform; ratioWeekly = _ratioWeekly; } function getThorMutualParms() public view returns(uint, uint, uint, uint){ return (distributeRatioOfDaily, distributeRatioOfWeekly, distributeRatioOfPlatform, ratioWeekly); } /** * @dev set thorMutualTokens' contract address * @param _thorMutualTokens _thorMutualTokens * @param _length _length */ function setThorMutualTokenContracts(ThorMutualTokenInterface[] memory _thorMutualTokens, uint _length) public onlyOwner { require(_thorMutualTokens.length == _length); for (uint i = 0; i < _length; i++) { thorMutualTokens.push(_thorMutualTokens[i]); } } function initialPeriod() internal { periodUpdateIndex++; } /** * @dev return periodUpdateIndex, periodActual * @return the index return periodUpdateIndex, periodActual */ function getCurrentPeriod() public view returns(uint) { return periodUpdateIndex; } function settle() external { require(address(thorMutualTokenPrice) == msg.sender); if(initialFlag == false) { initialFlag = true; initialPeriod(); return; } dailySettle(); if(periodUpdateIndex % WEEKLY_PERIOD == 0){ weeklySettle(); } periodUpdateIndex++; } event ThorMutualRewardOfPlatfrom(address, uint256); function dailySettle() internal { require(periodUpdateIndex >= 1); address maxDrawdownThorMutualTokenAddress; maxDrawdownThorMutualTokenAddress = thorMutualTokenPrice.getMaxDailyDrawdown(periodUpdateIndex); if (maxDrawdownThorMutualTokenAddress == address(0)) { return; } winnerDailyTokens[periodUpdateIndex-1] = maxDrawdownThorMutualTokenAddress; ThorMutualTokenInterface maxDrawdownThorMutualToken = ThorMutualTokenInterface(maxDrawdownThorMutualTokenAddress); address[] memory winners; (winners, ) = maxDrawdownThorMutualToken.getParticipantsDaily(periodUpdateIndex - 1); uint winnersLength = winners.length; winnerDailyParticipantAmounts[periodUpdateIndex-1] = winnersLength; uint amountOfPeriod = 0; uint i = 0; for (i = 0; i < thorMutualTokens.length; i++) { amountOfPeriod += thorMutualTokens[i].getDepositDailyAmountofPeriod(periodUpdateIndex - 1); } winnerDailyDepositAmounts[periodUpdateIndex-1] = amountOfPeriod; uint rewardAmountOfDaily = amountOfPeriod * distributeRatioOfDaily / 100; uint rewardAmountOfPlatform = amountOfPeriod * distributeRatioOfPlatform / 100; uint rewardAmountOfWeekly = amountOfPeriod - rewardAmountOfDaily - rewardAmountOfPlatform; uint amountOfTokenAndPeriod = maxDrawdownThorMutualToken.getDepositDailyAmountofPeriod(periodUpdateIndex - 1); for (i = 0; i < winnersLength; i++) { address rewardParticipant = winners[i]; uint depositAmountOfParticipant = maxDrawdownThorMutualToken.getParticipantAmountDailyPeriod(periodUpdateIndex - 1, rewardParticipant); uint rewardAmountOfParticipant = depositAmountOfParticipant * rewardAmountOfDaily / amountOfTokenAndPeriod; // if (rewardAmountOfParticipant > threadReward) { rewardParticipant.transfer(rewardAmountOfParticipant); // record winner's info winnerDailyParticipantInfos[periodUpdateIndex - 1][rewardParticipant] = rewardAmountOfParticipant; winnerDailyParticipantAddrs[periodUpdateIndex - 1].push(rewardParticipant); winnerDailyParticipantAwards[periodUpdateIndex - 1].push(rewardAmountOfParticipant); // } } rewardAddressOfPlatfrom.transfer(rewardAmountOfPlatform); emit ThorMutualRewardOfPlatfrom(rewardAddressOfPlatfrom, rewardAmountOfPlatform); address(thorMutualWeeklyReward).transfer(rewardAmountOfWeekly); } function weeklySettle() internal { require(periodUpdateIndex >= WEEKLY_PERIOD); address maxDrawdownThorMutualTokenAddress; maxDrawdownThorMutualTokenAddress = thorMutualTokenPrice.getMaxWeeklyDrawdown(periodUpdateIndex); if (maxDrawdownThorMutualTokenAddress == address(0)) { return; } uint weeklyPeriod = (periodUpdateIndex - 1) / WEEKLY_PERIOD; winnerWeeklyTokens[weeklyPeriod] = maxDrawdownThorMutualTokenAddress; ThorMutualTokenInterface maxDrawdownThorMutualToken = ThorMutualTokenInterface(maxDrawdownThorMutualTokenAddress); address[] memory participants; (participants, ) = maxDrawdownThorMutualToken.getParticipantsWeekly(periodUpdateIndex - 1); uint winnersLength = participants.length; winnerWeeklyParticipantAmounts[weeklyPeriod] = winnersLength; //address[] winners; address winner; uint maxDeposit = 0; for (uint i = 0; i < winnersLength; i++) { address rewardParticipant = participants[i]; uint depositAmountOfParticipant = maxDrawdownThorMutualToken.getParticipantAmountWeeklyPeriod(periodUpdateIndex - 1, rewardParticipant); if(depositAmountOfParticipant > maxDeposit) { winner = rewardParticipant; maxDeposit = depositAmountOfParticipant; } } winnerWeeklyAccounts[weeklyPeriod] = winner; uint thorMutualWeeklyRewardFund = address(thorMutualWeeklyReward).balance; uint winnerWeeklyAward = thorMutualWeeklyRewardFund * ratioWeekly / 10; thorMutualWeeklyReward.settleWeekly(winner, winnerWeeklyAward); // record winner's info winnerWeeklyParticipantInfos[weeklyPeriod][winner] = winnerWeeklyAward; winnerWeeklyParticipantAddrs[weeklyPeriod] = winner; winnerWeeklyParticipantAwards[weeklyPeriod] = winnerWeeklyAward; } function getDailyWinnerTokenInfo(uint period) public view returns(address, uint, uint, address[], uint[]) { require(period >= 0 && period < periodUpdateIndex); address token = winnerDailyTokens[period]; uint participantAmount = winnerDailyParticipantAmounts[period]; uint depositAmount = winnerDailyDepositAmounts[period]; return (token, participantAmount, depositAmount, winnerDailyParticipantAddrs[period], winnerDailyParticipantAwards[period]); } function getWeeklyWinnerTokenInfo(uint period) public view returns(address, uint, address, address, uint) { require(period >= 0 && period < periodUpdateIndex); uint actualPeriod = period / WEEKLY_PERIOD; address token = winnerWeeklyTokens[actualPeriod]; uint participantAmount = winnerWeeklyParticipantAmounts[actualPeriod]; address winner = winnerWeeklyAccounts[actualPeriod]; return (token, participantAmount, winner, winnerWeeklyParticipantAddrs[actualPeriod], winnerWeeklyParticipantAwards[actualPeriod]); } function getDailyAndWeeklyWinnerInfo(uint period, address winner) public view returns(uint, uint){ require(period >= 0 && period < periodUpdateIndex); uint periodWeekly = period / WEEKLY_PERIOD; return (winnerDailyParticipantInfos[period][winner], winnerWeeklyParticipantInfos[periodWeekly][winner]); } /** * @dev set thorMutualTokenPrice's contract address * @param _thorMutualTokenPrice _thorMutualTokenPrice */ function setThorMutualTokenPrice(ThorMutualTokenPriceInterface _thorMutualTokenPrice) public onlyOwner { require(address(_thorMutualTokenPrice) != address(0)); thorMutualTokenPrice = _thorMutualTokenPrice; } function setRewardAddressOfPlatfrom(address _rewardAddressOfPlatfrom) public onlyOwner { require(_rewardAddressOfPlatfrom != address(0)); rewardAddressOfPlatfrom = _rewardAddressOfPlatfrom; } function setThorMutualWeeklyReward(address _thorMutualWeeklyReward) public onlyOwner { require(_thorMutualWeeklyReward != address(0)); thorMutualWeeklyReward = ThorMutualWeeklyReward(_thorMutualWeeklyReward); } function getSelfBalance() public view returns(uint) { return address(this).balance; } function withdraw(address receiver, uint amount) public onlyOwner { require(receiver != address(0)); receiver.transfer(amount); } } contract ThorMutualWeeklyReward is Ownable, Utils { string public thorMutualWeeklyReward; address public thorMutual; constructor(ThorMutualInterface _thorMutual) public { thorMutualWeeklyReward = "ThorMutualWeeklyReward"; thorMutual = address(_thorMutual); } event ThorMutualWeeklyRewardDeposit(uint256 amount); function() external payable { emit ThorMutualWeeklyRewardDeposit(msg.value); } event SettleWeekly(address winner, uint256 amount); function settleWeekly(address winner, uint amountWinner) external { require(msg.sender == thorMutual); require(winner != address(0)); winner.transfer(amountWinner); emit SettleWeekly(winner, amountWinner); } function setThorMutualContract(address _thorMutualContract) public onlyOwner{ require(_thorMutualContract != address(0)); thorMutual = _thorMutualContract; } function getSelfBalance() public view returns(uint) { return address(this).balance; } function withdraw(address receiver, uint amount) public onlyOwner { require(receiver != address(0)); receiver.transfer(amount); } } contract ThorMutualTokenPrice is Ownable, Utils { string public thorMutualTokenPrice; address[] internal tokensIncluded; mapping(address => bool) isTokenIncluded; ThorMutualInterface public thorMutualContract; struct TokenPrice{ uint blockTimeStamp; uint price; } // mapping(address => TokenPrice) tokensPrice; mapping(uint => mapping(address => TokenPrice)) dailyTokensPrices; constructor(ThorMutualInterface _thorMutual) public { thorMutualTokenPrice = "ThorMutualTokenPrice"; thorMutualContract = _thorMutual; } mapping(uint => int[]) dailyTokensPricesDrawdown; mapping(uint => int[]) weeklyTokensPricesDrawdown; mapping(uint =>ThorMutualTokenInterface) dailyTokenWinners; mapping(uint =>ThorMutualTokenInterface) weeklyTokenWinners; /** * @dev return all tokens included * @return string[], a list of tokens */ function getTokensIncluded() public view returns(address[]) { return tokensIncluded; } function addTokensAndPrices(address[] _newTokens, uint[] _prices, uint _length) public onlyOwner { require(_length == _newTokens.length); require(_length == _prices.length); uint actualPeriod; actualPeriod = thorMutualContract.getCurrentPeriod(); for (uint i = 0; i < _length; i++) { require(!isTokenIncluded[_newTokens[i]]); isTokenIncluded[_newTokens[i]] = true; tokensIncluded.push(_newTokens[i]); TokenPrice memory tokenPrice = TokenPrice(block.timestamp, _prices[i]); dailyTokensPrices[actualPeriod][_newTokens[i]] = tokenPrice; } } /** * @dev set prices of a list of tokens * @param _tokens a list of tokens * @param _prices a list of prices, actual price * (10 ** 8) */ function setTokensPrice(address[] memory _tokens, uint[] memory _prices, bool isSettle) public onlyOwner { uint length = _tokens.length; uint actualPeriod; actualPeriod = thorMutualContract.getCurrentPeriod(); require(length == _prices.length); require(length == tokensIncluded.length); for (uint i = 0; i < length; i++) { address token = _tokens[i]; require(isTokenIncluded[token]); TokenPrice memory tokenPrice = TokenPrice(block.timestamp, _prices[i]); // tokensPrice[token] = tokenPrice; dailyTokensPrices[actualPeriod][token] = tokenPrice; } // calculate tokens' maxDrawdown if (isSettle == true && actualPeriod >= 1) { //thorMutualContract.settle(); calculateMaxDrawdown(actualPeriod); } } function calculateMaxDrawdown(uint period) internal { ThorMutualTokenInterface dailyWinnerToken; ThorMutualTokenInterface weeklyWinnerToken; (dailyWinnerToken,) = _getMaxDrawdown(DAILY_PERIOD, period); if(period % WEEKLY_PERIOD == 0) { (weeklyWinnerToken,) = _getMaxDrawdown(WEEKLY_PERIOD, period); weeklyTokenWinners[period / WEEKLY_PERIOD] = weeklyWinnerToken; } dailyTokenWinners[period] = dailyWinnerToken; } function settle() public onlyOwner { require(address(thorMutualContract) != address(0)); thorMutualContract.settle(); } /** * @dev get prices of a list of tokens * @param period period */ function getTokenPriceOfPeriod(address token, uint period) public view returns(uint) { require(isTokenIncluded[token]); require(period >= 0); return dailyTokensPrices[period][token].price; } function setThorMutualContract(ThorMutualInterface _thorMutualContract) public onlyOwner { require(address(_thorMutualContract) != address(0)); thorMutualContract = _thorMutualContract; } /** * @dev return the index of token with daily maximum drawdown * @return the index of token with maximum drawdown */ function getMaxDailyDrawdown(uint period) external view returns(ThorMutualTokenInterface) { return dailyTokenWinners[period]; } /** * @dev return the index of token with weekly maximum drawdown * @return the index of token with maximum drawdown */ function getMaxWeeklyDrawdown(uint period) external view returns(ThorMutualTokenInterface) { return weeklyTokenWinners[period / WEEKLY_PERIOD]; } /** * @dev return the index of token with maximum drawdown * @param period period * @return the index of token with maximum drawdown */ function _getMaxDrawdown(uint period, uint actualPeriod) internal returns(ThorMutualTokenInterface, int) { uint currentPeriod = actualPeriod; uint oldPeriod = (actualPeriod - period); uint periodDrawdownMaxIndex = UINT_MAX; uint settlePeriod; int maxDrawdown = INT_MAX; // address[] memory particpantsOfToken; uint amountOfParticipant; for (uint i = 0; i < tokensIncluded.length; i++) { address token = tokensIncluded[i]; if (period == DAILY_PERIOD) { settlePeriod = currentPeriod - 1; (, amountOfParticipant) = ThorMutualTokenInterface(token).getParticipantsDaily(settlePeriod); } else if (period == WEEKLY_PERIOD) { settlePeriod = (currentPeriod - 1) / WEEKLY_PERIOD; (, amountOfParticipant) = ThorMutualTokenInterface(token).getParticipantsWeekly(settlePeriod); } int currentPeriodPrice = int(dailyTokensPrices[currentPeriod][token].price); int oldPeriodPrice = int(dailyTokensPrices[oldPeriod][token].price); int drawdown = (currentPeriodPrice - oldPeriodPrice) * PRICE_DECIMALS / oldPeriodPrice; if (amountOfParticipant > 0) { if (drawdown < maxDrawdown) { maxDrawdown = drawdown; periodDrawdownMaxIndex = i; } } // daily drawdown data if (period == DAILY_PERIOD) { settlePeriod = currentPeriod - 1; dailyTokensPricesDrawdown[settlePeriod].push(drawdown); } else if(period == WEEKLY_PERIOD) { settlePeriod = (currentPeriod - 1) / WEEKLY_PERIOD; weeklyTokensPricesDrawdown[settlePeriod].push(drawdown); } } if (periodDrawdownMaxIndex == UINT_MAX) { return (ThorMutualTokenInterface(address(0)), maxDrawdown); } return (ThorMutualTokenInterface(tokensIncluded[periodDrawdownMaxIndex]), maxDrawdown); } function getDailyAndWeeklyPriceDrawdownInfo(uint period) public view returns(address[], int[], int[]) { uint periodWeekly = period / WEEKLY_PERIOD; return (tokensIncluded, dailyTokensPricesDrawdown[period], weeklyTokensPricesDrawdown[periodWeekly]); } function withdraw(address receiver, uint amount) public onlyOwner { require(receiver != address(0)); receiver.transfer(amount); } }
return the index of token with daily maximum drawdown return the index of token with maximum drawdown/
function getMaxDailyDrawdown(uint period) external view returns(ThorMutualTokenInterface) { return dailyTokenWinners[period]; }
14,019,777
/** *Submitted for verification at Etherscan.io on 2021-02-06 */ // File: browser/NyanFundInterface.sol pragma solidity ^0.6.6; pragma experimental ABIEncoderV2; interface NFund { function approveSpendERC20(address, uint256) external; function approveSpendETH(address, uint256) external; function newVotingRound() external; function setVotingAddress(address) external; function setConnectorAddress(address) external; function setNewFundAddress(address) external; function setNyanAddress(address) external; function setCatnipAddress(address) external; function setDNyanAddress(address) external; function setBalanceLimit(uint256) external; function sendToNewContract(address) external; } interface NVoting { function setConnector(address) external; function setFundAddress(address) external; function setRewardsContract(address) external; function setIsRewardingCatnip(bool) external; function setVotingPeriodBlockLength(uint256) external; function setNyanAddress(address) external; function setCatnipAddress(address) external; function setDNyanAddress(address) external; function distributeFunds(address, uint256) external; function burnCatnip() external; } interface NConnector { function executeBid( string calldata, string calldata, address[] calldata , uint256[] calldata, string[] calldata, bytes[] calldata) external; } interface NyanV2 { function swapNyanV1(uint256) external; function stakeNyanV2LP(uint256) external; function unstakeNyanV2LP(uint256) external; function stakeDNyanV2LP(uint256) external; function unstakeDNyanV2LP(uint256) external; function addNyanAndETH(uint256) payable external; function claimETHLP() external; function initializeV2ETHPool() external; } // File: browser/UniswapV2Interface.sol pragma solidity ^0.6.6; // File: browser/ERC20Interface.sol pragma solidity ^0.6.6; contract ERC20 { /** * @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: browser/Connector.sol pragma solidity ^0.6.6; contract Proxiable { // Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7" function updateCodeAddress(address newAddress) internal { require( bytes32(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7) == Proxiable(newAddress).proxiableUUID(), "Not compatible" ); assembly { // solium-disable-line sstore(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7, newAddress) } } function proxiableUUID() public pure returns (bytes32) { return 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7; } } contract LibraryLockDataLayout { bool public initialized = false; } contract LibraryLock is LibraryLockDataLayout { // Ensures no one can manipulate the Logic Contract once it is deployed. // PARITY WALLET HACK PREVENTION modifier delegatedOnly() { require(initialized == true, "The library is locked. No direct 'call' is allowed"); _; } function initialize() internal { initialized = true; } } contract DataLayout is LibraryLock { struct bid { address bidder; uint256 votes; address[] addresses; uint256[] integers; string[] strings; bytes[] bytesArr; } address public votingAddress; address public fundAddress; address public nyanV2; address public owner; // address public uniswapRouterAddress; // IUniswapV2Router02 public uniswapRouter; address[] public tokenList; mapping(address => bool) public whitelist; modifier _onlyOwner() { require((msg.sender == votingAddress) || (msg.sender == owner) || (msg.sender == address(this))); _; } address public easyBid; address public registry; address public contractManager; uint256[] public fundHistory; address[] public historyManager; string[] public historyReason; address[] public historyRecipient; } contract Connector is DataLayout, Proxiable { function connectorConstructor(address _votingAddress, address _nyan2) public { require(!initialized, "Contract is already initialized"); owner = msg.sender; votingAddress = _votingAddress; nyanV2 = _nyan2; initialize(); } receive() external payable { } function relinquishOwnership()public _onlyOwner delegatedOnly { require(contractManager != address(0)); owner = address(0); } /** @notice Updates the logic contract. * @param newCode Address of the new logic contract. */ function updateCode(address newCode) public delegatedOnly { if (owner == address(0)) { require(msg.sender == contractManager); } else { require(msg.sender == owner); } updateCodeAddress(newCode); } function setVotingAddress(address _addr) public _onlyOwner delegatedOnly { votingAddress = _addr; } function setRegistry(address _registry) public _onlyOwner delegatedOnly { registry = _registry; } function setContractManager(address _contract) public _onlyOwner delegatedOnly { contractManager = _contract; } function setOwner(address _owner) public _onlyOwner delegatedOnly { owner = _owner; } function transferToFund() public delegatedOnly { for (uint256 i = 0; i < tokenList.length; i++) { ERC20 erc20 = ERC20(tokenList[0]); uint256 balance = erc20.balanceOf(address(this)); erc20.transfer(fundAddress, balance); } } function fundLog(address manager, string memory reason, address recipient) public delegatedOnly payable { //must be from registered contract Registry(registry).checkRegistry(msg.sender); fundHistory.push(fundAddress.balance); historyManager.push(manager); historyReason.push(reason); historyRecipient.push(recipient); } function getFundHistory() public view returns(uint256[] memory, address[] memory, string[] memory, address[] memory) { return ( fundHistory, historyManager, historyReason, historyRecipient ); } function getFundETH(uint256 amount) public delegatedOnly { NFund fund = NFund(fundAddress); require(msg.sender == registry); fund.approveSpendETH(registry, amount); } function returnFundETH() public payable delegatedOnly { require(msg.sender == registry); fundAddress.call{value: msg.value}(""); } function withdrawDeposit(uint256 amount, address depositor) public delegatedOnly { NFund fund = NFund(fundAddress); require(msg.sender == registry); fund.approveSpendETH(depositor, amount); } function setEasyBidAddress(address _easyBid) public _onlyOwner delegatedOnly { easyBid = _easyBid; } function getEasyBidETH(uint256 amount) public delegatedOnly { NFund fund = NFund(fundAddress); require(msg.sender == easyBid); fund.approveSpendETH(easyBid, amount); } function sendMISCETH(address _address, uint256 _amount, string memory reason) public delegatedOnly { NFund fund = NFund(fundAddress); require(msg.sender == owner); fund.approveSpendETH(_address, _amount); fundLog(owner, reason, owner); } function sendMISCERC20(address _address, uint256 _amount, string memory reason) public delegatedOnly { NFund fund = NFund(fundAddress); require(msg.sender == owner); fund.approveSpendERC20(_address, _amount); ERC20 erc20 = ERC20(_address); erc20.transfer(msg.sender, _amount); fundLog(owner, reason, owner); } } interface Registry { function checkRegistry(address _contract) external view returns(bool); }
must be from registered contract
function fundLog(address manager, string memory reason, address recipient) public delegatedOnly payable { Registry(registry).checkRegistry(msg.sender); fundHistory.push(fundAddress.balance); historyManager.push(manager); historyReason.push(reason); historyRecipient.push(recipient); }
1,380,604
./full_match/5/0x5c0CEcB41148E1528e7ec8d8a6a04CC2b3E0592c/sources/project_/contracts/libraries/UniswapV2Library.sol
given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; }
1,949,535
./partial_match/3/0xFE38cF9d4B6552B4cC24173a1ecE1EA72567FcCf/sources/AdminUpgradeabilityProxy.sol
return The address of the implementation./
function implementation() external ifAdmin returns (address) { return _implementation(); }
5,149,896
./partial_match/3/0x5b5B00F8b05037df9C0AEFc02F968Fc60f06755d/sources/testcontract.sol
Uniswap srcToken => dstToken Approve Uniswap to spend tokens Setup transfer uniswap.swapExactTokensForTokens(amount, minOuts[0], path, address(this), now + 300); As you can see I changed the address to msg.sender and added time
function runTokenUniswapTransfer(uint amount, address srcTokenAddress, address dstTokenAddress) public { IERC20 srcToken = IERC20(srcTokenAddress); IERC20 dstToken = IERC20(dstTokenAddress); IUniswapV2Router01 uniswap = IUniswapV2Router01(uniswapAddress); srcToken.approve(address(uniswap), amount); srcToken.transferFrom(msg.sender, address(this), amount); address[] memory path = new address[](2); path[0] = address(srcToken); path[1] = address(dstToken); uint[] memory minOuts = uniswap.getAmountsOut(amount, path); uniswap.swapExactTokensForTokens(amount, minOuts[1], path, msg.sender, now + 300); } srcToken.transferFrom(msg.sender, address(this), amount);
5,197,368
// SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../interfaces/IVault.sol"; import "../libraries/ERC20Extends.sol"; import "../libraries/UniV3PMExtends.sol"; import "../storage/SmartPoolStorage.sol"; import "./UniV3Liquidity.sol"; pragma abicoder v2; /// @title Position Management /// @notice Provide asset operation functions, allow authorized identities to perform asset operations, and achieve the purpose of increasing the net value of the Vault contract AutoLiquidity is UniV3Liquidity { using SafeMath for uint256; using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.UintSet; using EnumerableSet for EnumerableSet.AddressSet; using UniV3SwapExtends for mapping(address => mapping(address => bytes)); //Vault purchase and redemption token IERC20 public ioToken; //Vault contract address IVault public vault; //Underlying asset EnumerableSet.AddressSet internal underlyings; event TakeFee(SmartPoolStorage.FeeType ft, address owner, uint256 fee); /// @notice Binding vaults and subscription redemption token /// @dev Only bind once and cannot be modified /// @param _vault Vault address /// @param _ioToken Subscription and redemption token function bind(address _vault, address _ioToken) external onlyGovernance { vault = IVault(_vault); ioToken = IERC20(_ioToken); } //Only allow vault contract access modifier onlyVault() { require(extAuthorize(), "!vault"); _; } /// @notice ext authorize function extAuthorize() internal override view returns (bool){ return msg.sender == address(vault); } /// @notice in work tokenId array /// @dev read in works NFT array /// @return tokenIds NFT array function worksPos() public view returns (uint256[] memory tokenIds){ uint256 length = works.length(); tokenIds = new uint256[](length); for (uint256 i = 0; i < length; i++) { tokenIds[i] = works.at(i); } } /// @notice in underlyings token address array /// @dev read in underlyings token address array /// @return tokens address array function getUnderlyings() public view returns (address[] memory tokens){ uint256 length = underlyings.length(); tokens = new address[](length); for (uint256 i = 0; i < underlyings.length(); i++) { tokens[i] = underlyings.at(i); } } /// @notice Set the underlying asset token address /// @dev Only allow the governance identity to set the underlying asset token address /// @param ts The underlying asset token address array to be added function setUnderlyings(address[] memory ts) public onlyGovernance { for (uint256 i = 0; i < ts.length; i++) { if (!underlyings.contains(ts[i])) { underlyings.add(ts[i]); } } } /// @notice Delete the underlying asset token address /// @dev Only allow the governance identity to delete the underlying asset token address /// @param ts The underlying asset token address array to be deleted function removeUnderlyings(address[] memory ts) public onlyGovernance { for (uint256 i = 0; i < ts.length; i++) { if (underlyings.contains(ts[i])) { underlyings.remove(ts[i]); } } } /// @notice swap after handle /// @param tokenOut token address /// @param amountOut token amount function swapAfter( address tokenOut, uint256 amountOut) internal override { uint256 fee = vault.calcRatioFee(SmartPoolStorage.FeeType.TURNOVER_FEE, amountOut); if (tokenOut != address(ioToken) && fee > 0) { fee = swapRoute.exactInput(tokenOut, address(ioToken), fee, address(this), 0); } if (fee > 0) { address rewards=getRewards(); ioToken.safeTransfer(rewards, fee); emit TakeFee(SmartPoolStorage.FeeType.TURNOVER_FEE, rewards, fee); } } /// @notice collect after handle /// @param token0 token address /// @param token1 token address /// @param amount0 token amount /// @param amount1 token amount function collectAfter( address token0, address token1, uint256 amount0, uint256 amount1) internal override { uint256 fee0 = vault.calcRatioFee(SmartPoolStorage.FeeType.TURNOVER_FEE, amount0); uint256 fee1 = vault.calcRatioFee(SmartPoolStorage.FeeType.TURNOVER_FEE, amount1); if (token0 != address(ioToken) && fee0 > 0) { fee0 = swapRoute.exactInput(token0, address(ioToken), fee0, address(this), 0); } if (token1 != address(ioToken) && fee1 > 0) { fee1 = swapRoute.exactInput(token1, address(ioToken), fee1, address(this), 0); } uint256 fee = fee0.add(fee1); if (fee > 0) { address rewards=getRewards(); ioToken.safeTransfer(rewards, fee); emit TakeFee(SmartPoolStorage.FeeType.TURNOVER_FEE, rewards, fee); } } /// @notice Asset transfer used to upgrade the contract /// @param to address function withdrawAll(address to) external onlyGovernance { for (uint256 i = 0; i < underlyings.length(); i++) { IERC20 token = IERC20(underlyings.at(i)); uint256 balance = token.balanceOf(address(this)); if (balance > 0) { token.safeTransfer(to, balance); } } } /// @notice Withdraw asset /// @dev Only vault contract can withdraw asset /// @param to Withdraw address /// @param amount Withdraw amount /// @param scale Withdraw percentage function withdraw(address to, uint256 amount, uint256 scale) external onlyVault { uint256 surplusAmount = ioToken.balanceOf(address(this)); if (surplusAmount < amount) { _decreaseLiquidityByScale(scale); for (uint256 i = 0; i < underlyings.length(); i++) { address token = underlyings.at(i); uint256 balance = IERC20(token).balanceOf(address(this)); if (token != address(ioToken) && balance > 0) { exactInput(token, address(ioToken), balance, 0); } } } surplusAmount = ioToken.balanceOf(address(this)); if (surplusAmount < amount) { amount = surplusAmount; } ioToken.safeTransfer(to, amount); } /// @notice Withdraw underlying asset /// @dev Only vault contract can withdraw underlying asset /// @param to Withdraw address /// @param scale Withdraw percentage function withdrawOfUnderlying(address to, uint256 scale) external onlyVault { uint256 length = underlyings.length(); uint256[] memory balances = new uint256[](length); uint256[] memory withdrawAmounts = new uint256[](length); for (uint256 i = 0; i < length; i++) { address token = underlyings.at(i); uint256 balance = IERC20(token).balanceOf(address(this)); balances[i] = balance; withdrawAmounts[i] = balance.mul(scale).div(1e18); } _decreaseLiquidityByScale(scale); for (uint256 i = 0; i < length; i++) { address token = underlyings.at(i); uint256 balance = IERC20(token).balanceOf(address(this)); uint256 decreaseAmount = balance.sub(balances[i]); uint256 addAmount = decreaseAmount.mul(scale).div(1e18); uint256 transferAmount = withdrawAmounts[i].add(addAmount); IERC20(token).safeTransfer(to, transferAmount); } } /// @notice Decrease liquidity by scale /// @dev Decrease liquidity by provided scale /// @param scale Scale of the liquidity function _decreaseLiquidityByScale(uint256 scale) internal { uint256 length = works.length(); for (uint256 i = 0; i < length; i++) { uint256 tokenId = works.at(i); ( , , , , , , , uint128 liquidity, , , , ) = UniV3PMExtends.PM.positions(tokenId); if (liquidity > 0) { uint256 _decreaseLiquidity = uint256(liquidity).mul(scale).div(1e18); (uint256 amount0, uint256 amount1) = decreaseLiquidity(tokenId, uint128(_decreaseLiquidity), 0, 0); collect(tokenId, uint128(amount0), uint128(amount1)); } } } /// @notice Total asset /// @dev This function calculates the net worth or AUM /// @return Total asset function assets() public view returns (uint256){ uint256 total = idleAssets(); total = total.add(liquidityAssets()); return total; } /// @notice idle asset /// @dev This function calculates idle asset /// @return idle asset function idleAssets() public view returns (uint256){ uint256 total; for (uint256 i = 0; i < underlyings.length(); i++) { address token = underlyings.at(i); uint256 balance = IERC20(token).balanceOf(address(this)); if (token == address(ioToken)) { total = total.add(balance); } else { uint256 _estimateAmountOut = estimateAmountOut(token, address(ioToken), balance); total = total.add(_estimateAmountOut); } } return total; } /// @notice at work liquidity asset /// @dev This function calculates liquidity asset /// @return liquidity asset function liquidityAssets() public view returns (uint256){ uint256 total; address ioTokenAddr = address(ioToken); uint256 length = works.length(); for (uint256 i = 0; i < length; i++) { uint256 tokenId = works.at(i); total = total.add(calcLiquidityAssets(tokenId, ioTokenAddr)); } return total; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../base/GovIdentity.sol"; import "../interfaces/uniswap-v3/Path.sol"; import "../libraries/ERC20Extends.sol"; import "../libraries/UniV3SwapExtends.sol"; import "../libraries/UniV3PMExtends.sol"; pragma abicoder v2; /// @title Position Management /// @notice Provide asset operation functions, allow authorized identities to perform asset operations, and achieve the purpose of increasing the net value of the fund contract UniV3Liquidity is GovIdentity { using SafeMath for uint256; using Path for bytes; using EnumerableSet for EnumerableSet.UintSet; using UniV3SwapExtends for mapping(address => mapping(address => bytes)); //Swap route mapping(address => mapping(address => bytes)) public swapRoute; //Position list mapping(bytes32 => uint256) public history; //position mapping owner mapping(uint256 => address) public positionOwners; //available token limit mapping(address => mapping(address => uint256)) public tokenLimit; //Working positions EnumerableSet.UintSet internal works; //Swap event Swap(address sender, address fromToken, address toToken, uint256 amountIn, uint256 amountOut); //Create positoin event Mint(address sender, uint256 tokenId, uint128 liquidity); //Increase liquidity event IncreaseLiquidity(address sender, uint256 tokenId, uint128 liquidity); //Decrease liquidity event DecreaseLiquidity(address sender, uint256 tokenId, uint128 liquidity); //Collect asset event Collect(address sender, uint256 tokenId, uint256 amount0, uint256 amount1); //Only allow governance, strategy, ext authorize modifier onlyAssetsManager() { require( msg.sender == getGovernance() || isAdmin(msg.sender) || isStrategist(msg.sender) || extAuthorize(), "!AM"); _; } //Only position owner modifier onlyPositionManager(uint256 tokenId) { require( msg.sender == getGovernance() || isAdmin(msg.sender) || positionOwners[tokenId] == msg.sender || extAuthorize(), "!PM"); _; } /// @notice extend authorize function extAuthorize() internal virtual view returns (bool){ return false; } /// @notice swap after handle function swapAfter( address, uint256) internal virtual { } /// @notice collect after handle function collectAfter( address, address, uint256, uint256) internal virtual { } /// @notice Check current position /// @dev Check the current UniV3 position by pool token ID. /// @param pool liquidity pool /// @param tickLower Tick lower bound /// @param tickUpper Tick upper bound /// @return atWork Position status /// @return has Check if the position ID exist /// @return tokenId Position ID function checkPos( address pool, int24 tickLower, int24 tickUpper ) public view returns (bool atWork, bool has, uint256 tokenId){ bytes32 pk = UniV3PMExtends.positionKey(pool, tickLower, tickUpper); tokenId = history[pk]; atWork = works.contains(tokenId); has = tokenId > 0 ? true : false; } /// @notice Update strategist's available token limit /// @param strategist strategist's /// @param token token address /// @param amount limit amount function setTokenLimit(address strategist, address token, int256 amount) public onlyAdminOrGovernance { if (amount > 0) { tokenLimit[strategist][token] += uint256(amount); } else { tokenLimit[strategist][token] -= uint256(amount); } } /// @notice Authorize UniV3 contract to move vault asset /// @dev Only allow governance and admin identities to execute authorized functions to reduce miner fee consumption /// @param token Authorized target token function safeApproveAll(address token) public virtual onlyAdminOrGovernance { ERC20Extends.safeApprove(token, address(UniV3PMExtends.PM), type(uint256).max); ERC20Extends.safeApprove(token, address(UniV3SwapExtends.SRT), type(uint256).max); } /// @notice Multiple functions of the contract can be executed at the same time /// @dev Only the assets manager identities are allowed to execute multiple function calls, /// and the execution of multiple functions can ensure the consistency of the execution results /// @param data Encode data of multiple execution functions /// @return results Execution result function multicall(bytes[] calldata data) external onlyAssetsManager returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); if (!success) { if (result.length < 68) revert(); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } results[i] = result; } } /// @notice Set asset swap route /// @dev Only the governance and admin identity is allowed to set the asset swap path, and the firstToken and lastToken contained in the path will be used as the underlying asset token address by default /// @param path Swap path byte code function settingSwapRoute(bytes memory path) external onlyAdminOrGovernance { require(path.valid(), 'path is not valid'); address fromToken = path.getFirstAddress(); address toToken = path.getLastAddress(); swapRoute[fromToken][toToken] = path; } /// @notice Estimated to obtain the target token amount /// @dev Only allow the asset transaction path that has been set to be estimated /// @param from Source token address /// @param to Target token address /// @param amountIn Source token amount /// @return amountOut Target token amount function estimateAmountOut( address from, address to, uint256 amountIn ) public view returns (uint256 amountOut){ return swapRoute.estimateAmountOut(from, to, amountIn); } /// @notice Estimate the amount of source tokens that need to be provided /// @dev Only allow the governance identity to set the underlying asset token address /// @param from Source token address /// @param to Target token address /// @param amountOut Expect to get the target token amount /// @return amountIn Source token amount function estimateAmountIn( address from, address to, uint256 amountOut ) public view returns (uint256 amountIn){ return swapRoute.estimateAmountIn(from, to, amountOut); } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @dev Initiate a transaction with a known input amount and return the output amount /// @param tokenIn Token in address /// @param tokenOut Token out address /// @param amountIn Token in amount /// @param amountOutMinimum Expected to get minimum token out amount /// @return amountOut Token out amount function exactInput( address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOutMinimum ) public onlyAssetsManager returns (uint256 amountOut) { bool _isStrategist = isStrategist(msg.sender); if (_isStrategist) { require(tokenLimit[msg.sender][tokenIn] >= amountIn, '!check limit'); } amountOut = swapRoute.exactInput(tokenIn, tokenOut, amountIn, address(this), amountOutMinimum); if (_isStrategist) { tokenLimit[msg.sender][tokenIn] -= amountIn; tokenLimit[msg.sender][tokenOut] += amountOut; } swapAfter(tokenOut, amountOut); emit Swap(msg.sender, tokenIn, tokenOut, amountIn, amountOut); } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @dev Initiate a transaction with a known output amount and return the input amount /// @param tokenIn Token in address /// @param tokenOut Token out address /// @param amountOut Token out amount /// @param amountInMaximum Expect to input the maximum amount of tokens /// @return amountIn Token in amount function exactOutput( address tokenIn, address tokenOut, uint256 amountOut, uint256 amountInMaximum ) public onlyAssetsManager returns (uint256 amountIn) { amountIn = swapRoute.exactOutput(tokenIn, tokenOut, address(this), amountOut, amountInMaximum); if (isStrategist(msg.sender)) { require(tokenLimit[msg.sender][tokenIn] >= amountIn, '!check limit'); tokenLimit[msg.sender][tokenIn] -= amountIn; tokenLimit[msg.sender][tokenOut] += amountOut; } swapAfter(tokenOut, amountOut); emit Swap(msg.sender, tokenIn, tokenOut, amountIn, amountOut); } /// @notice Create position /// @dev Repeated creation of the same position will cause an error, you need to change tickLower Or tickUpper /// @param token0 Liquidity pool token 0 contract address /// @param token1 Liquidity pool token 1 contract address /// @param fee Target liquidity pool rate /// @param tickLower Expect to place the lower price boundary of the target liquidity pool /// @param tickUpper Expect to place the upper price boundary of the target liquidity pool /// @param amount0Desired Desired token 0 amount /// @param amount1Desired Desired token 1 amount function mint( address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint256 amount0Desired, uint256 amount1Desired ) public onlyAssetsManager { bool _isStrategist = isStrategist(msg.sender); if (_isStrategist) { require(tokenLimit[msg.sender][token0] >= amount0Desired, '!check limit'); require(tokenLimit[msg.sender][token1] >= amount1Desired, '!check limit'); } ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ) = UniV3PMExtends.PM.mint(INonfungiblePositionManager.MintParams({ token0 : token0, token1 : token1, fee : fee, tickLower : tickLower, tickUpper : tickUpper, amount0Desired : amount0Desired, amount1Desired : amount1Desired, amount0Min : 0, amount1Min : 0, recipient : address(this), deadline : block.timestamp })); if (_isStrategist) { tokenLimit[msg.sender][token0] -= amount0; tokenLimit[msg.sender][token1] -= amount1; } address pool = UniV3PMExtends.getPool(tokenId); bytes32 pk = UniV3PMExtends.positionKey(pool, tickLower, tickUpper); history[pk] = tokenId; positionOwners[tokenId] = msg.sender; works.add(tokenId); emit Mint(msg.sender, tokenId, liquidity); } /// @notice Increase liquidity /// @dev Use checkPos to check the position ID /// @param tokenId Position ID /// @param amount0 Desired Desired token 0 amount /// @param amount1 Desired Desired token 1 amount /// @param amount0Min Minimum token 0 amount /// @param amount1Min Minimum token 1 amount /// @return liquidity The amount of liquidity /// @return amount0 Actual token 0 amount being added /// @return amount1 Actual token 1 amount being added function increaseLiquidity( uint256 tokenId, uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min ) public onlyPositionManager(tokenId) returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ){ ( , , address token0, address token1, , , , , , , , ) = UniV3PMExtends.PM.positions(tokenId); address po = positionOwners[tokenId]; if (isStrategist(po)) { require(tokenLimit[po][token0] >= amount0Desired, '!check limit'); require(tokenLimit[po][token1] >= amount1Desired, '!check limit'); } (liquidity, amount0, amount1) = UniV3PMExtends.PM.increaseLiquidity(INonfungiblePositionManager.IncreaseLiquidityParams({ tokenId : tokenId, amount0Desired : amount0Desired, amount1Desired : amount1Desired, amount0Min : amount0Min, amount1Min : amount1Min, deadline : block.timestamp })); if (isStrategist(po)) { tokenLimit[po][token0] -= amount0; tokenLimit[po][token1] -= amount1; } if (!works.contains(tokenId)) { works.add(tokenId); } emit IncreaseLiquidity(msg.sender, tokenId, liquidity); } /// @notice Decrease liquidity /// @dev Use checkPos to query the position ID /// @param tokenId Position ID /// @param liquidity Expected reduction amount of liquidity /// @param amount0Min Minimum amount of token 0 to be reduced /// @param amount1Min Minimum amount of token 1 to be reduced /// @return amount0 Actual amount of token 0 being reduced /// @return amount1 Actual amount of token 1 being reduced function decreaseLiquidity( uint256 tokenId, uint128 liquidity, uint256 amount0Min, uint256 amount1Min ) public onlyPositionManager(tokenId) returns (uint256 amount0, uint256 amount1){ (amount0, amount1) = UniV3PMExtends.PM.decreaseLiquidity(INonfungiblePositionManager.DecreaseLiquidityParams({ tokenId : tokenId, liquidity : liquidity, amount0Min : amount0Min, amount1Min : amount1Min, deadline : block.timestamp })); emit DecreaseLiquidity(msg.sender, tokenId, liquidity); } /// @notice Collect position asset /// @dev Use checkPos to check the position ID /// @param tokenId Position ID /// @param amount0Max Maximum amount of token 0 to be collected /// @param amount1Max Maximum amount of token 1 to be collected /// @return amount0 Actual amount of token 0 being collected /// @return amount1 Actual amount of token 1 being collected function collect( uint256 tokenId, uint128 amount0Max, uint128 amount1Max ) public onlyPositionManager(tokenId) returns (uint256 amount0, uint256 amount1){ (amount0, amount1) = UniV3PMExtends.PM.collect(INonfungiblePositionManager.CollectParams({ tokenId : tokenId, recipient : address(this), amount0Max : amount0Max, amount1Max : amount1Max })); ( , , address token0, address token1, , , , uint128 liquidity, , , , ) = UniV3PMExtends.PM.positions(tokenId); address po = positionOwners[tokenId]; if (isStrategist(po)) { tokenLimit[po][token0] += amount0; tokenLimit[po][token1] += amount1; } if (liquidity == 0) { works.remove(tokenId); } collectAfter(token0, token1, amount0, amount1); emit Collect(msg.sender, tokenId, amount0, amount1); } /// @notice calc tokenId asset /// @dev This function calc tokenId asset /// @return tokenId asset function calcLiquidityAssets(uint256 tokenId, address toToken) internal view returns (uint256) { ( , , address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, , , , ) = UniV3PMExtends.PM.positions(tokenId); (uint256 amount0, uint256 amount1) = UniV3PMExtends.getAmountsForLiquidity( token0, token1, fee, tickLower, tickUpper, liquidity); (uint256 fee0, uint256 fee1) = UniV3PMExtends.getFeesForLiquidity(tokenId); (amount0, amount1) = (amount0.add(fee0), amount1.add(fee1)); uint256 total; if (token0 == toToken) { total = amount0; } else { uint256 _estimateAmountOut = swapRoute.estimateAmountOut(token0, toToken, amount0); total = _estimateAmountOut; } if (token1 == toToken) { total = total.add(amount1); } else { uint256 _estimateAmountOut = swapRoute.estimateAmountOut(token1, toToken, amount1); total = total.add(_estimateAmountOut); } return total; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; library SmartPoolStorage { bytes32 public constant sSlot = keccak256("SmartPoolStorage.storage.location"); struct Storage { mapping(FeeType => Fee) fees; mapping(address => uint256) nets; address token; address am; uint256 cap; uint256 lup; bool bind; bool suspend; bool allowJoin; bool allowExit; } struct Fee { uint256 ratio; uint256 denominator; uint256 lastTimestamp; uint256 minLine; } enum FeeType{ JOIN_FEE, EXIT_FEE, MANAGEMENT_FEE, PERFORMANCE_FEE,TURNOVER_FEE } function load() internal pure returns (Storage storage s) { bytes32 loc = sSlot; assembly { s.slot := loc } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "../interfaces/uniswap-v3/INonfungiblePositionManager.sol"; import "../interfaces/uniswap-v3/IUniswapV3Pool.sol"; import "../interfaces/uniswap-v3/TickMath.sol"; import "../interfaces/uniswap-v3/LiquidityAmounts.sol"; import "../interfaces/uniswap-v3/FixedPoint128.sol"; import "../interfaces/uniswap-v3/PoolAddress.sol"; /// @title UniV3 extends libraries /// @notice libraries library UniV3PMExtends { //Nonfungible Position Manager INonfungiblePositionManager constant internal PM = INonfungiblePositionManager(0xC36442b4a4522E871399CD717aBDD847Ab11FE88); /// @notice Position id /// @dev Position ID /// @param addr any address /// @param tickLower Tick lower price bound /// @param tickUpper Tick upper price bound /// @return ABI encode function positionKey( address addr, int24 tickLower, int24 tickUpper ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(addr, tickLower, tickUpper)); } /// @notice get pool by tokenId /// @param tokenId position Id function getPool(uint256 tokenId) internal view returns (address){ ( , , address token0, address token1, uint24 fee, , , , , , , ) = PM.positions(tokenId); return PoolAddress.getPool(token0, token1, fee); } /// @notice Calculate the number of redeemable tokens based on the amount of liquidity /// @dev Used when redeeming liquidity /// @param token0 Token 0 address /// @param token1 Token 1 address /// @param fee Fee rate /// @param tickLower Tick lower price bound /// @param tickUpper Tick upper price bound /// @param liquidity Liquidity amount /// @return amount0 Token 0 amount /// @return amount1 Token 1 amount function getAmountsForLiquidity( address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity ) internal view returns (uint256 amount0, uint256 amount1) { (uint160 sqrtPriceX96,,,,,,) = IUniswapV3Pool(PoolAddress.getPool(token0, token1, fee)).slot0(); uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(tickLower); uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(tickUpper); (amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity( sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, liquidity ); } ///@notice Calculate unreceived handling fees for liquid positions /// @param tokenId Position ID /// @return fee0 Token 0 fee amount /// @return fee1 Token 1 fee amount function getFeesForLiquidity( uint256 tokenId ) internal view returns (uint256 fee0, uint256 fee1){ ( , , , , , , , uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ) = PM.positions(tokenId); (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) = getFeeGrowthInside(tokenId); fee0 = tokensOwed0 + FullMath.mulDiv( feeGrowthInside0X128 - feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128 ); fee1 = tokensOwed1 + FullMath.mulDiv( feeGrowthInside1X128 - feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128 ); } /// @notice Retrieves fee growth data function getFeeGrowthInside( uint256 tokenId ) internal view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) { ( , , , , , int24 tickLower, int24 tickUpper, , , , , ) = PM.positions(tokenId); IUniswapV3Pool pool = IUniswapV3Pool(getPool(tokenId)); (,int24 tickCurrent,,,,,) = pool.slot0(); uint256 feeGrowthGlobal0X128 = pool.feeGrowthGlobal0X128(); uint256 feeGrowthGlobal1X128 = pool.feeGrowthGlobal1X128(); ( , , uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128, , , , ) = pool.ticks(tickLower); ( , , uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128, , , , ) = pool.ticks(tickUpper); // calculate fee growth below uint256 feeGrowthBelow0X128; uint256 feeGrowthBelow1X128; if (tickCurrent >= tickLower) { feeGrowthBelow0X128 = lowerFeeGrowthOutside0X128; feeGrowthBelow1X128 = lowerFeeGrowthOutside1X128; } else { feeGrowthBelow0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128; feeGrowthBelow1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128; } // calculate fee growth above uint256 feeGrowthAbove0X128; uint256 feeGrowthAbove1X128; if (tickCurrent < tickUpper) { feeGrowthAbove0X128 = upperFeeGrowthOutside0X128; feeGrowthAbove1X128 = upperFeeGrowthOutside1X128; } else { feeGrowthAbove0X128 = feeGrowthGlobal0X128 - upperFeeGrowthOutside0X128; feeGrowthAbove1X128 = feeGrowthGlobal1X128 - upperFeeGrowthOutside1X128; } feeGrowthInside0X128 = feeGrowthGlobal0X128 - feeGrowthBelow0X128 - feeGrowthAbove0X128; feeGrowthInside1X128 = feeGrowthGlobal1X128 - feeGrowthBelow1X128 - feeGrowthAbove1X128; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /// @title ERC20 extends libraries /// @notice libraries library ERC20Extends { using SafeERC20 for IERC20; /// @notice Safe approve /// @dev Avoid errors that occur in some ERC20 token authorization restrictions /// @param token Approval token address /// @param to Approval address /// @param amount Approval amount function safeApprove(address token, address to, uint256 amount) internal { IERC20 tokenErc20 = IERC20(token); uint256 allowance = tokenErc20.allowance(address(this), to); if (allowance < amount) { if (allowance > 0) { tokenErc20.safeApprove(to, 0); } tokenErc20.safeApprove(to, amount); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "../storage/SmartPoolStorage.sol"; pragma abicoder v2; /// @title Vault - the vault interface /// @notice This contract extends ERC20, defines basic vault functions and rewrites ERC20 transferFrom function interface IVault { /// @notice Vault cap /// @dev The max number of vault to be issued /// @return Max vault cap function getCap() external view returns (uint256); /// @notice Get fee by type /// @dev (0=JOIN_FEE,1=EXIT_FEE,2=MANAGEMENT_FEE,3=PERFORMANCE_FEE,4=TURNOVER_FEE) /// @param ft Fee type function getFee(SmartPoolStorage.FeeType ft) external view returns (SmartPoolStorage.Fee memory); /// @notice Calculate the fee by ratio /// @dev This is used to calculate join and redeem fee /// @param ft Fee type /// @param vaultAmount vault amount function calcRatioFee(SmartPoolStorage.FeeType ft, uint256 vaultAmount) external view returns (uint256); /// @notice The net worth of the vault from the time the last fee collected /// @dev This is used to calculate the performance fee /// @param account Account address /// @return The net worth of the vault function accountNetValue(address account) external view returns (uint256); /// @notice The current vault net worth /// @dev This is used to update and calculate account net worth /// @return The net worth of the vault function globalNetValue() external view returns (uint256); /// @notice Convert vault amount to cash amount /// @dev This converts the user vault amount to cash amount when a user redeems the vault /// @param vaultAmount Redeem vault amount /// @return Cash amount function convertToCash(uint256 vaultAmount) external view returns (uint256); /// @notice Convert cash amount to share amount /// @dev This converts cash amount to share amount when a user buys the vault /// @param cashAmount Join cash amount /// @return share amount function convertToShare(uint256 cashAmount) external view returns (uint256); /// @notice Vault token address for joining and redeeming /// @dev This is address is created when the vault is first created. /// @return Vault token address function ioToken() external view returns (address); /// @notice Vault mangement contract address /// @dev The vault management contract address is bind to the vault when the vault is created /// @return Vault management contract address function AM() external view returns (address); /// @notice Vault total asset /// @dev This calculates vault net worth or AUM /// @return Vault total asset function assets()external view returns(uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; 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 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.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/uniswap-v3/ISwapRouter.sol"; import "../interfaces/uniswap-v3/IUniswapV3Pool.sol"; import "../interfaces/uniswap-v3/PoolAddress.sol"; import "../interfaces/uniswap-v3/Path.sol"; import "./SafeMathExtends.sol"; pragma abicoder v2; /// @title UniV3 Swap extends libraries /// @notice libraries library UniV3SwapExtends { using Path for bytes; using SafeMath for uint256; using SafeMathExtends for uint256; //x96 uint256 constant internal x96 = 2 ** 96; //fee denominator uint256 constant internal denominator = 1000000; //Swap Router ISwapRouter constant internal SRT = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); /// @notice Estimated to obtain the target token amount /// @dev Only allow the asset transaction path that has been set to be estimated /// @param self Mapping path /// @param from Source token address /// @param to Target token address /// @param amountIn Source token amount /// @return amountOut Target token amount function estimateAmountOut( mapping(address => mapping(address => bytes)) storage self, address from, address to, uint256 amountIn ) internal view returns (uint256 amountOut){ if (amountIn == 0) {return 0;} bytes memory path = self[from][to]; amountOut = amountIn; while (true) { (address fromToken, address toToken, uint24 fee) = path.getFirstPool().decodeFirstPool(); address _pool = PoolAddress.getPool(fromToken, toToken, fee); (uint160 sqrtPriceX96,,,,,,) = IUniswapV3Pool(_pool).slot0(); address token0 = fromToken < toToken ? fromToken : toToken; amountOut = amountOut.mul(denominator.sub(uint256(fee))).div(denominator); if (token0 == toToken) { amountOut = amountOut.sqrt().mul(x96).div(sqrtPriceX96) ** 2; } else { amountOut = amountOut.sqrt().mul(sqrtPriceX96).div(x96) ** 2; } bool hasMultiplePools = path.hasMultiplePools(); if (hasMultiplePools) { path = path.skipToken(); } else { break; } } } /// @notice Estimate the amount of source tokens that need to be provided /// @dev Only allow the governance identity to set the underlying asset token address /// @param self Mapping path /// @param from Source token address /// @param to Target token address /// @param amountOut Expected target token amount /// @return amountIn Source token amount function estimateAmountIn( mapping(address => mapping(address => bytes)) storage self, address from, address to, uint256 amountOut ) internal view returns (uint256 amountIn){ if (amountOut == 0) {return 0;} bytes memory path = self[from][to]; amountIn = amountOut; while (true) { (address fromToken, address toToken, uint24 fee) = path.getFirstPool().decodeFirstPool(); address _pool = PoolAddress.getPool(fromToken, toToken, fee); (uint160 sqrtPriceX96,,,,,,) = IUniswapV3Pool(_pool).slot0(); address token0 = fromToken < toToken ? fromToken : toToken; if (token0 == toToken) { amountIn = amountIn.sqrt().mul(sqrtPriceX96).div(x96) ** 2; } else { amountIn = amountIn.sqrt().mul(x96).div(sqrtPriceX96) ** 2; } amountIn = amountIn.mul(denominator).div(denominator.sub(uint256(fee))); bool hasMultiplePools = path.hasMultiplePools(); if (hasMultiplePools) { path = path.skipToken(); } else { break; } } } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @dev Initiate a transaction with a known input amount and return the output amount /// @param self Mapping path /// @param from Input token address /// @param to Output token address /// @param amountIn Token in amount /// @param recipient Recipient address /// @param amountOutMinimum Expected to get minimum token out amount /// @return Token out amount function exactInput( mapping(address => mapping(address => bytes)) storage self, address from, address to, uint256 amountIn, address recipient, uint256 amountOutMinimum ) internal returns (uint256){ bytes memory path = self[from][to]; return SRT.exactInput( ISwapRouter.ExactInputParams({ path : path, recipient : recipient, deadline : block.timestamp, amountIn : amountIn, amountOutMinimum : amountOutMinimum })); } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @dev Initiate a transaction with a known output amount and return the input amount /// @param self Mapping path /// @param from Input token address /// @param to Output token address /// @param recipient Recipient address /// @param amountOut Token out amount /// @param amountInMaximum Expect to input the maximum amount of tokens /// @return Token in amount function exactOutput( mapping(address => mapping(address => bytes)) storage self, address from, address to, address recipient, uint256 amountOut, uint256 amountInMaximum ) internal returns (uint256){ bytes memory path = self[to][from]; return SRT.exactOutput( ISwapRouter.ExactOutputParams({ path : path, recipient : recipient, deadline : block.timestamp, amountOut : amountOut, amountInMaximum : amountInMaximum })); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.0; import './BytesLib.sol'; /// @title Functions for manipulating path data for multihop swaps library Path { using BytesLib for bytes; /// @dev The length of the bytes encoded address uint256 private constant ADDR_SIZE = 20; /// @dev The length of the bytes encoded fee uint256 private constant FEE_SIZE = 3; /// @dev The offset of a single token address and pool fee uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE; /// @dev The offset of an encoded pool key uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE; /// @dev The minimum length of an encoding that contains 2 or more pools uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET; /// @notice Check the legitimacy of the path /// @param path The encoded swap path /// @return Legal path function valid(bytes memory path)internal pure returns(bool) { return path.length>=POP_OFFSET; } /// @notice Returns true iff the path contains two or more pools /// @param path The encoded swap path /// @return True if path contains two or more pools, otherwise false function hasMultiplePools(bytes memory path) internal pure returns (bool) { return path.length >= MULTIPLE_POOLS_MIN_LENGTH; } /// @notice Decodes the first pool in path /// @param path The bytes encoded swap path /// @return tokenA The first token of the given pool /// @return tokenB The second token of the given pool /// @return fee The fee level of the pool function decodeFirstPool(bytes memory path) internal pure returns ( address tokenA, address tokenB, uint24 fee ) { tokenA = path.toAddress(0); fee = path.toUint24(ADDR_SIZE); tokenB = path.toAddress(NEXT_OFFSET); } /// @notice Gets the segment corresponding to the first pool in the path /// @param path The bytes encoded swap path /// @return The segment containing all data necessary to target the first pool in the path function getFirstPool(bytes memory path) internal pure returns (bytes memory) { return path.slice(0, POP_OFFSET); } /// @notice Gets the segment corresponding to the last pool in the path /// @param path The bytes encoded swap path /// @return The segment containing all data necessary to target the last pool in the path function getLastPool(bytes memory path) internal pure returns (bytes memory) { if(path.length==POP_OFFSET){ return path; }else{ return path.slice(path.length-POP_OFFSET, path.length); } } /// @notice Gets the first address of the path /// @param path The encoded swap path /// @return address function getFirstAddress(bytes memory path)internal pure returns(address){ return path.toAddress(0); } /// @notice Gets the last address of the path /// @param path The encoded swap path /// @return address function getLastAddress(bytes memory path)internal pure returns(address){ return path.toAddress(path.length-ADDR_SIZE); } /// @notice Skips a token + fee element from the buffer and returns the remainder /// @param path The swap path /// @return The remaining token + fee elements in the path function skipToken(bytes memory path) internal pure returns (bytes memory) { return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "../storage/GovIdentityStorage.sol"; /// @title manager role /// @notice provide a unified identity address pool contract GovIdentity { constructor() { _init(); } function _init() internal{ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); identity.governance = msg.sender; identity.rewards = msg.sender; identity.strategist[msg.sender]=true; identity.admin[msg.sender]=true; } modifier onlyAdmin() { GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); require(isAdmin(msg.sender), "!admin"); _; } modifier onlyStrategist() { require(isStrategist(msg.sender), "!strategist"); _; } modifier onlyGovernance() { GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); require(msg.sender == identity.governance, "!governance"); _; } modifier onlyStrategistOrGovernance() { GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); require(identity.strategist[msg.sender] || msg.sender == identity.governance, "!governance and !strategist"); _; } modifier onlyAdminOrGovernance() { GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); require(identity.admin[msg.sender] || msg.sender == identity.governance, "!governance and !admin"); _; } function setGovernance(address _governance) public onlyGovernance{ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); identity.governance = _governance; } function setRewards(address _rewards) public onlyGovernance{ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); identity.rewards = _rewards; } function setStrategist(address _strategist,bool enable) public onlyGovernance{ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); identity.strategist[_strategist]=enable; } function setAdmin(address _admin,bool enable) public onlyGovernance{ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); identity.admin[_admin]=enable; } function getGovernance() public view returns(address){ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); return identity.governance; } function getRewards() public view returns(address){ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); return identity.rewards ; } function isStrategist(address _strategist) public view returns(bool){ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); return identity.strategist[_strategist]; } function isAdmin(address _admin) public view returns(bool){ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); return identity.admin[_admin]; } } // 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: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; //Uniswap V3 Factory address constant private factory = address(0x1F98431c8aD98523631AE4a59f267346ea31F984); /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @dev Returns the pool for the given token pair and fee. The pool contract may or may not exist. function getPool( address tokenA, address tokenB, uint24 fee ) internal pure returns (address) { return computeAddress(getPoolKey(tokenA, tokenB, fee)); } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0 : tokenA, token1 : tokenB, fee : fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint128 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) library FixedPoint128 { uint256 internal constant Q128 = 0x100000000000000000000000000000000; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './FullMath.sol'; import './FixedPoint96.sol'; /// @title Liquidity amount functions /// @notice Provides functions for computing liquidity amounts from token amounts and prices library LiquidityAmounts { /// @notice Downcasts uint256 to uint128 /// @param x The uint258 to be downcasted /// @return y The passed value, downcasted to uint128 function toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount0 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount1 The amount1 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount of token0 being sent in /// @param amount1 The amount of token1 being sent in /// @return liquidity The maximum amount of liquidity received function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } /// @notice Computes the amount of token0 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; } /// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount1 The amount of token1 function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity); amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity); } else { amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = - 887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = - MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(- int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; pragma experimental ABIEncoderV2; interface INonfungiblePositionManager is IERC721 { /// @notice Returns the position information associated with a given token ID. /// @dev Throws if the token ID is not valid. /// @param tokenId The ID of the token that represents the position /// @return nonce The nonce for permits /// @return operator The address that is approved for spending /// @return token0 The address of the token0 for a specific pool /// @return token1 The address of the token1 for a specific pool /// @return fee The fee associated with the pool /// @return tickLower The lower end of the tick range for the position /// @return tickUpper The higher end of the tick range for the position /// @return liquidity The liquidity of the position /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation function positions(uint256 tokenId) external view returns ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; } /// @notice Creates a new position wrapped in a NFT /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized /// a method does not exist, i.e. the pool is assumed to be initialized. /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata /// @return tokenId The ID of the token that represents the minted position /// @return liquidity The amount of liquidity for this position /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function mint(MintParams calldata params) external payable returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ); struct IncreaseLiquidityParams { uint256 tokenId; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender` /// @param params tokenId The ID of the token for which liquidity is being increased, /// amount0Desired The desired amount of token0 to be spent, /// amount1Desired The desired amount of token1 to be spent, /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check, /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check, /// deadline The time by which the transaction must be included to effect the change /// @return liquidity The new liquidity amount as a result of the increase /// @return amount0 The amount of token0 to acheive resulting liquidity /// @return amount1 The amount of token1 to acheive resulting liquidity function increaseLiquidity(IncreaseLiquidityParams calldata params) external payable returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ); struct DecreaseLiquidityParams { uint256 tokenId; uint128 liquidity; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Decreases the amount of liquidity in a position and accounts it to the position /// @param params tokenId The ID of the token for which liquidity is being decreased, /// amount The amount by which liquidity will be decreased, /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity, /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity, /// deadline The time by which the transaction must be included to effect the change /// @return amount0 The amount of token0 accounted to the position's tokens owed /// @return amount1 The amount of token1 accounted to the position's tokens owed function decreaseLiquidity(DecreaseLiquidityParams calldata params) external payable returns (uint256 amount0, uint256 amount1); struct CollectParams { uint256 tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient /// @param params tokenId The ID of the NFT for which tokens are being collected, /// recipient The account that should receive the tokens, /// amount0Max The maximum amount of token0 to collect, /// amount1Max The maximum amount of token1 to collect /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1); /// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens /// must be collected first. /// @param tokenId The ID of the token that is being burned function burn(uint256 tokenId) external payable; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; // a library for performing various math operations library SafeMathExtends { uint256 internal constant BONE = 10 ** 18; // Add two numbers together checking for overflows function badd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "ERR_ADD_OVERFLOW"); return c; } // subtract two numbers and return diffecerence when it underflows function bsubSign(uint256 a, uint256 b) internal pure returns (uint256, bool) { if (a >= b) { return (a - b, false); } else { return (b - a, true); } } // Subtract two numbers checking for underflows function bsub(uint256 a, uint256 b) internal pure returns (uint256) { (uint256 c, bool flag) = bsubSign(a, b); require(!flag, "ERR_SUB_UNDERFLOW"); return c; } // Multiply two 18 decimals numbers function bmul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c0 = a * b; require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW"); uint256 c1 = c0 + (BONE / 2); require(c1 >= c0, "ERR_MUL_OVERFLOW"); uint256 c2 = c1 / BONE; return c2; } // Divide two 18 decimals numbers function bdiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "ERR_DIV_ZERO"); uint256 c0 = a * BONE; require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); // bmul overflow uint256 c1 = c0 + (b / 2); require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require uint256 c2 = c1 / b; return c2; } function min(uint x, uint y) internal pure returns (uint z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; pragma experimental ABIEncoderV2; import './IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later /* * @title Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ pragma solidity >=0.5.0 <=0.8.0; library BytesLib { function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, 'slice_overflow'); require(_start + _length >= _start, 'slice_overflow'); require(_bytes.length >= _start + _length, 'slice_outOfBounds'); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_start + 20 >= _start, 'toAddress_overflow'); require(_bytes.length >= _start + 20, 'toAddress_outOfBounds'); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) { require(_start + 3 >= _start, 'toUint24_overflow'); require(_bytes.length >= _start + 3, 'toUint24_outOfBounds'); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = - denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; library GovIdentityStorage { bytes32 public constant govSlot = keccak256("GovIdentityStorage.storage.location"); struct Identity{ address governance; address rewards; mapping(address=>bool) strategist; mapping(address=>bool) admin; } function load() internal pure returns (Identity storage gov) { bytes32 loc = govSlot; assembly { gov.slot := loc } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
collect after handle token0 token address token1 token address amount0 token amount amount1 token amount
function collectAfter( address token0, address token1, uint256 amount0, uint256 amount1) internal override { uint256 fee0 = vault.calcRatioFee(SmartPoolStorage.FeeType.TURNOVER_FEE, amount0); uint256 fee1 = vault.calcRatioFee(SmartPoolStorage.FeeType.TURNOVER_FEE, amount1); if (token0 != address(ioToken) && fee0 > 0) { fee0 = swapRoute.exactInput(token0, address(ioToken), fee0, address(this), 0); } if (token1 != address(ioToken) && fee1 > 0) { fee1 = swapRoute.exactInput(token1, address(ioToken), fee1, address(this), 0); } uint256 fee = fee0.add(fee1); if (fee > 0) { address rewards=getRewards(); ioToken.safeTransfer(rewards, fee); emit TakeFee(SmartPoolStorage.FeeType.TURNOVER_FEE, rewards, fee); } }
5,843,733
./full_match/1/0x10aEC5622602e02186508318bD6e2cD995C92705/sources/contracts/MusicRacerNFT333.sol
задает адрес фабрики-минтера
function SetMinter(address newMinter) public onlyOwner { Minter = newMinter; }
3,872,348
pragma solidity ^0.4.24; import "browser/data.sol"; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract BitSTDLogic { address public owner; // data layer BitSTDData private data; constructor(address dataAddress) { data = BitSTDData(dataAddress); owner = msg.sender; } // Transfer logical layer authority function transferAuthority(address newOwner) onlyOwner public { owner = newOwner; } modifier onlyOwner(){ require(msg.sender == owner); _; } // Transfer data layer authority function transferDataAuthority(address newOwner) onlyOwner public { data.transferAuthority(newOwner); } function setData(address dataAddress)onlyOwner public { data = BitSTDData(dataAddress); } // Old contract data function getOldBalanceOf(address addr) constant public returns (uint256) { return data.getOldBalanceOf(addr); } /** * Internal transfers can only be invoked through this contract */ function _transfer(address _from, address _to, uint _value) internal { uint256 f_value = balanceOf(_from); uint256 t_value = balanceOf(_to); // Prevents transmission to 0x0 address.Call to Burn () require(_to != 0x0); // Check that the sender is adequate require(f_value >= _value); // Check the overflow require(t_value + _value > t_value); // Save it as a future assertion uint previousBalances = f_value + t_value; // Minus from the sender setBalanceOf(_from, f_value - _value); // Add to receiver setBalanceOf(_to, t_value + _value); // Assertions are used to use static analysis to detect errors in code.They should not fail assert(balanceOf(_from) + balanceOf(_to) == previousBalances); } // data migration function migration(address sender, address receiver) onlyOwner public returns (bool) { require(sender != receiver); bool result = false; // Start data migration // uint256 t_value = balanceOf(receiver); uint256 _value = data.getOldBalanceOf(receiver); //Transfer balance if (data.balanceOf(receiver) == 0) { if (_value > 0) { _transfer(sender, receiver, _value); result = true; } } //Frozen account migration if (data.getOldFrozenAccount(receiver) == true) { if (data.frozenAccount(receiver) != true) { data.setFrozenAccount(receiver, true); } } //End data migration return result; } // Check the contract token function balanceOf(address addr) constant public returns (uint256) { return data.balanceOf(addr); } function name() constant public returns (string) { return data.name(); } function symbol() constant public returns(string) { return data.symbol(); } function decimals() constant public returns(uint8) { return data.decimals(); } function totalSupply() constant public returns(uint256) { return data.totalSupply(); } function allowance(address authorizer, address sender) constant public returns(uint256) { return data.allowance(authorizer, sender); } function sellPrice() constant public returns (uint256) { return data.sellPrice(); } function buyPrice() constant public returns (uint256) { return data.buyPrice(); } function frozenAccount(address addr) constant public returns(bool) { return data.frozenAccount(addr); } //Modify the contract function setBalanceOf(address addr, uint256 value) onlyOwner public { data.setBalanceOfAddr(addr, value); } /** * Pass the token * send a value token to your account */ function transfer(address sender, address _to, uint256 _value) onlyOwner public returns (bool) { _transfer(sender, _to, _value); return true; } /** *Passing tokens from other addresses * * sends the value token to "to", representing "from" * * @param _from sender's address * @param _to recipient's address * @param _value number sent */ function transferFrom(address _from, address sender, address _to, uint256 _value) onlyOwner public returns (bool success) { uint256 a_value = data.allowance(_from, sender); require(_value <= a_value ); // Check allowance data.setAllowance(_from, sender, a_value - _value); _transfer(_from, _to, _value); return true; } /** * set allowances for other addresses * * allow the "spender" to spend only the "value" card in your name * * @param _spender authorized address * @param _value they can spend the most money */ function approve(address _spender, address sender, uint256 _value) onlyOwner public returns (bool success) { data.setAllowance(sender, _spender, _value); return true; } /** * Grant and notify other addresses * * allow "spender" to only mark "value" in your name and then write the contract on it. * * @param _spender authorized address * @param _value they can spend the most money * @param _extraData sends some additional information to the approved contract */ function approveAndCall(address _spender, address sender, address _contract, uint256 _value, bytes _extraData) onlyOwner public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, sender, _value)) { spender.receiveApproval(sender, _value, _contract, _extraData); return true; } } /** * Destroy the tokens, * * delete "value" tokens from the system * * param _value the amount of money to burn */ function burn(address sender, uint256 _value) onlyOwner public returns (bool success) { uint256 f_value = balanceOf(sender); require(f_value >= _value); // Check that the sender is adequate setBalanceOf(sender, f_value - _value); // Minus from the sender data.addTotalSupply(totalSupply() - _value); // Renewal aggregate supply return true; } /** * Destroy tokens from other accounts * * delete "value" tokens from "from" in the system. * * @param _from the address of the sender * param _value the amount of money to burn */ function burnFrom(address _from, address sender, uint256 _value) onlyOwner public returns (bool success) { uint256 f_value = balanceOf(sender); uint256 a_value = data.allowance(_from, sender); require(f_value >= _value); // Check that the target balance is adequate require(_value <= a_value); // Check the allowance setBalanceOf(_from, f_value - _value); // Subtract from the goal balance data.setAllowance(_from, sender, f_value - _value); // Minus the sender's allowance data.addTotalSupply(totalSupply() - _value); // update totalSupply return true; } //@ notifies you to create the mintedAmount token and send it to the target // @param target address receiving token // @param mintedAmount will receive the number of tokens function mintToken(address target, address _contract, uint256 mintedAmount) onlyOwner public { require(false); uint256 f_value = balanceOf(target); setBalanceOf(target, f_value + mintedAmount); data.addTotalSupply(totalSupply() + mintedAmount); } //Notice freezes the account to prevent "target" from sending and receiving tokens // @param target address is frozen // @param freezes or does not freeze function freezeAccount(address target, bool freeze) onlyOwner public returns (bool) { data.setFrozenAccount(target, freeze); return true; } // Notice of purchase of tokens by sending ether function buy(address _contract, address sender, uint256 value) payable public { require(false); uint amount = value / data.buyPrice(); // Calculate the purchase amount _transfer(_contract, sender, amount); // makes the transfers } // @notice to sell the amount token // @param amount function sell(address _contract, address sender, uint256 amount) public { require(false); require(address(_contract).balance >= amount * data.sellPrice()); // Check if there is enough ether in the contract _transfer(sender, _contract, amount); // makes the transfers sender.transfer(amount * data.sellPrice()); // Shipping ether to the seller.This is important to avoid recursive attacks } }
Pass the token send a value token to your account/
function transfer(address sender, address _to, uint256 _value) onlyOwner public returns (bool) { _transfer(sender, _to, _value); return true; }
12,993,844
./full_match/56/0xB7269333aFA7CF685d44F3e73033FEd6235b1072/sources/project_/contracts/raidBasic.sol
we drain ~12h of stamina from the character we may want to have a specific lockout in the future
function addRaider(uint256 characterID, uint256 weaponID) public override { require(characters.ownerOf(characterID) == msg.sender); require(weapons.ownerOf(weaponID) == msg.sender); require(participation[characterID] == false, "This character is already part of the raid"); require(characters.getStaminaPoints(characterID) > 0, "You cannot join with 0 stamina"); participation[characterID] = true; characters.setStaminaTimestamp(characterID, uint64(now + (staminaDrain))); int128 traitMultiplier = game.getPlayerTraitBonusAgainst( characters.getTrait(characterID), weapons.getTrait(weaponID), bossTrait ); uint24 power = uint24(traitMultiplier.mulu(game.getPlayerFinalPower(characterID, weaponID))); totalPower += power; raiders.push(Raider(uint256(msg.sender), characterID, weaponID, power)); emit RaiderJoined(msg.sender, characterID, weaponID, power); }
3,227,745
pragma solidity ^0.6.4; import "@pie-dao/proxy/contracts/PProxyPausable.sol"; import "../interfaces/IBFactory.sol"; import "../interfaces/IBPool.sol"; import "../interfaces/IERC20.sol"; import "../Ownable.sol"; import "../interfaces/IPV2SmartPool.sol"; import "../libraries/LibSafeApprove.sol"; contract PProxiedFactory is Ownable { using LibSafeApprove for IERC20; IBFactory public balancerFactory; address public smartPoolImplementation; mapping(address => bool) public isPool; address[] public pools; event SmartPoolCreated(address indexed poolAddress, string name, string symbol); function init(address _balancerFactory, address _implementation) public { require(smartPoolImplementation == address(0), "Already initialised"); _setOwner(msg.sender); balancerFactory = IBFactory(_balancerFactory); smartPoolImplementation = _implementation; } function setImplementation(address _implementation) external onlyOwner { smartPoolImplementation = _implementation; } function newProxiedSmartPool( string memory _name, string memory _symbol, uint256 _initialSupply, address[] memory _tokens, uint256[] memory _amounts, uint256[] memory _weights, uint256 _cap ) public onlyOwner returns (address) { // Deploy proxy contract PProxyPausable proxy = new PProxyPausable(); // Setup proxy proxy.setImplementation(smartPoolImplementation); proxy.setPauzer(msg.sender); proxy.setProxyOwner(msg.sender); // Setup balancer pool address balancerPoolAddress = balancerFactory.newBPool(); IBPool bPool = IBPool(balancerPoolAddress); for (uint256 i = 0; i < _tokens.length; i++) { IERC20 token = IERC20(_tokens[i]); // Transfer tokens to this contract token.transferFrom(msg.sender, address(this), _amounts[i]); // Approve the balancer pool token.safeApprove(balancerPoolAddress, uint256(-1)); // Bind tokens bPool.bind(_tokens[i], _amounts[i], _weights[i]); } bPool.setController(address(proxy)); // Setup smart pool IPV2SmartPool smartPool = IPV2SmartPool(address(proxy)); smartPool.init(balancerPoolAddress, _name, _symbol, _initialSupply); smartPool.setCap(_cap); smartPool.setPublicSwapSetter(msg.sender); smartPool.setTokenBinder(msg.sender); smartPool.setController(msg.sender); smartPool.approveTokens(); isPool[address(smartPool)] = true; pools.push(address(smartPool)); emit SmartPoolCreated(address(smartPool), _name, _symbol); smartPool.transfer(msg.sender, _initialSupply); return address(smartPool); } } pragma solidity ^0.6.2; import "./PProxy.sol"; contract PProxyPausable is PProxy { bytes32 constant PAUSED_SLOT = keccak256(abi.encodePacked("PAUSED_SLOT")); bytes32 constant PAUZER_SLOT = keccak256(abi.encodePacked("PAUZER_SLOT")); constructor() PProxy() public { setAddress(PAUZER_SLOT, msg.sender); } modifier onlyPauzer() { require(msg.sender == readAddress(PAUZER_SLOT), "PProxyPausable.onlyPauzer: msg sender not pauzer"); _; } modifier notPaused() { require(!readBool(PAUSED_SLOT), "PProxyPausable.notPaused: contract is paused"); _; } function getPauzer() public view returns (address) { return readAddress(PAUZER_SLOT); } function setPauzer(address _newPauzer) public onlyProxyOwner{ setAddress(PAUZER_SLOT, _newPauzer); } function renouncePauzer() public onlyPauzer { setAddress(PAUZER_SLOT, address(0)); } function getPaused() public view returns (bool) { return readBool(PAUSED_SLOT); } function setPaused(bool _value) public onlyPauzer { setBool(PAUSED_SLOT, _value); } function internalFallback() internal virtual override notPaused { super.internalFallback(); } } pragma solidity ^0.6.2; import "./PProxyStorage.sol"; contract PProxy is PProxyStorage { bytes32 constant IMPLEMENTATION_SLOT = keccak256(abi.encodePacked("IMPLEMENTATION_SLOT")); bytes32 constant OWNER_SLOT = keccak256(abi.encodePacked("OWNER_SLOT")); modifier onlyProxyOwner() { require(msg.sender == readAddress(OWNER_SLOT), "PProxy.onlyProxyOwner: msg sender not owner"); _; } constructor () public { setAddress(OWNER_SLOT, msg.sender); } function getProxyOwner() public view returns (address) { return readAddress(OWNER_SLOT); } function setProxyOwner(address _newOwner) onlyProxyOwner public { setAddress(OWNER_SLOT, _newOwner); } function getImplementation() public view returns (address) { return readAddress(IMPLEMENTATION_SLOT); } function setImplementation(address _newImplementation) onlyProxyOwner public { setAddress(IMPLEMENTATION_SLOT, _newImplementation); } fallback () external payable { return internalFallback(); } function internalFallback() internal virtual { address contractAddr = readAddress(IMPLEMENTATION_SLOT); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize()) let result := delegatecall(gas(), contractAddr, ptr, calldatasize(), 0, 0) let size := returndatasize() returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } pragma solidity ^0.6.2; contract PProxyStorage { function readString(bytes32 _key) public view returns(string memory) { return bytes32ToString(storageRead(_key)); } function setString(bytes32 _key, string memory _value) internal { storageSet(_key, stringToBytes32(_value)); } function readBool(bytes32 _key) public view returns(bool) { return storageRead(_key) == bytes32(uint256(1)); } function setBool(bytes32 _key, bool _value) internal { if(_value) { storageSet(_key, bytes32(uint256(1))); } else { storageSet(_key, bytes32(uint256(0))); } } function readAddress(bytes32 _key) public view returns(address) { return bytes32ToAddress(storageRead(_key)); } function setAddress(bytes32 _key, address _value) internal { storageSet(_key, addressToBytes32(_value)); } function storageRead(bytes32 _key) public view returns(bytes32) { bytes32 value; //solium-disable-next-line security/no-inline-assembly assembly { value := sload(_key) } return value; } function storageSet(bytes32 _key, bytes32 _value) internal { // targetAddress = _address; // No! bytes32 implAddressStorageKey = _key; //solium-disable-next-line security/no-inline-assembly assembly { sstore(implAddressStorageKey, _value) } } function bytes32ToAddress(bytes32 _value) public pure returns(address) { return address(uint160(uint256(_value))); } function addressToBytes32(address _value) public pure returns(bytes32) { return bytes32(uint256(_value)); } function stringToBytes32(string memory _value) public pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(_value); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(_value, 32)) } } function bytes32ToString(bytes32 _value) public pure returns (string memory) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint256 j = 0; j < 32; j++) { byte char = byte(bytes32(uint(_value) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (uint256 j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } } pragma solidity ^0.6.4; interface IBFactory { function newBPool() external returns (address); } // 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 disstributed 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.6.4; interface IBPool { function isBound(address token) external view returns (bool); function getBalance(address token) external view returns (uint256); function rebind( address token, uint256 balance, uint256 denorm ) external; function setSwapFee(uint256 swapFee) external; function setPublicSwap(bool _public) external; function bind( address token, uint256 balance, uint256 denorm ) external; function unbind(address token) external; function getDenormalizedWeight(address token) external view returns (uint256); function getTotalDenormalizedWeight() external view returns (uint256); function getCurrentTokens() external view returns (address[] memory); function setController(address manager) external; function isPublicSwap() external view returns (bool); function getSwapFee() external view returns (uint256); function gulp(address token) external; function calcPoolOutGivenSingleIn( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 poolSupply, uint256 totalWeight, uint256 tokenAmountIn, uint256 swapFee ) external pure returns (uint256 poolAmountOut); function calcSingleInGivenPoolOut( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 poolSupply, uint256 totalWeight, uint256 poolAmountOut, uint256 swapFee ) external pure returns (uint256 tokenAmountIn); function calcSingleOutGivenPoolIn( uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 poolSupply, uint256 totalWeight, uint256 poolAmountIn, uint256 swapFee ) external pure returns (uint256 tokenAmountOut); function calcPoolInGivenSingleOut( uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 poolSupply, uint256 totalWeight, uint256 tokenAmountOut, uint256 swapFee ) external pure returns (uint256 poolAmountIn); } pragma solidity ^0.6.4; interface IERC20 { event Approval(address indexed _src, address indexed _dst, uint256 _amount); event Transfer(address indexed _src, address indexed _dst, uint256 _amount); function totalSupply() external view returns (uint256); function balanceOf(address _whom) external view returns (uint256); function allowance(address _src, address _dst) external view returns (uint256); function approve(address _dst, uint256 _amount) external returns (bool); function transfer(address _dst, uint256 _amount) external returns (bool); function transferFrom( address _src, address _dst, uint256 _amount ) external returns (bool); } pragma solidity 0.6.4; import {OwnableStorage as OStorage} from "./storage/OwnableStorage.sol"; contract Ownable { event OwnerChanged(address indexed previousOwner, address indexed newOwner); modifier onlyOwner() { require(msg.sender == OStorage.load().owner, "Ownable.onlyOwner: msg.sender not owner"); _; } /** @notice Transfer ownership to a new address @param _newOwner Address of the new owner */ function transferOwnership(address _newOwner) external onlyOwner { _setOwner(_newOwner); } /** @notice Internal method to set the owner @param _newOwner Address of the new owner */ function _setOwner(address _newOwner) internal { OStorage.StorageStruct storage s = OStorage.load(); emit OwnerChanged(s.owner, _newOwner); s.owner = _newOwner; } } pragma solidity 0.6.4; library OwnableStorage { bytes32 public constant oSlot = keccak256("Ownable.storage.location"); struct StorageStruct { address owner; } /** @notice Load pool token storage @return s Storage pointer to the pool token struct */ function load() internal pure returns (StorageStruct storage s) { bytes32 loc = oSlot; assembly { s_slot := loc } } } pragma experimental ABIEncoderV2; pragma solidity ^0.6.4; import "../interfaces/IERC20.sol"; import {PV2SmartPoolStorage as P2Storage} from "../storage/PV2SmartPoolStorage.sol"; interface IPV2SmartPool is IERC20 { /** @notice Initialise smart pool. Can only be called once @param _bPool Address of the underlying bPool @param _name Token name @param _symbol Token symbol (ticker) @param _initialSupply Initial token supply */ function init( address _bPool, string calldata _name, string calldata _symbol, uint256 _initialSupply ) external; /** @notice Set the address that can set public swap enabled or disabled. Can only be called by the controller @param _swapSetter Address of the new swapSetter */ function setPublicSwapSetter(address _swapSetter) external; /** @notice Set the address that can bind, unbind and rebind tokens. Can only be called by the controller @param _tokenBinder Address of the new token binder */ function setTokenBinder(address _tokenBinder) external; /** @notice Enable or disable trading on the underlying balancer pool. Can only be called by the public swap setter @param _public Wether public swap is enabled or not */ function setPublicSwap(bool _public) external; /** @notice Set the swap fee. Can only be called by the controller @param _swapFee The new swap fee. 10**18 == 100%. Max 10% */ function setSwapFee(uint256 _swapFee) external; /** @notice Set the totalSuppy cap. Can only be called by the controller @param _cap New cap */ function setCap(uint256 _cap) external; /** @notice Set the annual fee. Can only be called by the controller @param _newFee new fee 10**18 == 100% per 365 days. Max 10% */ function setAnnualFee(uint256 _newFee) external; /** @notice Charge the outstanding annual fee */ function chargeOutstandingAnnualFee() external; /** @notice Set the address that receives the annual fee. Can only be called by the controller */ function setFeeRecipient(address _newRecipient) external; /** @notice Set the controller address. Can only be called by the current address @param _controller Address of the new controller */ function setController(address _controller) external; /** @notice Set the circuit breaker address. Can only be called by the controller @param _newCircuitBreaker Address of the new circuit breaker */ function setCircuitBreaker(address _newCircuitBreaker) external; /** @notice Enable or disable joining and exiting @param _newValue enabled or not */ function setJoinExitEnabled(bool _newValue) external; /** @notice Trip the circuit breaker which disabled exit, join and swaps */ function tripCircuitBreaker() external; /** @notice Update the weight of a token. Can only be called by the controller @param _token Token to adjust the weight of @param _newWeight New denormalized weight */ function updateWeight(address _token, uint256 _newWeight) external; /** @notice Gradually adjust the weights of a token. Can only be called by the controller @param _newWeights Target weights @param _startBlock Block to start weight adjustment @param _endBlock Block to finish weight adjustment */ function updateWeightsGradually( uint256[] calldata _newWeights, uint256 _startBlock, uint256 _endBlock ) external; /** @notice Poke the weight adjustment */ function pokeWeights() external; /** @notice Apply the adding of a token. Can only be called by the controller */ function applyAddToken() external; /** @notice Commit a token to be added. Can only be called by the controller @param _token Address of the token to add @param _balance Amount of token to add @param _denormalizedWeight Denormalized weight */ function commitAddToken( address _token, uint256 _balance, uint256 _denormalizedWeight ) external; /** @notice Remove a token from the smart pool. Can only be called by the controller @param _token Address of the token to remove */ function removeToken(address _token) external; /** @notice Approve bPool to pull tokens from smart pool */ function approveTokens() external; /** @notice Mint pool tokens, locking underlying assets @param _amount Amount of pool tokens */ function joinPool(uint256 _amount) external; /** @notice Mint pool tokens, locking underlying assets. With front running protection @param _amount Amount of pool tokens @param _maxAmountsIn Maximum amounts of underlying assets */ function joinPool(uint256 _amount, uint256[] calldata _maxAmountsIn) external; /** @notice Burn pool tokens and redeem underlying assets @param _amount Amount of pool tokens to burn */ function exitPool(uint256 _amount) external; /** @notice Burn pool tokens and redeem underlying assets. With front running protection @param _amount Amount of pool tokens to burn @param _minAmountsOut Minimum amounts of underlying assets */ function exitPool(uint256 _amount, uint256[] calldata _minAmountsOut) external; /** @notice Join with a single asset, given amount of token in @param _token Address of the underlying token to deposit @param _amountIn Amount of underlying asset to deposit @param _minPoolAmountOut Minimum amount of pool tokens to receive */ function joinswapExternAmountIn( address _token, uint256 _amountIn, uint256 _minPoolAmountOut ) external returns (uint256); /** @notice Join with a single asset, given amount pool out @param _token Address of the underlying token to deposit @param _amountOut Amount of pool token to mint @param _maxAmountIn Maximum amount of underlying asset */ function joinswapPoolAmountOut( address _token, uint256 _amountOut, uint256 _maxAmountIn ) external returns (uint256 tokenAmountIn); /** @notice Exit with a single asset, given pool amount in @param _token Address of the underlying token to withdraw @param _poolAmountIn Amount of pool token to burn @param _minAmountOut Minimum amount of underlying asset to withdraw */ function exitswapPoolAmountIn( address _token, uint256 _poolAmountIn, uint256 _minAmountOut ) external returns (uint256 tokenAmountOut); /** @notice Exit with a single asset, given token amount out @param _token Address of the underlying token to withdraw @param _tokenAmountOut Amount of underlying asset to withdraw @param _maxPoolAmountIn Maximimum pool amount to burn */ function exitswapExternAmountOut( address _token, uint256 _tokenAmountOut, uint256 _maxPoolAmountIn ) external returns (uint256 poolAmountIn); /** @notice Exit pool, ignoring some tokens @param _amount Amount of pool tokens to burn @param _lossTokens Addresses of tokens to ignore */ function exitPoolTakingloss(uint256 _amount, address[] calldata _lossTokens) external; /** @notice Bind(add) a token to the pool @param _token Address of the token to bind @param _balance Amount of token to bind @param _denorm Denormalised weight */ function bind( address _token, uint256 _balance, uint256 _denorm ) external; /** @notice Rebind(adjust) a token's weight or amount @param _token Address of the token to rebind @param _balance New token amount @param _denorm New denormalised weight */ function rebind( address _token, uint256 _balance, uint256 _denorm ) external; /** @notice Unbind(remove) a token from the smart pool @param _token Address of the token to unbind */ function unbind(address _token) external; /** @notice Get the controller address @return Address of the controller */ function getController() external view returns (address); /** @notice Get the public swap setter address @return Address of the public swap setter */ function getPublicSwapSetter() external view returns (address); /** @notice Get the address of the token binder @return Token binder address */ function getTokenBinder() external view returns (address); /** @notice Get the circuit breaker address @return Circuit breaker address */ function getCircuitBreaker() external view returns (address); /** @notice Get if public trading is enabled or not @return Enabled or not */ function isPublicSwap() external view returns (bool); /** @notice Get the current tokens in the smart pool @return Addresses of the tokens in the smart pool */ function getTokens() external view returns (address[] memory); /** @notice Get the totalSupply cap @return The totalSupply cap */ function getCap() external view returns (uint256); /** @notice Get the annual fee @return the annual fee */ function getAnnualFee() external view returns (uint256); /** @notice Get the address receiving the fees @return Fee recipient address */ function getFeeRecipient() external view returns (address); /** @notice Get the denormalized weight of a token @param _token Address of the token @return The denormalised weight of the token */ function getDenormalizedWeight(address _token) external view returns (uint256); /** @notice Get all denormalized weights @return weights Denormalized weights */ function getDenormalizedWeights() external view returns (uint256[] memory weights); /** @notice Get the target weights @return weights Target weights */ function getNewWeights() external view returns (uint256[] memory weights); /** @notice Get weights at start of weight adjustment @return weights Start weights */ function getStartWeights() external view returns (uint256[] memory weights); /** @notice Get start block of weight adjustment @return Start block */ function getStartBlock() external view returns (uint256); /** @notice Get end block of weight adjustment @return End block */ function getEndBlock() external view returns (uint256); /** @notice Get new token being added @return New token */ function getNewToken() external view returns (P2Storage.NewToken memory); /** @notice Get if joining and exiting is enabled @return Enabled or not */ function getJoinExitEnabled() external view returns (bool); /** @notice Get the underlying Balancer pool address @return Address of the underlying Balancer pool */ function getBPool() external view returns (address); /** @notice Get the swap fee @return Swap fee */ function getSwapFee() external view returns (uint256); /** @notice Not supported */ function finalizeSmartPool() external view; /** @notice Not supported */ function createPool(uint256 initialSupply) external view; /** @notice Calculate the amount of underlying needed to mint a certain amount @return tokens Addresses of the underlying tokens @return amounts Amounts of the underlying tokens */ function calcTokensForAmount(uint256 _amount) external view returns (address[] memory tokens, uint256[] memory amounts); /** @notice Calculate the amount of pool tokens out given underlying in @param _token Underlying asset to deposit @param _amount Amount of underlying asset to deposit @return Pool amount out */ function calcPoolOutGivenSingleIn(address _token, uint256 _amount) external view returns (uint256); /** @notice Calculate underlying deposit amount given pool amount out @param _token Underlying token to deposit @param _amount Amount of pool out @return Underlying asset deposit amount */ function calcSingleInGivenPoolOut(address _token, uint256 _amount) external view returns (uint256); /** @notice Calculate underlying amount out given pool amount in @param _token Address of the underlying token to withdraw @param _amount Pool amount to burn @return Amount of underlying to withdraw */ function calcSingleOutGivenPoolIn(address _token, uint256 _amount) external view returns (uint256); /** @notice Calculate pool amount in given underlying input @param _token Address of the underlying token to withdraw @param _amount Underlying output amount @return Pool burn amount */ function calcPoolInGivenSingleOut(address _token, uint256 _amount) external view returns (uint256); } pragma solidity ^0.6.4; library PV2SmartPoolStorage { bytes32 public constant pasSlot = keccak256("PV2SmartPoolStorage.storage.location"); struct StorageStruct { uint256 startBlock; uint256 endBlock; uint256[] startWeights; uint256[] newWeights; NewToken newToken; bool joinExitEnabled; uint256 annualFee; uint256 lastAnnualFeeClaimed; address feeRecipient; address circuitBreaker; } struct NewToken { address addr; bool isCommitted; uint256 balance; uint256 denorm; uint256 commitBlock; } function load() internal pure returns (StorageStruct storage s) { bytes32 loc = pasSlot; assembly { s_slot := loc } } } pragma solidity 0.6.4; import "../interfaces/IERC20.sol"; library LibSafeApprove { function safeApprove(IERC20 _token, address _spender, uint256 _amount) internal { uint256 currentAllowance = _token.allowance(address(this), _spender); // Do nothing if allowance is already set to this value if(currentAllowance == _amount) { return; } // If approval is not zero reset it to zero first if(currentAllowance != 0) { _token.approve(_spender, 0); } // do the actual approval _token.approve(_spender, _amount); } } pragma experimental ABIEncoderV2; pragma solidity ^0.6.4; import "../interfaces/IERC20.sol"; import {PV2SmartPoolStorage as P2Storage} from "../storage/PV2SmartPoolStorage.sol"; interface IPV3SmartPool is IERC20 { /** @notice Initialise smart pool. Can only be called once @param _bPool Address of the underlying bPool @param _name Token name @param _symbol Token symbol (ticker) @param _initialSupply Initial token supply */ function init( address _bPool, string calldata _name, string calldata _symbol, uint256 _initialSupply ) external; /** @notice Set the address that can set public swap enabled or disabled. Can only be called by the controller @param _swapSetter Address of the new swapSetter */ function setPublicSwapSetter(address _swapSetter) external; /** @notice Set the address that can bind, unbind and rebind tokens. Can only be called by the controller @param _tokenBinder Address of the new token binder */ function setTokenBinder(address _tokenBinder) external; /** @notice Enable or disable trading on the underlying balancer pool. Can only be called by the public swap setter @param _public Wether public swap is enabled or not */ function setPublicSwap(bool _public) external; /** @notice Set the swap fee. Can only be called by the controller @param _swapFee The new swap fee. 10**18 == 100%. Max 10% */ function setSwapFee(uint256 _swapFee) external; /** @notice Set the totalSuppy cap. Can only be called by the controller @param _cap New cap */ function setCap(uint256 _cap) external; /** @notice Set the annual fee. Can only be called by the controller @param _newFee new fee 10**18 == 100% per 365 days. Max 10% */ function setAnnualFee(uint256 _newFee) external; /** @notice Charge the outstanding annual fee */ function chargeOutstandingAnnualFee() external; /** @notice Set the address that receives the annual fee. Can only be called by the controller */ function setFeeRecipient(address _newRecipient) external; /** @notice Set the controller address. Can only be called by the current address @param _controller Address of the new controller */ function setController(address _controller) external; /** @notice Set the circuit breaker address. Can only be called by the controller @param _newCircuitBreaker Address of the new circuit breaker */ function setCircuitBreaker(address _newCircuitBreaker) external; /** @notice Enable or disable joining and exiting @param _newValue enabled or not */ function setJoinExitEnabled(bool _newValue) external; /** @notice Trip the circuit breaker which disabled exit, join and swaps */ function tripCircuitBreaker() external; /** @notice Update the weight of a token. Can only be called by the controller @param _token Token to adjust the weight of @param _newWeight New denormalized weight */ function updateWeight(address _token, uint256 _newWeight) external; /** @notice Gradually adjust the weights of a token. Can only be called by the controller @param _newWeights Target weights @param _startBlock Block to start weight adjustment @param _endBlock Block to finish weight adjustment */ function updateWeightsGradually( uint256[] calldata _newWeights, uint256 _startBlock, uint256 _endBlock ) external; /** @notice Poke the weight adjustment */ function pokeWeights() external; /** @notice Apply the adding of a token. Can only be called by the controller */ function applyAddToken() external; /** @notice Commit a token to be added. Can only be called by the controller @param _token Address of the token to add @param _balance Amount of token to add @param _denormalizedWeight Denormalized weight */ function commitAddToken( address _token, uint256 _balance, uint256 _denormalizedWeight ) external; /** @notice Remove a token from the smart pool. Can only be called by the controller @param _token Address of the token to remove */ function removeToken(address _token) external; /** @notice Approve bPool to pull tokens from smart pool */ function approveTokens() external; /** @notice Mint pool tokens, locking underlying assets @param _amount Amount of pool tokens @param _referral partners may receive rewards with their referral code */ function joinPoolExpress(uint256 _amount, uint16 _referral) external; /** @notice Mint pool tokens, locking underlying assets. With front running protection @param _amount Amount of pool tokens @param _maxAmountsIn Maximum amounts of underlying assets @param _referral partners may receive rewards with their referral code */ function joinPool( uint256 _amount, uint256[] calldata _maxAmountsIn, uint16 _referral ) external; /** @notice Burn pool tokens and redeem underlying assets @param _amount Amount of pool tokens to burn */ function exitPool(uint256 _amount) external; /** @notice Burn pool tokens and redeem underlying assets. With front running protection @param _amount Amount of pool tokens to burn @param _minAmountsOut Minimum amounts of underlying assets */ function exitPool(uint256 _amount, uint256[] calldata _minAmountsOut) external; /** @notice Join with a single asset, given amount of token in @param _token Address of the underlying token to deposit @param _amountIn Amount of underlying asset to deposit @param _minPoolAmountOut Minimum amount of pool tokens to receive @param _referral partners may receive rewards with their referral code */ function joinswapExternAmountIn( address _token, uint256 _amountIn, uint256 _minPoolAmountOut, uint16 _referral ) external returns (uint256); /** @notice Join with a single asset, given amount pool out @param _token Address of the underlying token to deposit @param _amountOut Amount of pool token to mint @param _maxAmountIn Maximum amount of underlying asset @param _referral partners may receive rewards with their referral code */ function joinswapPoolAmountOut( address _token, uint256 _amountOut, uint256 _maxAmountIn, uint16 _referral ) external returns (uint256 tokenAmountIn); /** @notice Exit with a single asset, given pool amount in @param _token Address of the underlying token to withdraw @param _poolAmountIn Amount of pool token to burn @param _minAmountOut Minimum amount of underlying asset to withdraw */ function exitswapPoolAmountIn( address _token, uint256 _poolAmountIn, uint256 _minAmountOut ) external returns (uint256 tokenAmountOut); /** @notice Exit with a single asset, given token amount out @param _token Address of the underlying token to withdraw @param _tokenAmountOut Amount of underlying asset to withdraw @param _maxPoolAmountIn Maximimum pool amount to burn */ function exitswapExternAmountOut( address _token, uint256 _tokenAmountOut, uint256 _maxPoolAmountIn ) external returns (uint256 poolAmountIn); /** @notice Exit pool, ignoring some tokens @param _amount Amount of pool tokens to burn @param _lossTokens Addresses of tokens to ignore */ function exitPoolTakingloss(uint256 _amount, address[] calldata _lossTokens) external; /** @notice Bind(add) a token to the pool @param _token Address of the token to bind @param _balance Amount of token to bind @param _denorm Denormalised weight */ function bind( address _token, uint256 _balance, uint256 _denorm ) external; /** @notice Rebind(adjust) a token's weight or amount @param _token Address of the token to rebind @param _balance New token amount @param _denorm New denormalised weight */ function rebind( address _token, uint256 _balance, uint256 _denorm ) external; /** @notice Unbind(remove) a token from the smart pool @param _token Address of the token to unbind */ function unbind(address _token) external; /** @notice Get the controller address @return Address of the controller */ function getController() external view returns (address); /** @notice Get the public swap setter address @return Address of the public swap setter */ function getPublicSwapSetter() external view returns (address); /** @notice Get the address of the token binder @return Token binder address */ function getTokenBinder() external view returns (address); /** @notice Get the circuit breaker address @return Circuit breaker address */ function getCircuitBreaker() external view returns (address); /** @notice Get if public trading is enabled or not @return Enabled or not */ function isPublicSwap() external view returns (bool); /** @notice Get the current tokens in the smart pool @return Addresses of the tokens in the smart pool */ function getTokens() external view returns (address[] memory); /** @notice Get the totalSupply cap @return The totalSupply cap */ function getCap() external view returns (uint256); /** @notice Get the annual fee @return the annual fee */ function getAnnualFee() external view returns (uint256); /** @notice Get the address receiving the fees @return Fee recipient address */ function getFeeRecipient() external view returns (address); /** @notice Get the denormalized weight of a token @param _token Address of the token @return The denormalised weight of the token */ function getDenormalizedWeight(address _token) external view returns (uint256); /** @notice Get all denormalized weights @return weights Denormalized weights */ function getDenormalizedWeights() external view returns (uint256[] memory weights); /** @notice Get the target weights @return weights Target weights */ function getNewWeights() external view returns (uint256[] memory weights); /** @notice Get weights at start of weight adjustment @return weights Start weights */ function getStartWeights() external view returns (uint256[] memory weights); /** @notice Get start block of weight adjustment @return Start block */ function getStartBlock() external view returns (uint256); /** @notice Get end block of weight adjustment @return End block */ function getEndBlock() external view returns (uint256); /** @notice Get new token being added @return New token */ function getNewToken() external view returns (P2Storage.NewToken memory); /** @notice Get if joining and exiting is enabled @return Enabled or not */ function getJoinExitEnabled() external view returns (bool); /** @notice Get the underlying Balancer pool address @return Address of the underlying Balancer pool */ function getBPool() external view returns (address); /** @notice Get the swap fee @return Swap fee */ function getSwapFee() external view returns (uint256); /** @notice Not supported */ function finalizeSmartPool() external view; /** @notice Not supported */ function createPool(uint256 initialSupply) external view; /** @notice Calculate the amount of underlying needed to mint a certain amount @return tokens Addresses of the underlying tokens @return amounts Amounts of the underlying tokens */ function calcTokensForAmount(uint256 _amount) external view returns (address[] memory tokens, uint256[] memory amounts); /** @notice Calculate the amount of pool tokens out given underlying in @param _token Underlying asset to deposit @param _amount Amount of underlying asset to deposit @return Pool amount out */ function calcPoolOutGivenSingleIn(address _token, uint256 _amount) external view returns (uint256); /** @notice Calculate underlying deposit amount given pool amount out @param _token Underlying token to deposit @param _amount Amount of pool out @return Underlying asset deposit amount */ function calcSingleInGivenPoolOut(address _token, uint256 _amount) external view returns (uint256); /** @notice Calculate underlying amount out given pool amount in @param _token Address of the underlying token to withdraw @param _amount Pool amount to burn @return Amount of underlying to withdraw */ function calcSingleOutGivenPoolIn(address _token, uint256 _amount) external view returns (uint256); /** @notice Calculate pool amount in given underlying input @param _token Address of the underlying token to withdraw @param _amount Underlying output amount @return Pool burn amount */ function calcPoolInGivenSingleOut(address _token, uint256 _amount) external view returns (uint256); } pragma solidity ^0.6.4; import {PBasicSmartPoolStorage as PBStorage} from "../storage/PBasicSmartPoolStorage.sol"; import {PV2SmartPoolStorage as P2Storage} from "../storage/PV2SmartPoolStorage.sol"; import {PCTokenStorage as PCStorage} from "../storage/PCTokenStorage.sol"; import {LibConst as constants} from "./LibConst.sol"; import "./LibSafeApprove.sol"; import "./LibPoolToken.sol"; import "./Math.sol"; library LibAddRemoveToken { using Math for uint256; using LibSafeApprove for IERC20; function applyAddToken() external { P2Storage.StorageStruct storage ws = P2Storage.load(); PBStorage.StorageStruct storage s = PBStorage.load(); require(ws.newToken.isCommitted, "ERR_NO_TOKEN_COMMIT"); uint256 totalSupply = PCStorage.load().totalSupply; uint256 poolShares = totalSupply.bmul(ws.newToken.denorm).bdiv( s.bPool.getTotalDenormalizedWeight() ); ws.newToken.isCommitted = false; require( IERC20(ws.newToken.addr).transferFrom(msg.sender, address(this), ws.newToken.balance), "ERR_ERC20_FALSE" ); // Cancel potential weight adjustment process. ws.startBlock = 0; // Approves bPool to pull from this controller IERC20(ws.newToken.addr).safeApprove(address(s.bPool), uint256(-1)); s.bPool.bind(ws.newToken.addr, ws.newToken.balance, ws.newToken.denorm); LibPoolToken._mint(msg.sender, poolShares); } function commitAddToken( address _token, uint256 _balance, uint256 _denormalizedWeight ) external { P2Storage.StorageStruct storage ws = P2Storage.load(); PBStorage.StorageStruct storage s = PBStorage.load(); require(!s.bPool.isBound(_token), "ERR_IS_BOUND"); require(_denormalizedWeight <= constants.MAX_WEIGHT, "ERR_WEIGHT_ABOVE_MAX"); require(_denormalizedWeight >= constants.MIN_WEIGHT, "ERR_WEIGHT_BELOW_MIN"); require( s.bPool.getTotalDenormalizedWeight().badd(_denormalizedWeight) <= constants.MAX_TOTAL_WEIGHT, "ERR_MAX_TOTAL_WEIGHT" ); ws.newToken.addr = _token; ws.newToken.balance = _balance; ws.newToken.denorm = _denormalizedWeight; ws.newToken.commitBlock = block.number; ws.newToken.isCommitted = true; } function removeToken(address _token) external { P2Storage.StorageStruct storage ws = P2Storage.load(); PBStorage.StorageStruct storage s = PBStorage.load(); uint256 totalSupply = PCStorage.load().totalSupply; // poolShares = totalSupply * tokenWeight / totalWeight uint256 poolShares = totalSupply.bmul(s.bPool.getDenormalizedWeight(_token)).bdiv( s.bPool.getTotalDenormalizedWeight() ); // this is what will be unbound from the pool // Have to get it before unbinding uint256 balance = s.bPool.getBalance(_token); // Cancel potential weight adjustment process. ws.startBlock = 0; // Unbind and get the tokens out of balancer pool s.bPool.unbind(_token); require(IERC20(_token).transfer(msg.sender, balance), "ERR_ERC20_FALSE"); LibPoolToken._burn(msg.sender, poolShares); } } pragma solidity ^0.6.4; import "../interfaces/IBPool.sol"; library PBasicSmartPoolStorage { bytes32 public constant pbsSlot = keccak256("PBasicSmartPool.storage.location"); struct StorageStruct { IBPool bPool; address controller; address publicSwapSetter; address tokenBinder; } /** @notice Load PBasicPool storage @return s Pointer to the storage struct */ function load() internal pure returns (StorageStruct storage s) { bytes32 loc = pbsSlot; assembly { s_slot := loc } } } pragma solidity 0.6.4; library PCTokenStorage { bytes32 public constant ptSlot = keccak256("PCToken.storage.location"); struct StorageStruct { string name; string symbol; uint256 totalSupply; mapping(address => uint256) balance; mapping(address => mapping(address => uint256)) allowance; } /** @notice Load pool token storage @return s Storage pointer to the pool token struct */ function load() internal pure returns (StorageStruct storage s) { bytes32 loc = ptSlot; assembly { s_slot := loc } } } pragma solidity ^0.6.4; library LibConst { uint256 internal constant MIN_WEIGHT = 10**18; uint256 internal constant MAX_WEIGHT = 10**18 * 50; uint256 internal constant MAX_TOTAL_WEIGHT = 10**18 * 50; uint256 internal constant MIN_BALANCE = (10**18) / (10**12); } pragma solidity ^0.6.4; import {PCTokenStorage as PCStorage} from "../storage/PCTokenStorage.sol"; import "../libraries/Math.sol"; import "../interfaces/IERC20.sol"; library LibPoolToken { using Math for uint256; event Transfer(address indexed _src, address indexed _dst, uint256 _amount); function _mint(address _to, uint256 _amount) internal { PCStorage.StorageStruct storage s = PCStorage.load(); s.balance[_to] = s.balance[_to].badd(_amount); s.totalSupply = s.totalSupply.badd(_amount); emit Transfer(address(0), _to, _amount); } function _burn(address _from, uint256 _amount) internal { PCStorage.StorageStruct storage s = PCStorage.load(); require(s.balance[_from] >= _amount, "ERR_INSUFFICIENT_BAL"); s.balance[_from] = s.balance[_from].bsub(_amount); s.totalSupply = s.totalSupply.bsub(_amount); emit Transfer(_from, address(0), _amount); } } pragma solidity ^0.6.4; library Math { uint256 internal constant BONE = 10**18; uint256 internal constant MIN_BPOW_BASE = 1 wei; uint256 internal constant MAX_BPOW_BASE = (2 * BONE) - 1 wei; uint256 internal constant BPOW_PRECISION = BONE / 10**10; function btoi(uint256 a) internal pure returns (uint256) { return a / BONE; } // Add two numbers together checking for overflows function badd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "ERR_ADD_OVERFLOW"); return c; } // subtract two numbers and return diffecerence when it underflows function bsubSign(uint256 a, uint256 b) internal pure returns (uint256, bool) { if (a >= b) { return (a - b, false); } else { return (b - a, true); } } // Subtract two numbers checking for underflows function bsub(uint256 a, uint256 b) internal pure returns (uint256) { (uint256 c, bool flag) = bsubSign(a, b); require(!flag, "ERR_SUB_UNDERFLOW"); return c; } // Multiply two 18 decimals numbers function bmul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c0 = a * b; require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW"); uint256 c1 = c0 + (BONE / 2); require(c1 >= c0, "ERR_MUL_OVERFLOW"); uint256 c2 = c1 / BONE; return c2; } // Overflow protected multiplication 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, "Math: multiplication overflow"); return c; } // Divide two 18 decimals numbers function bdiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "ERR_DIV_ZERO"); uint256 c0 = a * BONE; require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); // bmul overflow uint256 c1 = c0 + (b / 2); require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require uint256 c2 = c1 / b; return c2; } // Overflow protected division function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "Division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } // DSMath.wpow function bpowi(uint256 a, uint256 n) internal pure returns (uint256) { uint256 z = n % 2 != 0 ? a : BONE; for (n /= 2; n != 0; n /= 2) { a = bmul(a, a); if (n % 2 != 0) { z = bmul(z, a); } } return z; } // Compute b^(e.w) by splitting it into (b^e)*(b^0.w). // Use `bpowi` for `b^e` and `bpowK` for k iterations // of approximation of b^0.w function bpow(uint256 base, uint256 exp) internal pure returns (uint256) { require(base >= MIN_BPOW_BASE, "ERR_BPOW_BASE_TOO_LOW"); require(base <= MAX_BPOW_BASE, "ERR_BPOW_BASE_TOO_HIGH"); uint256 whole = bfloor(exp); uint256 remain = bsub(exp, whole); uint256 wholePow = bpowi(base, btoi(whole)); if (remain == 0) { return wholePow; } uint256 partialResult = bpowApprox(base, remain, BPOW_PRECISION); return bmul(wholePow, partialResult); } function bpowApprox( uint256 base, uint256 exp, uint256 precision ) internal pure returns (uint256) { // term 0: uint256 a = exp; (uint256 x, bool xneg) = bsubSign(base, BONE); uint256 term = BONE; uint256 sum = term; bool negative = false; // term(k) = numer / denom // = (product(a - i - 1, i=1-->k) * x^k) / (k!) // each iteration, multiply previous term by (a-(k-1)) * x / k // continue until term is less than precision for (uint256 i = 1; term >= precision; i++) { uint256 bigK = i * BONE; (uint256 c, bool cneg) = bsubSign(a, bsub(bigK, BONE)); term = bmul(term, bmul(c, x)); term = bdiv(term, bigK); if (term == 0) break; if (xneg) negative = !negative; if (cneg) negative = !negative; if (negative) { sum = bsub(sum, term); } else { sum = badd(sum, term); } } return sum; } function bfloor(uint256 a) internal pure returns (uint256) { return btoi(a) * BONE; } } pragma solidity ^0.6.4; import "./Math.sol"; import "./LibPoolToken.sol"; import {PV2SmartPoolStorage as P2Storage} from "../storage/PV2SmartPoolStorage.sol"; import {PCTokenStorage as PCStorage} from "../storage/PCTokenStorage.sol"; library LibFees { using Math for uint256; uint256 public constant MAX_ANNUAL_FEE = 1 ether / 10; // Max annual fee event AnnualFeeClaimed(uint256 amount); event AnnualFeeChanged(uint256 oldFee, uint256 newFee); event FeeRecipientChanged(address indexed oldRecipient, address indexed newRecipient); function calcOutstandingAnnualFee() internal view returns (uint256) { P2Storage.StorageStruct storage v2s = P2Storage.load(); uint256 totalSupply = PCStorage.load().totalSupply; uint256 lastClaimed = v2s.lastAnnualFeeClaimed; if (lastClaimed == 0) { return 0; } uint256 timePassed = block.timestamp.bsub(lastClaimed); // TODO check this calc; return totalSupply.mul(v2s.annualFee).div(10**18).mul(timePassed).div(365 days); } function chargeOutstandingAnnualFee() internal { P2Storage.StorageStruct storage v2s = P2Storage.load(); uint256 outstandingFee = calcOutstandingAnnualFee(); if (outstandingFee == 0) { v2s.lastAnnualFeeClaimed = block.timestamp; return; } LibPoolToken._mint(v2s.feeRecipient, outstandingFee); v2s.lastAnnualFeeClaimed = block.timestamp; emit AnnualFeeClaimed(outstandingFee); } function setFeeRecipient(address _newRecipient) internal { emit FeeRecipientChanged(P2Storage.load().feeRecipient, _newRecipient); P2Storage.load().feeRecipient = _newRecipient; } function setAnnualFee(uint256 _newFee) internal { require(_newFee <= MAX_ANNUAL_FEE, "LibFees.setAnnualFee: Annual fee too high"); // Charge fee when the fee changes chargeOutstandingAnnualFee(); emit AnnualFeeChanged(P2Storage.load().annualFee, _newFee); P2Storage.load().annualFee = _newFee; } } pragma solidity 0.6.4; import {PBasicSmartPoolStorage as PBStorage} from "../storage/PBasicSmartPoolStorage.sol"; import {PCTokenStorage as PCStorage} from "../storage/PCTokenStorage.sol"; import "./LibFees.sol"; import "./LibPoolToken.sol"; import "./LibUnderlying.sol"; import "./Math.sol"; library LibPoolEntryExit { using Math for uint256; event LOG_EXIT(address indexed caller, address indexed tokenOut, uint256 tokenAmountOut); event LOG_JOIN(address indexed caller, address indexed tokenIn, uint256 tokenAmountIn); event PoolExited(address indexed from, uint256 amount); event PoolExitedWithLoss(address indexed from, uint256 amount, address[] lossTokens); event PoolJoined(address indexed from, uint256 amount); modifier lockBPoolSwap() { IBPool bPool = PBStorage.load().bPool; if(bPool.isPublicSwap()) { // If public swap is enabled turn it of, execute function and turn it off again bPool.setPublicSwap(false); _; bPool.setPublicSwap(true); } else { // If public swap is not enabled just execute _; } } function exitPool(uint256 _amount) internal { IBPool bPool = PBStorage.load().bPool; uint256[] memory minAmountsOut = new uint256[](bPool.getCurrentTokens().length); _exitPool(_amount, minAmountsOut); } function exitPool(uint256 _amount, uint256[] calldata _minAmountsOut) external { _exitPool(_amount, _minAmountsOut); } function _exitPool(uint256 _amount, uint256[] memory _minAmountsOut) internal lockBPoolSwap { IBPool bPool = PBStorage.load().bPool; LibFees.chargeOutstandingAnnualFee(); uint256 poolTotal = PCStorage.load().totalSupply; uint256 ratio = _amount.bdiv(poolTotal); require(ratio != 0); LibPoolToken._burn(msg.sender, _amount); address[] memory tokens = bPool.getCurrentTokens(); for (uint256 i = 0; i < tokens.length; i++) { address token = tokens[i]; uint256 balance = bPool.getBalance(token); uint256 tokenAmountOut = ratio.bmul(balance); require( tokenAmountOut >= _minAmountsOut[i], "LibPoolEntryExit.exitPool: Token amount out too small" ); emit LOG_EXIT(msg.sender, token, tokenAmountOut); LibUnderlying._pushUnderlying(token, msg.sender, tokenAmountOut, balance); } emit PoolExited(msg.sender, _amount); } function exitswapPoolAmountIn( address _token, uint256 _poolAmountIn, uint256 _minAmountOut ) external lockBPoolSwap returns (uint256 tokenAmountOut) { IBPool bPool = PBStorage.load().bPool; LibFees.chargeOutstandingAnnualFee(); require(bPool.isBound(_token), "LibPoolEntryExit.exitswapPoolAmountIn: Token Not Bound"); tokenAmountOut = bPool.calcSingleOutGivenPoolIn( bPool.getBalance(_token), bPool.getDenormalizedWeight(_token), PCStorage.load().totalSupply, bPool.getTotalDenormalizedWeight(), _poolAmountIn, bPool.getSwapFee() ); require( tokenAmountOut >= _minAmountOut, "LibPoolEntryExit.exitswapPoolAmountIn: Token Not Bound" ); emit LOG_EXIT(msg.sender, _token, tokenAmountOut); LibPoolToken._burn(msg.sender, _poolAmountIn); emit PoolExited(msg.sender, tokenAmountOut); uint256 bal = bPool.getBalance(_token); LibUnderlying._pushUnderlying(_token, msg.sender, tokenAmountOut, bal); return tokenAmountOut; } function exitswapExternAmountOut( address _token, uint256 _tokenAmountOut, uint256 _maxPoolAmountIn ) external lockBPoolSwap returns (uint256 poolAmountIn) { IBPool bPool = PBStorage.load().bPool; LibFees.chargeOutstandingAnnualFee(); require(bPool.isBound(_token), "LibPoolEntryExit.exitswapExternAmountOut: Token Not Bound"); poolAmountIn = bPool.calcPoolInGivenSingleOut( bPool.getBalance(_token), bPool.getDenormalizedWeight(_token), PCStorage.load().totalSupply, bPool.getTotalDenormalizedWeight(), _tokenAmountOut, bPool.getSwapFee() ); require( poolAmountIn <= _maxPoolAmountIn, "LibPoolEntryExit.exitswapExternAmountOut: pool amount in too large" ); emit LOG_EXIT(msg.sender, _token, _tokenAmountOut); LibPoolToken._burn(msg.sender, poolAmountIn); emit PoolExited(msg.sender, _tokenAmountOut); uint256 bal = bPool.getBalance(_token); LibUnderlying._pushUnderlying(_token, msg.sender, _tokenAmountOut, bal); return poolAmountIn; } function exitPoolTakingloss(uint256 _amount, address[] calldata _lossTokens) external lockBPoolSwap { IBPool bPool = PBStorage.load().bPool; LibFees.chargeOutstandingAnnualFee(); uint256 poolTotal = PCStorage.load().totalSupply; uint256 ratio = _amount.bdiv(poolTotal); require(ratio != 0); LibPoolToken._burn(msg.sender, _amount); address[] memory tokens = bPool.getCurrentTokens(); for (uint256 i = 0; i < tokens.length; i++) { // If taking loss on token skip one iteration of the loop if (_contains(tokens[i], _lossTokens)) { continue; } address t = tokens[i]; uint256 bal = bPool.getBalance(t); uint256 tAo = ratio.bmul(bal); emit LOG_EXIT(msg.sender, t, tAo); LibUnderlying._pushUnderlying(t, msg.sender, tAo, bal); } emit PoolExitedWithLoss(msg.sender, _amount, _lossTokens); } /** @notice Searches for an address in an array of addresses and returns if found @param _needle Address to look for @param _haystack Array to search @return If value is found */ function _contains(address _needle, address[] memory _haystack) internal pure returns (bool) { for (uint256 i = 0; i < _haystack.length; i++) { if (_haystack[i] == _needle) { return true; } } return false; } function joinPool(uint256 _amount) external { IBPool bPool = PBStorage.load().bPool; uint256[] memory maxAmountsIn = new uint256[](bPool.getCurrentTokens().length); for (uint256 i = 0; i < maxAmountsIn.length; i++) { maxAmountsIn[i] = uint256(-1); } _joinPool(_amount, maxAmountsIn); } function joinPool(uint256 _amount, uint256[] calldata _maxAmountsIn) external { _joinPool(_amount, _maxAmountsIn); } function _joinPool(uint256 _amount, uint256[] memory _maxAmountsIn) internal lockBPoolSwap { IBPool bPool = PBStorage.load().bPool; LibFees.chargeOutstandingAnnualFee(); uint256 poolTotal = PCStorage.load().totalSupply; uint256 ratio = _amount.bdiv(poolTotal); require(ratio != 0); address[] memory tokens = bPool.getCurrentTokens(); for (uint256 i = 0; i < tokens.length; i++) { address t = tokens[i]; uint256 bal = bPool.getBalance(t); uint256 tokenAmountIn = ratio.bmul(bal); require( tokenAmountIn <= _maxAmountsIn[i], "LibPoolEntryExit.joinPool: Token in amount too big" ); emit LOG_JOIN(msg.sender, t, tokenAmountIn); LibUnderlying._pullUnderlying(t, msg.sender, tokenAmountIn, bal); } LibPoolToken._mint(msg.sender, _amount); emit PoolJoined(msg.sender, _amount); } function joinswapExternAmountIn( address _token, uint256 _amountIn, uint256 _minPoolAmountOut ) external lockBPoolSwap returns (uint256 poolAmountOut) { IBPool bPool = PBStorage.load().bPool; LibFees.chargeOutstandingAnnualFee(); require(bPool.isBound(_token), "LibPoolEntryExit.joinswapExternAmountIn: Token Not Bound"); poolAmountOut = bPool.calcPoolOutGivenSingleIn( bPool.getBalance(_token), bPool.getDenormalizedWeight(_token), PCStorage.load().totalSupply, bPool.getTotalDenormalizedWeight(), _amountIn, bPool.getSwapFee() ); require( poolAmountOut >= _minPoolAmountOut, "LibPoolEntryExit.joinswapExternAmountIn: Insufficient pool amount out" ); emit LOG_JOIN(msg.sender, _token, _amountIn); LibPoolToken._mint(msg.sender, poolAmountOut); emit PoolJoined(msg.sender, poolAmountOut); uint256 bal = bPool.getBalance(_token); LibUnderlying._pullUnderlying(_token, msg.sender, _amountIn, bal); return poolAmountOut; } function joinswapPoolAmountOut( address _token, uint256 _amountOut, uint256 _maxAmountIn ) external lockBPoolSwap returns (uint256 tokenAmountIn) { IBPool bPool = PBStorage.load().bPool; LibFees.chargeOutstandingAnnualFee(); require(bPool.isBound(_token), "LibPoolEntryExit.joinswapPoolAmountOut: Token Not Bound"); tokenAmountIn = bPool.calcSingleInGivenPoolOut( bPool.getBalance(_token), bPool.getDenormalizedWeight(_token), PCStorage.load().totalSupply, bPool.getTotalDenormalizedWeight(), _amountOut, bPool.getSwapFee() ); require( tokenAmountIn <= _maxAmountIn, "LibPoolEntryExit.joinswapPoolAmountOut: Token amount in too big" ); emit LOG_JOIN(msg.sender, _token, tokenAmountIn); LibPoolToken._mint(msg.sender, _amountOut); emit PoolJoined(msg.sender, _amountOut); uint256 bal = bPool.getBalance(_token); LibUnderlying._pullUnderlying(_token, msg.sender, tokenAmountIn, bal); return tokenAmountIn; } } pragma solidity ^0.6.4; import "../interfaces/IERC20.sol"; import "../interfaces/IBPool.sol"; import {PBasicSmartPoolStorage as PBStorage} from "../storage/PBasicSmartPoolStorage.sol"; import "./Math.sol"; library LibUnderlying { using Math for uint256; function _pullUnderlying( address _token, address _from, uint256 _amount, uint256 _tokenBalance ) internal { IBPool bPool = PBStorage.load().bPool; // Gets current Balance of token i, Bi, and weight of token i, Wi, from BPool. uint256 tokenWeight = bPool.getDenormalizedWeight(_token); require( IERC20(_token).transferFrom(_from, address(this), _amount), "LibUnderlying._pullUnderlying: transferFrom failed" ); bPool.rebind(_token, _tokenBalance.badd(_amount), tokenWeight); } function _pushUnderlying( address _token, address _to, uint256 _amount, uint256 _tokenBalance ) internal { IBPool bPool = PBStorage.load().bPool; // Gets current Balance of token i, Bi, and weight of token i, Wi, from BPool. uint256 tokenWeight = bPool.getDenormalizedWeight(_token); bPool.rebind(_token, _tokenBalance.bsub(_amount), tokenWeight); require( IERC20(_token).transfer(_to, _amount), "LibUnderlying._pushUnderlying: transfer failed" ); } } pragma solidity 0.6.4; import {PBasicSmartPoolStorage as PBStorage} from "../storage/PBasicSmartPoolStorage.sol"; import {PCTokenStorage as PCStorage} from "../storage/PCTokenStorage.sol"; import "./LibFees.sol"; import "./LibPoolToken.sol"; import "./LibUnderlying.sol"; import "./Math.sol"; library LibPoolEntryExitV2 { using Math for uint256; event LOG_EXIT(address indexed caller, address indexed tokenOut, uint256 tokenAmountOut); event LOG_JOIN(address indexed caller, address indexed tokenIn, uint256 tokenAmountIn); event PoolExited(address indexed from, uint256 amount); event PoolExitedWithLoss(address indexed from, uint256 amount, address[] lossTokens); event PoolJoined(address indexed from, uint256 amount, uint16 indexed _referral); modifier lockBPoolSwap() { IBPool bPool = PBStorage.load().bPool; if(bPool.isPublicSwap()) { // If public swap is enabled turn it of, execute function and turn it off again bPool.setPublicSwap(false); _; bPool.setPublicSwap(true); } else { // If public swap is not enabled just execute _; } } function exitPool(uint256 _amount) internal { IBPool bPool = PBStorage.load().bPool; uint256[] memory minAmountsOut = new uint256[](bPool.getCurrentTokens().length); _exitPool(_amount, minAmountsOut); } function exitPool(uint256 _amount, uint256[] calldata _minAmountsOut) external { _exitPool(_amount, _minAmountsOut); } function _exitPool(uint256 _amount, uint256[] memory _minAmountsOut) internal lockBPoolSwap { IBPool bPool = PBStorage.load().bPool; LibFees.chargeOutstandingAnnualFee(); uint256 poolTotal = PCStorage.load().totalSupply; uint256 ratio = _amount.bdiv(poolTotal); require(ratio != 0); LibPoolToken._burn(msg.sender, _amount); address[] memory tokens = bPool.getCurrentTokens(); for (uint256 i = 0; i < tokens.length; i++) { address token = tokens[i]; uint256 balance = bPool.getBalance(token); uint256 tokenAmountOut = ratio.bmul(balance); require( tokenAmountOut >= _minAmountsOut[i], "LibPoolEntryExit.exitPool: Token amount out too small" ); emit LOG_EXIT(msg.sender, token, tokenAmountOut); LibUnderlying._pushUnderlying(token, msg.sender, tokenAmountOut, balance); } emit PoolExited(msg.sender, _amount); } function exitswapPoolAmountIn( address _token, uint256 _poolAmountIn, uint256 _minAmountOut ) external lockBPoolSwap returns (uint256 tokenAmountOut) { IBPool bPool = PBStorage.load().bPool; LibFees.chargeOutstandingAnnualFee(); require(bPool.isBound(_token), "LibPoolEntryExit.exitswapPoolAmountIn: Token Not Bound"); tokenAmountOut = bPool.calcSingleOutGivenPoolIn( bPool.getBalance(_token), bPool.getDenormalizedWeight(_token), PCStorage.load().totalSupply, bPool.getTotalDenormalizedWeight(), _poolAmountIn, bPool.getSwapFee() ); require( tokenAmountOut >= _minAmountOut, "LibPoolEntryExit.exitswapPoolAmountIn: Token Not Bound" ); emit LOG_EXIT(msg.sender, _token, tokenAmountOut); LibPoolToken._burn(msg.sender, _poolAmountIn); emit PoolExited(msg.sender, tokenAmountOut); uint256 bal = bPool.getBalance(_token); LibUnderlying._pushUnderlying(_token, msg.sender, tokenAmountOut, bal); return tokenAmountOut; } function exitswapExternAmountOut( address _token, uint256 _tokenAmountOut, uint256 _maxPoolAmountIn ) external lockBPoolSwap returns (uint256 poolAmountIn) { IBPool bPool = PBStorage.load().bPool; LibFees.chargeOutstandingAnnualFee(); require(bPool.isBound(_token), "LibPoolEntryExit.exitswapExternAmountOut: Token Not Bound"); poolAmountIn = bPool.calcPoolInGivenSingleOut( bPool.getBalance(_token), bPool.getDenormalizedWeight(_token), PCStorage.load().totalSupply, bPool.getTotalDenormalizedWeight(), _tokenAmountOut, bPool.getSwapFee() ); require( poolAmountIn <= _maxPoolAmountIn, "LibPoolEntryExit.exitswapExternAmountOut: pool amount in too large" ); emit LOG_EXIT(msg.sender, _token, _tokenAmountOut); LibPoolToken._burn(msg.sender, poolAmountIn); emit PoolExited(msg.sender, _tokenAmountOut); uint256 bal = bPool.getBalance(_token); LibUnderlying._pushUnderlying(_token, msg.sender, _tokenAmountOut, bal); return poolAmountIn; } function exitPoolTakingloss(uint256 _amount, address[] calldata _lossTokens) external lockBPoolSwap { IBPool bPool = PBStorage.load().bPool; LibFees.chargeOutstandingAnnualFee(); uint256 poolTotal = PCStorage.load().totalSupply; uint256 ratio = _amount.bdiv(poolTotal); require(ratio != 0); LibPoolToken._burn(msg.sender, _amount); address[] memory tokens = bPool.getCurrentTokens(); for (uint256 i = 0; i < tokens.length; i++) { // If taking loss on token skip one iteration of the loop if (_contains(tokens[i], _lossTokens)) { continue; } address t = tokens[i]; uint256 bal = bPool.getBalance(t); uint256 tAo = ratio.bmul(bal); emit LOG_EXIT(msg.sender, t, tAo); LibUnderlying._pushUnderlying(t, msg.sender, tAo, bal); } emit PoolExitedWithLoss(msg.sender, _amount, _lossTokens); } /** @notice Searches for an address in an array of addresses and returns if found @param _needle Address to look for @param _haystack Array to search @return If value is found */ function _contains(address _needle, address[] memory _haystack) internal pure returns (bool) { for (uint256 i = 0; i < _haystack.length; i++) { if (_haystack[i] == _needle) { return true; } } return false; } function joinPoolExpress(uint256 _amount, uint16 _referral) external { IBPool bPool = PBStorage.load().bPool; uint256[] memory maxAmountsIn = new uint256[](bPool.getCurrentTokens().length); for (uint256 i = 0; i < maxAmountsIn.length; i++) { maxAmountsIn[i] = uint256(-1); } _joinPool(_amount, maxAmountsIn, _referral); } function joinPool(uint256 _amount, uint256[] calldata _maxAmountsIn, uint16 _referral) external { _joinPool(_amount, _maxAmountsIn, _referral); } function _joinPool(uint256 _amount, uint256[] memory _maxAmountsIn, uint16 _referral) internal lockBPoolSwap { IBPool bPool = PBStorage.load().bPool; LibFees.chargeOutstandingAnnualFee(); uint256 poolTotal = PCStorage.load().totalSupply; uint256 ratio = _amount.bdiv(poolTotal); require(ratio != 0); address[] memory tokens = bPool.getCurrentTokens(); for (uint256 i = 0; i < tokens.length; i++) { address t = tokens[i]; uint256 bal = bPool.getBalance(t); uint256 tokenAmountIn = ratio.bmul(bal); require( tokenAmountIn <= _maxAmountsIn[i], "LibPoolEntryExit.joinPool: Token in amount too big" ); emit LOG_JOIN(msg.sender, t, tokenAmountIn); LibUnderlying._pullUnderlying(t, msg.sender, tokenAmountIn, bal); } LibPoolToken._mint(msg.sender, _amount); emit PoolJoined(msg.sender, _amount, _referral); } function joinswapExternAmountIn( address _token, uint256 _amountIn, uint256 _minPoolAmountOut, uint16 _referral ) external lockBPoolSwap returns (uint256 poolAmountOut) { IBPool bPool = PBStorage.load().bPool; LibFees.chargeOutstandingAnnualFee(); require(bPool.isBound(_token), "LibPoolEntryExit.joinswapExternAmountIn: Token Not Bound"); poolAmountOut = bPool.calcPoolOutGivenSingleIn( bPool.getBalance(_token), bPool.getDenormalizedWeight(_token), PCStorage.load().totalSupply, bPool.getTotalDenormalizedWeight(), _amountIn, bPool.getSwapFee() ); require( poolAmountOut >= _minPoolAmountOut, "LibPoolEntryExit.joinswapExternAmountIn: Insufficient pool amount out" ); emit LOG_JOIN(msg.sender, _token, _amountIn); LibPoolToken._mint(msg.sender, poolAmountOut); emit PoolJoined(msg.sender, poolAmountOut, _referral); uint256 bal = bPool.getBalance(_token); LibUnderlying._pullUnderlying(_token, msg.sender, _amountIn, bal); return poolAmountOut; } function joinswapPoolAmountOut( address _token, uint256 _amountOut, uint256 _maxAmountIn, uint16 _referral ) external lockBPoolSwap returns (uint256 tokenAmountIn) { IBPool bPool = PBStorage.load().bPool; LibFees.chargeOutstandingAnnualFee(); require(bPool.isBound(_token), "LibPoolEntryExit.joinswapPoolAmountOut: Token Not Bound"); tokenAmountIn = bPool.calcSingleInGivenPoolOut( bPool.getBalance(_token), bPool.getDenormalizedWeight(_token), PCStorage.load().totalSupply, bPool.getTotalDenormalizedWeight(), _amountOut, bPool.getSwapFee() ); require( tokenAmountIn <= _maxAmountIn, "LibPoolEntryExit.joinswapPoolAmountOut: Token amount in too big" ); emit LOG_JOIN(msg.sender, _token, tokenAmountIn); LibPoolToken._mint(msg.sender, _amountOut); emit PoolJoined(msg.sender, _amountOut, _referral); uint256 bal = bPool.getBalance(_token); LibUnderlying._pullUnderlying(_token, msg.sender, tokenAmountIn, bal); return tokenAmountIn; } } // modified version of // https://github.com/balancer-labs/balancer-core/blob/master/contracts/BMath.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity 0.6.4; import "./Math.sol"; import "./LibFees.sol"; import {PBasicSmartPoolStorage as PBStorage} from "../storage/PBasicSmartPoolStorage.sol"; import {PCTokenStorage as PCStorage} from "../storage/PCTokenStorage.sol"; library LibPoolMath { using Math for uint256; uint256 constant BONE = 1 * 10**18; uint256 constant EXIT_FEE = 0; /********************************************************************************************** // calcSpotPrice // // sP = spotPrice // // bI = tokenBalanceIn ( bI / wI ) 1 // // bO = tokenBalanceOut sP = ----------- * ---------- // // wI = tokenWeightIn ( bO / wO ) ( 1 - sF ) // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/ function calcSpotPrice( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 swapFee ) internal pure returns (uint256 spotPrice) { uint256 numer = tokenBalanceIn.bdiv(tokenWeightIn); uint256 denom = tokenBalanceOut.bdiv(tokenWeightOut); uint256 ratio = numer.bdiv(denom); uint256 scale = BONE.bdiv(BONE.bsub(swapFee)); return (spotPrice = ratio.bmul(scale)); } /********************************************************************************************** // calcOutGivenIn // // aO = tokenAmountOut // // bO = tokenBalanceOut // // bI = tokenBalanceIn / / bI \ (wI / wO) \ // // aI = tokenAmountIn aO = bO * | 1 - | -------------------------- | ^ | // // wI = tokenWeightIn \ \ ( bI + ( aI * ( 1 - sF )) / / // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/ function calcOutGivenIn( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 tokenAmountIn, uint256 swapFee ) internal pure returns (uint256 tokenAmountOut) { uint256 weightRatio = tokenWeightIn.bdiv(tokenWeightOut); uint256 adjustedIn = BONE.bsub(swapFee); adjustedIn = tokenAmountIn.bmul(adjustedIn); uint256 y = tokenBalanceIn.bdiv(tokenBalanceIn.badd(adjustedIn)); uint256 foo = y.bpow(weightRatio); uint256 bar = BONE.bsub(foo); tokenAmountOut = tokenBalanceOut.bmul(bar); return tokenAmountOut; } /********************************************************************************************** // calcInGivenOut // // aI = tokenAmountIn // // bO = tokenBalanceOut / / bO \ (wO / wI) \ // // bI = tokenBalanceIn bI * | | ------------ | ^ - 1 | // // aO = tokenAmountOut aI = \ \ ( bO - aO ) / / // // wI = tokenWeightIn -------------------------------------------- // // wO = tokenWeightOut ( 1 - sF ) // // sF = swapFee // **********************************************************************************************/ function calcInGivenOut( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 tokenAmountOut, uint256 swapFee ) internal pure returns (uint256 tokenAmountIn) { uint256 weightRatio = tokenWeightOut.bdiv(tokenWeightIn); uint256 diff = tokenBalanceOut.bsub(tokenAmountOut); uint256 y = tokenBalanceOut.bdiv(diff); uint256 foo = y.bpow(weightRatio); foo = foo.bsub(BONE); tokenAmountIn = BONE.bsub(swapFee); tokenAmountIn = tokenBalanceIn.bmul(foo).bdiv(tokenAmountIn); return tokenAmountIn; } /********************************************************************************************** // calcPoolOutGivenSingleIn // // pAo = poolAmountOut / \ // // tAi = tokenAmountIn /// / // wI \ \\ \ wI \ // // wI = tokenWeightIn //| tAi *| 1 - || 1 - -- | * sF || + tBi \ -- \ // // tW = totalWeight pAo=|| \ \ \\ tW / // | ^ tW | * pS - pS // // tBi = tokenBalanceIn \\ ------------------------------------- / / // // pS = poolSupply \\ tBi / / // // sF = swapFee \ / // **********************************************************************************************/ function calcPoolOutGivenSingleIn( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 poolSupply, uint256 totalWeight, uint256 tokenAmountIn, uint256 swapFee ) internal pure returns (uint256 poolAmountOut) { // Charge the trading fee for the proportion of tokenAi /// which is implicitly traded to the other pool tokens. // That proportion is (1- weightTokenIn) // tokenAiAfterFee = tAi * (1 - (1-weightTi) * poolFee); uint256 normalizedWeight = tokenWeightIn.bdiv(totalWeight); uint256 zaz = BONE.bsub(normalizedWeight).bmul(swapFee); uint256 tokenAmountInAfterFee = tokenAmountIn.bmul(BONE.bsub(zaz)); uint256 newTokenBalanceIn = tokenBalanceIn.badd(tokenAmountInAfterFee); uint256 tokenInRatio = newTokenBalanceIn.bdiv(tokenBalanceIn); uint256 poolRatio = tokenInRatio.bpow(normalizedWeight); uint256 newPoolSupply = poolRatio.bmul(poolSupply); poolAmountOut = newPoolSupply.bsub(poolSupply); return poolAmountOut; } /********************************************************************************************** // calcSingleInGivenPoolOut // // tAi = tokenAmountIn //(pS + pAo)\ / 1 \\ // // pS = poolSupply || --------- | ^ | --------- || * bI - bI // // pAo = poolAmountOut \\ pS / \(wI / tW)// // // bI = balanceIn tAi = -------------------------------------------- // // wI = weightIn / wI \ // // tW = totalWeight 1 - | 1 - ---- | * sF // // sF = swapFee \ tW / // **********************************************************************************************/ function calcSingleInGivenPoolOut( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 poolSupply, uint256 totalWeight, uint256 poolAmountOut, uint256 swapFee ) internal pure returns (uint256 tokenAmountIn) { uint256 normalizedWeight = tokenWeightIn.bdiv(totalWeight); uint256 newPoolSupply = poolSupply.badd(poolAmountOut); uint256 poolRatio = newPoolSupply.bdiv(poolSupply); //uint256 newBalTi = poolRatio^(1/weightTi) * balTi; uint256 boo = BONE.bdiv(normalizedWeight); uint256 tokenInRatio = poolRatio.bpow(boo); uint256 newTokenBalanceIn = tokenInRatio.bmul(tokenBalanceIn); uint256 tokenAmountInAfterFee = newTokenBalanceIn.bsub(tokenBalanceIn); // Do reverse order of fees charged in joinswap_ExternAmountIn, this way // ``` pAo == joinswap_ExternAmountIn(Ti, joinswap_PoolAmountOut(pAo, Ti)) ``` //uint256 tAi = tAiAfterFee / (1 - (1-weightTi) * swapFee) ; uint256 zar = BONE.bsub(normalizedWeight).bmul(swapFee); tokenAmountIn = tokenAmountInAfterFee.bdiv(BONE.bsub(zar)); return tokenAmountIn; } /********************************************************************************************** // calcSingleOutGivenPoolIn // // tAo = tokenAmountOut / / \\ // // bO = tokenBalanceOut / // pS - (pAi * (1 - eF)) \ / 1 \ \\ // // pAi = poolAmountIn | bO - || ----------------------- | ^ | --------- | * b0 || // // ps = poolSupply \ \\ pS / \(wO / tW)/ // // // wI = tokenWeightIn tAo = \ \ // // // tW = totalWeight / / wO \ \ // // sF = swapFee * | 1 - | 1 - ---- | * sF | // // eF = exitFee \ \ tW / / // **********************************************************************************************/ function calcSingleOutGivenPoolIn( uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 poolSupply, uint256 totalWeight, uint256 poolAmountIn, uint256 swapFee ) internal pure returns (uint256 tokenAmountOut) { uint256 normalizedWeight = tokenWeightOut.bdiv(totalWeight); // charge exit fee on the pool token side // pAiAfterExitFee = pAi*(1-exitFee) uint256 poolAmountInAfterExitFee = poolAmountIn.bmul(BONE.bsub(EXIT_FEE)); uint256 newPoolSupply = poolSupply.bsub(poolAmountInAfterExitFee); uint256 poolRatio = newPoolSupply.bdiv(poolSupply); // newBalTo = poolRatio^(1/weightTo) * balTo; uint256 tokenOutRatio = poolRatio.bpow(BONE.bdiv(normalizedWeight)); uint256 newTokenBalanceOut = tokenOutRatio.bmul(tokenBalanceOut); uint256 tokenAmountOutBeforeSwapFee = tokenBalanceOut.bsub(newTokenBalanceOut); // charge swap fee on the output token side //uint256 tAo = tAoBeforeSwapFee * (1 - (1-weightTo) * swapFee) uint256 zaz = BONE.bsub(normalizedWeight).bmul(swapFee); tokenAmountOut = tokenAmountOutBeforeSwapFee.bmul(BONE.bsub(zaz)); return tokenAmountOut; } /********************************************************************************************** // calcPoolInGivenSingleOut // // pAi = poolAmountIn // / tAo \\ / wO \ \ // // bO = tokenBalanceOut // | bO - -------------------------- |\ | ---- | \ // // tAo = tokenAmountOut pS - || \ 1 - ((1 - (tO / tW)) * sF)/ | ^ \ tW / * pS | // // ps = poolSupply \\ -----------------------------------/ / // // wO = tokenWeightOut pAi = \\ bO / / // // tW = totalWeight ------------------------------------------------------------- // // sF = swapFee ( 1 - eF ) // // eF = exitFee // **********************************************************************************************/ function calcPoolInGivenSingleOut( uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 poolSupply, uint256 totalWeight, uint256 tokenAmountOut, uint256 swapFee ) internal pure returns (uint256 poolAmountIn) { // charge swap fee on the output token side uint256 normalizedWeight = tokenWeightOut.bdiv(totalWeight); //uint256 tAoBeforeSwapFee = tAo / (1 - (1-weightTo) * swapFee) ; uint256 zoo = BONE.bsub(normalizedWeight); uint256 zar = zoo.bmul(swapFee); uint256 tokenAmountOutBeforeSwapFee = tokenAmountOut.bdiv(BONE.bsub(zar)); uint256 newTokenBalanceOut = tokenBalanceOut.bsub(tokenAmountOutBeforeSwapFee); uint256 tokenOutRatio = newTokenBalanceOut.bdiv(tokenBalanceOut); //uint256 newPoolSupply = (ratioTo ^ weightTo) * poolSupply; uint256 poolRatio = tokenOutRatio.bpow(normalizedWeight); uint256 newPoolSupply = poolRatio.bmul(poolSupply); uint256 poolAmountInAfterExitFee = poolSupply.bsub(newPoolSupply); // charge exit fee on the pool token side // pAi = pAiAfterExitFee/(1-exitFee) poolAmountIn = poolAmountInAfterExitFee.bdiv(BONE.bsub(EXIT_FEE)); return poolAmountIn; } // Wrapped public functions -------------------------------------------------------------------- /** @notice Gets the underlying assets and amounts to mint specific pool shares. @param _amount Amount of pool shares to calculate the values for @return tokens The addresses of the tokens @return amounts The amounts of tokens needed to mint that amount of pool shares */ function calcTokensForAmount(uint256 _amount) external view returns (address[] memory tokens, uint256[] memory amounts) { tokens = PBStorage.load().bPool.getCurrentTokens(); amounts = new uint256[](tokens.length); uint256 ratio = _amount.bdiv( PCStorage.load().totalSupply.badd(LibFees.calcOutstandingAnnualFee()) ); for (uint256 i = 0; i < tokens.length; i++) { address t = tokens[i]; uint256 bal = PBStorage.load().bPool.getBalance(t); uint256 amount = ratio.bmul(bal); amounts[i] = amount; } } /** @notice Calculate the amount of pool tokens out for a given amount in @param _token Address of the input token @param _amount Amount of input token @return Amount of pool token */ function calcPoolOutGivenSingleIn(address _token, uint256 _amount) external view returns (uint256) { PBStorage.StorageStruct storage s = PBStorage.load(); uint256 tokenBalanceIn = s.bPool.getBalance(_token); uint256 tokenWeightIn = s.bPool.getDenormalizedWeight(_token); uint256 poolSupply = PCStorage.load().totalSupply.badd(LibFees.calcOutstandingAnnualFee()); uint256 totalWeight = s.bPool.getTotalDenormalizedWeight(); uint256 swapFee = s.bPool.getSwapFee(); return ( LibPoolMath.calcPoolOutGivenSingleIn( tokenBalanceIn, tokenWeightIn, poolSupply, totalWeight, _amount, swapFee ) ); } /** @notice Calculate single in given pool out @param _token Address of the input token @param _amount Amount of pool out token @return Amount of token in */ function calcSingleInGivenPoolOut(address _token, uint256 _amount) external view returns (uint256) { PBStorage.StorageStruct storage s = PBStorage.load(); uint256 tokenBalanceIn = s.bPool.getBalance(_token); uint256 tokenWeightIn = s.bPool.getDenormalizedWeight(_token); uint256 poolSupply = PCStorage.load().totalSupply.badd(LibFees.calcOutstandingAnnualFee()); uint256 totalWeight = s.bPool.getTotalDenormalizedWeight(); uint256 swapFee = s.bPool.getSwapFee(); return ( LibPoolMath.calcSingleInGivenPoolOut( tokenBalanceIn, tokenWeightIn, poolSupply, totalWeight, _amount, swapFee ) ); } /** @notice Calculate single out given pool in @param _token Address of output token @param _amount Amount of pool in @return Amount of token in */ function calcSingleOutGivenPoolIn(address _token, uint256 _amount) external view returns (uint256) { PBStorage.StorageStruct storage s = PBStorage.load(); uint256 tokenBalanceOut = s.bPool.getBalance(_token); uint256 tokenWeightOut = s.bPool.getDenormalizedWeight(_token); uint256 poolSupply = PCStorage.load().totalSupply.badd(LibFees.calcOutstandingAnnualFee()); uint256 totalWeight = s.bPool.getTotalDenormalizedWeight(); uint256 swapFee = s.bPool.getSwapFee(); return ( LibPoolMath.calcSingleOutGivenPoolIn( tokenBalanceOut, tokenWeightOut, poolSupply, totalWeight, _amount, swapFee ) ); } /** @notice Calculate pool in given single token out @param _token Address of output token @param _amount Amount of output token @return Amount of pool in */ function calcPoolInGivenSingleOut(address _token, uint256 _amount) external view returns (uint256) { PBStorage.StorageStruct storage s = PBStorage.load(); uint256 tokenBalanceOut = s.bPool.getBalance(_token); uint256 tokenWeightOut = s.bPool.getDenormalizedWeight(_token); uint256 poolSupply = PCStorage.load().totalSupply.badd(LibFees.calcOutstandingAnnualFee()); uint256 totalWeight = s.bPool.getTotalDenormalizedWeight(); uint256 swapFee = s.bPool.getSwapFee(); return ( LibPoolMath.calcPoolInGivenSingleOut( tokenBalanceOut, tokenWeightOut, poolSupply, totalWeight, _amount, swapFee ) ); } } pragma solidity ^0.6.4; import {PBasicSmartPoolStorage as PBStorage} from "../storage/PBasicSmartPoolStorage.sol"; import {PV2SmartPoolStorage as P2Storage} from "../storage/PV2SmartPoolStorage.sol"; import {PCTokenStorage as PCStorage} from "../storage/PCTokenStorage.sol"; import {LibConst as constants} from "./LibConst.sol"; import "./LibPoolToken.sol"; import "./Math.sol"; library LibWeights { using Math for uint256; function updateWeight(address _token, uint256 _newWeight) external { PBStorage.StorageStruct storage s = PBStorage.load(); P2Storage.StorageStruct storage ws = P2Storage.load(); require(_newWeight >= constants.MIN_WEIGHT, "ERR_MIN_WEIGHT"); require(_newWeight <= constants.MAX_WEIGHT, "ERR_MAX_WEIGHT"); uint256 currentWeight = s.bPool.getDenormalizedWeight(_token); uint256 currentBalance = s.bPool.getBalance(_token); uint256 poolShares; uint256 deltaBalance; uint256 deltaWeight; uint256 totalSupply = PCStorage.load().totalSupply; uint256 totalWeight = s.bPool.getTotalDenormalizedWeight(); if (_newWeight < currentWeight) { // If weight goes down we need to pull tokens and burn pool shares require( totalWeight.badd(currentWeight.bsub(_newWeight)) <= constants.MAX_TOTAL_WEIGHT, "ERR_MAX_TOTAL_WEIGHT" ); deltaWeight = currentWeight.bsub(_newWeight); poolShares = totalSupply.bmul(deltaWeight.bdiv(totalWeight)); deltaBalance = currentBalance.bmul(deltaWeight.bdiv(currentWeight)); // New balance cannot be lower than MIN_BALANCE require(currentBalance.bsub(deltaBalance) >= constants.MIN_BALANCE, "ERR_MIN_BALANCE"); // First gets the tokens from this contract (Pool Controller) to msg.sender s.bPool.rebind(_token, currentBalance.bsub(deltaBalance), _newWeight); // Now with the tokens this contract can send them to msg.sender require(IERC20(_token).transfer(msg.sender, deltaBalance), "ERR_ERC20_FALSE"); // Cancel potential weight adjustment process. ws.startBlock = 0; LibPoolToken._burn(msg.sender, poolShares); } else { // This means the controller will deposit tokens to keep the price. // They will be minted and given PCTokens require( totalWeight.badd(_newWeight.bsub(currentWeight)) <= constants.MAX_TOTAL_WEIGHT, "ERR_MAX_TOTAL_WEIGHT" ); deltaWeight = _newWeight.bsub(currentWeight); poolShares = totalSupply.bmul(deltaWeight.bdiv(totalWeight)); deltaBalance = currentBalance.bmul(deltaWeight.bdiv(currentWeight)); // First gets the tokens from msg.sender to this contract (Pool Controller) require( IERC20(_token).transferFrom(msg.sender, address(this), deltaBalance), "TRANSFER_FAILED" ); // Now with the tokens this contract can bind them to the pool it controls s.bPool.rebind(_token, currentBalance.badd(deltaBalance), _newWeight); // Cancel potential weight adjustment process. ws.startBlock = 0; LibPoolToken._mint(msg.sender, poolShares); } } function updateWeightsGradually( uint256[] calldata _newWeights, uint256 _startBlock, uint256 _endBlock ) external { PBStorage.StorageStruct storage s = PBStorage.load(); P2Storage.StorageStruct storage ws = P2Storage.load(); uint256 weightsSum = 0; address[] memory tokens = s.bPool.getCurrentTokens(); // Check that endWeights are valid now to avoid reverting in a future pokeWeights call for (uint256 i = 0; i < tokens.length; i++) { require(_newWeights[i] <= constants.MAX_WEIGHT, "ERR_WEIGHT_ABOVE_MAX"); require(_newWeights[i] >= constants.MIN_WEIGHT, "ERR_WEIGHT_BELOW_MIN"); weightsSum = weightsSum.badd(_newWeights[i]); } require(weightsSum <= constants.MAX_TOTAL_WEIGHT, "ERR_MAX_TOTAL_WEIGHT"); if (block.number > _startBlock) { // This means the weight update should start ASAP ws.startBlock = block.number; } else { ws.startBlock = _startBlock; } ws.endBlock = _endBlock; ws.newWeights = _newWeights; require( _endBlock > _startBlock, "PWeightControlledSmartPool.updateWeightsGradually: End block must be after start block" ); delete ws.startWeights; for (uint256 i = 0; i < tokens.length; i++) { // startWeights are current weights ws.startWeights.push(s.bPool.getDenormalizedWeight(tokens[i])); } } function pokeWeights() external { PBStorage.StorageStruct storage s = PBStorage.load(); P2Storage.StorageStruct storage ws = P2Storage.load(); require(ws.startBlock != 0, "ERR_WEIGHT_ADJUSTMENT_FINISHED"); require(block.number >= ws.startBlock, "ERR_CANT_POKE_YET"); // This allows for pokes after endBlock that get weights to endWeights uint256 minBetweenEndBlockAndThisBlock; if (block.number > ws.endBlock) { minBetweenEndBlockAndThisBlock = ws.endBlock; } else { minBetweenEndBlockAndThisBlock = block.number; } uint256 blockPeriod = ws.endBlock.bsub(ws.startBlock); uint256 weightDelta; uint256 newWeight; address[] memory tokens = s.bPool.getCurrentTokens(); for (uint256 i = 0; i < tokens.length; i++) { if (ws.startWeights[i] >= ws.newWeights[i]) { weightDelta = ws.startWeights[i].bsub(ws.newWeights[i]); newWeight = ws.startWeights[i].bsub( (minBetweenEndBlockAndThisBlock.bsub(ws.startBlock)).bmul(weightDelta.bdiv(blockPeriod)) ); } else { weightDelta = ws.newWeights[i].bsub(ws.startWeights[i]); newWeight = ws.startWeights[i].badd( (minBetweenEndBlockAndThisBlock.bsub(ws.startBlock)).bmul(weightDelta.bdiv(blockPeriod)) ); } s.bPool.rebind(tokens[i], s.bPool.getBalance(tokens[i]), newWeight); } if(minBetweenEndBlockAndThisBlock == ws.endBlock) { // All the weights are adjusted, adjustment finished. // save gas option: set this to max number instead of 0 // And be able to remove ERR_WEIGHT_ADJUSTMENT_FINISHED check ws.startBlock = 0; } } } // 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.6.4; import {PCTokenStorage as PCStorage} from "./storage/PCTokenStorage.sol"; import "./libraries/LibPoolToken.sol"; import "./libraries/Math.sol"; import "./interfaces/IERC20.sol"; // Highly opinionated token implementation // Based on the balancer Implementation contract PCToken is IERC20 { using Math for uint256; event Approval(address indexed _src, address indexed _dst, uint256 _amount); event Transfer(address indexed _src, address indexed _dst, uint256 _amount); uint8 public constant decimals = 18; function _mint(uint256 _amount) internal { LibPoolToken._mint(address(this), _amount); } function _burn(uint256 _amount) internal { LibPoolToken._burn(address(this), _amount); } function _move( address _src, address _dst, uint256 _amount ) internal { PCStorage.StorageStruct storage s = PCStorage.load(); require(s.balance[_src] >= _amount, "ERR_INSUFFICIENT_BAL"); s.balance[_src] = s.balance[_src].bsub(_amount); s.balance[_dst] = s.balance[_dst].badd(_amount); emit Transfer(_src, _dst, _amount); } function _push(address _to, uint256 _amount) internal { _move(address(this), _to, _amount); } function _pull(address _from, uint256 _amount) internal { _move(_from, address(this), _amount); } function allowance(address _src, address _dst) external override view returns (uint256) { return PCStorage.load().allowance[_src][_dst]; } function balanceOf(address _whom) external override view returns (uint256) { return PCStorage.load().balance[_whom]; } function totalSupply() public override view returns (uint256) { return PCStorage.load().totalSupply; } function name() external view returns (string memory) { return PCStorage.load().name; } function symbol() external view returns (string memory) { return PCStorage.load().symbol; } function approve(address _dst, uint256 _amount) external override returns (bool) { PCStorage.load().allowance[msg.sender][_dst] = _amount; emit Approval(msg.sender, _dst, _amount); return true; } function increaseApproval(address _dst, uint256 _amount) external returns (bool) { PCStorage.StorageStruct storage s = PCStorage.load(); s.allowance[msg.sender][_dst] = s.allowance[msg.sender][_dst].badd(_amount); emit Approval(msg.sender, _dst, s.allowance[msg.sender][_dst]); return true; } function decreaseApproval(address _dst, uint256 _amount) external returns (bool) { PCStorage.StorageStruct storage s = PCStorage.load(); uint256 oldValue = s.allowance[msg.sender][_dst]; if (_amount > oldValue) { s.allowance[msg.sender][_dst] = 0; } else { s.allowance[msg.sender][_dst] = oldValue.bsub(_amount); } emit Approval(msg.sender, _dst, s.allowance[msg.sender][_dst]); return true; } function transfer(address _dst, uint256 _amount) external override returns (bool) { _move(msg.sender, _dst, _amount); return true; } function transferFrom( address _src, address _dst, uint256 _amount ) external override returns (bool) { PCStorage.StorageStruct storage s = PCStorage.load(); require( msg.sender == _src || _amount <= s.allowance[_src][msg.sender], "ERR_PCTOKEN_BAD_CALLER" ); _move(_src, _dst, _amount); if (msg.sender != _src && s.allowance[_src][msg.sender] != uint256(-1)) { s.allowance[_src][msg.sender] = s.allowance[_src][msg.sender].bsub(_amount); emit Approval(msg.sender, _dst, s.allowance[_src][msg.sender]); } return true; } } pragma solidity 0.6.4; import {ReentryProtectionStorage as RPStorage} from "./storage/ReentryProtectionStorage.sol"; contract ReentryProtection { modifier noReentry { // Use counter to only write to storage once RPStorage.StorageStruct storage s = RPStorage.load(); s.lockCounter++; uint256 lockValue = s.lockCounter; _; require(lockValue == s.lockCounter, "ReentryProtection.noReentry: reentry detected"); } } pragma solidity 0.6.4; library ReentryProtectionStorage { bytes32 public constant rpSlot = keccak256("ReentryProtection.storage.location"); struct StorageStruct { uint256 lockCounter; } /** @notice Load pool token storage @return s Storage pointer to the pool token struct */ function load() internal pure returns (StorageStruct storage s) { bytes32 loc = rpSlot; assembly { s_slot := loc } } } pragma experimental ABIEncoderV2; pragma solidity 0.6.4; import "../interfaces/IPV2SmartPool.sol"; import "../interfaces/IBPool.sol"; import "../PCToken.sol"; import "../ReentryProtection.sol"; import "../libraries/LibPoolToken.sol"; import "../libraries/LibAddRemoveToken.sol"; import "../libraries/LibPoolEntryExit.sol"; import "../libraries/LibPoolMath.sol"; import "../libraries/LibWeights.sol"; import "../libraries/LibSafeApprove.sol"; import {PBasicSmartPoolStorage as PBStorage} from "../storage/PBasicSmartPoolStorage.sol"; import {PCTokenStorage as PCStorage} from "../storage/PCTokenStorage.sol"; import {PCappedSmartPoolStorage as PCSStorage} from "../storage/PCappedSmartPoolStorage.sol"; import {PV2SmartPoolStorage as P2Storage} from "../storage/PV2SmartPoolStorage.sol"; contract PV2SmartPool is IPV2SmartPool, PCToken, ReentryProtection { using LibSafeApprove for IERC20; event TokensApproved(); event ControllerChanged(address indexed previousController, address indexed newController); event PublicSwapSetterChanged(address indexed previousSetter, address indexed newSetter); event TokenBinderChanged(address indexed previousTokenBinder, address indexed newTokenBinder); event PublicSwapSet(address indexed setter, bool indexed value); event SwapFeeSet(address indexed setter, uint256 newFee); event CapChanged(address indexed setter, uint256 oldCap, uint256 newCap); event CircuitBreakerTripped(); event JoinExitEnabledChanged(address indexed setter, bool oldValue, bool newValue); event CircuitBreakerChanged( address indexed _oldCircuitBreaker, address indexed _newCircuitBreaker ); modifier ready() { require(address(PBStorage.load().bPool) != address(0), "PV2SmartPool.ready: not ready"); _; } modifier onlyController() { require( msg.sender == PBStorage.load().controller, "PV2SmartPool.onlyController: not controller" ); _; } modifier onlyPublicSwapSetter() { require( msg.sender == PBStorage.load().publicSwapSetter, "PV2SmartPool.onlyPublicSwapSetter: not public swap setter" ); _; } modifier onlyTokenBinder() { require( msg.sender == PBStorage.load().tokenBinder, "PV2SmartPool.onlyTokenBinder: not token binder" ); _; } modifier onlyPublicSwap() { require( PBStorage.load().bPool.isPublicSwap(), "PV2SmartPool.onlyPublicSwap: swapping not enabled" ); _; } modifier onlyCircuitBreaker() { require( msg.sender == P2Storage.load().circuitBreaker, "PV2SmartPool.onlyCircuitBreaker: not circuit breaker" ); _; } modifier onlyJoinExitEnabled() { require( P2Storage.load().joinExitEnabled, "PV2SmartPool.onlyJoinExitEnabled: join and exit not enabled" ); _; } modifier withinCap() { _; require(totalSupply() < PCSStorage.load().cap, "PV2SmartPool.withinCap: Cap limit reached"); } /** @notice Initialises the contract @param _bPool Address of the underlying balancer pool @param _name Name for the smart pool token @param _symbol Symbol for the smart pool token @param _initialSupply Initial token supply to mint */ function init( address _bPool, string calldata _name, string calldata _symbol, uint256 _initialSupply ) external override { PBStorage.StorageStruct storage s = PBStorage.load(); require(address(s.bPool) == address(0), "PV2SmartPool.init: already initialised"); require(_bPool != address(0), "PV2SmartPool.init: _bPool cannot be 0x00....000"); require(_initialSupply != 0, "PV2SmartPool.init: _initialSupply can not zero"); s.bPool = IBPool(_bPool); s.controller = msg.sender; s.publicSwapSetter = msg.sender; s.tokenBinder = msg.sender; PCStorage.load().name = _name; PCStorage.load().symbol = _symbol; LibPoolToken._mint(msg.sender, _initialSupply); } /** @notice Sets approval to all tokens to the underlying balancer pool @dev It uses this function to save on gas in joinPool */ function approveTokens() public override noReentry { IBPool bPool = PBStorage.load().bPool; address[] memory tokens = bPool.getCurrentTokens(); for (uint256 i = 0; i < tokens.length; i++) { IERC20(tokens[i]).safeApprove(address(bPool), uint256(-1)); } emit TokensApproved(); } // POOL EXIT ------------------------------------------------ /** @notice Burns pool shares and sends back the underlying assets leaving some in the pool @param _amount Amount of pool tokens to burn @param _lossTokens Tokens skipped on redemption */ function exitPoolTakingloss(uint256 _amount, address[] calldata _lossTokens) external override ready noReentry onlyJoinExitEnabled { LibPoolEntryExit.exitPoolTakingloss(_amount, _lossTokens); } /** @notice Burns pool shares and sends back the underlying assets @param _amount Amount of pool tokens to burn */ function exitPool(uint256 _amount) external override ready noReentry onlyJoinExitEnabled { LibPoolEntryExit.exitPool(_amount); } /** @notice Burn pool tokens and redeem underlying assets. With front running protection @param _amount Amount of pool tokens to burn @param _minAmountsOut Minimum amounts of underlying assets */ function exitPool(uint256 _amount, uint256[] calldata _minAmountsOut) external override ready noReentry onlyJoinExitEnabled { LibPoolEntryExit.exitPool(_amount, _minAmountsOut); } /** @notice Exitswap single asset pool exit given pool amount in @param _token Address of exit token @param _poolAmountIn Amount of pool tokens sending to the pool @return tokenAmountOut amount of exit tokens being withdrawn */ function exitswapPoolAmountIn( address _token, uint256 _poolAmountIn, uint256 _minAmountOut ) external override ready noReentry onlyPublicSwap onlyJoinExitEnabled returns (uint256 tokenAmountOut) { return LibPoolEntryExit.exitswapPoolAmountIn(_token, _poolAmountIn, _minAmountOut); } /** @notice Exitswap single asset pool entry given token amount out @param _token Address of exit token @param _tokenAmountOut Amount of exit tokens @return poolAmountIn amount of pool tokens being deposited */ function exitswapExternAmountOut( address _token, uint256 _tokenAmountOut, uint256 _maxPoolAmountIn ) external override ready noReentry onlyPublicSwap onlyJoinExitEnabled returns (uint256 poolAmountIn) { return LibPoolEntryExit.exitswapExternAmountOut(_token, _tokenAmountOut, _maxPoolAmountIn); } // POOL ENTRY ----------------------------------------------- /** @notice Takes underlying assets and mints smart pool tokens. Enforces the cap @param _amount Amount of pool tokens to mint */ function joinPool(uint256 _amount) external override withinCap ready noReentry onlyJoinExitEnabled { LibPoolEntryExit.joinPool(_amount); } /** @notice Takes underlying assets and mints smart pool tokens. Enforces the cap. Allows you to specify the maximum amounts of underlying assets @param _amount Amount of pool tokens to mint */ function joinPool(uint256 _amount, uint256[] calldata _maxAmountsIn) external override withinCap ready noReentry onlyJoinExitEnabled { LibPoolEntryExit.joinPool(_amount, _maxAmountsIn); } /** @notice Joinswap single asset pool entry given token amount in @param _token Address of entry token @param _amountIn Amount of entry tokens @return poolAmountOut */ function joinswapExternAmountIn( address _token, uint256 _amountIn, uint256 _minPoolAmountOut ) external override ready withinCap onlyPublicSwap noReentry onlyJoinExitEnabled returns (uint256 poolAmountOut) { return LibPoolEntryExit.joinswapExternAmountIn(_token, _amountIn, _minPoolAmountOut); } /** @notice Joinswap single asset pool entry given pool amount out @param _token Address of entry token @param _amountOut Amount of entry tokens to deposit into the pool @return tokenAmountIn */ function joinswapPoolAmountOut( address _token, uint256 _amountOut, uint256 _maxAmountIn ) external override ready withinCap onlyPublicSwap noReentry onlyJoinExitEnabled returns (uint256 tokenAmountIn) { return LibPoolEntryExit.joinswapPoolAmountOut(_token, _amountOut, _maxAmountIn); } // ADMIN FUNCTIONS ------------------------------------------ /** @notice Bind a token to the underlying balancer pool. Can only be called by the token binder @param _token Token to bind @param _balance Amount to bind @param _denorm Denormalised weight */ function bind( address _token, uint256 _balance, uint256 _denorm ) external override onlyTokenBinder noReentry { P2Storage.StorageStruct storage ws = P2Storage.load(); IBPool bPool = PBStorage.load().bPool; IERC20 token = IERC20(_token); require( token.transferFrom(msg.sender, address(this), _balance), "PV2SmartPool.bind: transferFrom failed" ); // Cancel potential weight adjustment process. ws.startBlock = 0; token.safeApprove(address(bPool), uint256(-1)); bPool.bind(_token, _balance, _denorm); } /** @notice Rebind a token to the pool @param _token Token to bind @param _balance Amount to bind @param _denorm Denormalised weight */ function rebind( address _token, uint256 _balance, uint256 _denorm ) external override onlyTokenBinder noReentry { P2Storage.StorageStruct storage ws = P2Storage.load(); IBPool bPool = PBStorage.load().bPool; IERC20 token = IERC20(_token); // gulp old non acounted for token balance in the contract bPool.gulp(_token); uint256 oldBalance = token.balanceOf(address(bPool)); // If tokens need to be pulled from msg.sender if (_balance > oldBalance) { require( token.transferFrom(msg.sender, address(this), _balance.bsub(oldBalance)), "PV2SmartPool.rebind: transferFrom failed" ); token.safeApprove(address(bPool), uint256(-1)); } bPool.rebind(_token, _balance, _denorm); // Cancel potential weight adjustment process. ws.startBlock = 0; // If any tokens are in this contract send them to msg.sender uint256 tokenBalance = token.balanceOf(address(this)); if (tokenBalance > 0) { require(token.transfer(msg.sender, tokenBalance), "PV2SmartPool.rebind: transfer failed"); } } /** @notice Unbind a token @param _token Token to unbind */ function unbind(address _token) external override onlyTokenBinder noReentry { P2Storage.StorageStruct storage ws = P2Storage.load(); IBPool bPool = PBStorage.load().bPool; IERC20 token = IERC20(_token); // unbind the token in the bPool bPool.unbind(_token); // Cancel potential weight adjustment process. ws.startBlock = 0; // If any tokens are in this contract send them to msg.sender uint256 tokenBalance = token.balanceOf(address(this)); if (tokenBalance > 0) { require(token.transfer(msg.sender, tokenBalance), "PV2SmartPool.unbind: transfer failed"); } } /** @notice Sets the controller address. Can only be set by the current controller @param _controller Address of the new controller */ function setController(address _controller) external override onlyController noReentry { emit ControllerChanged(PBStorage.load().controller, _controller); PBStorage.load().controller = _controller; } /** @notice Sets public swap setter address. Can only be set by the controller @param _newPublicSwapSetter Address of the new public swap setter */ function setPublicSwapSetter(address _newPublicSwapSetter) external override onlyController noReentry { emit PublicSwapSetterChanged(PBStorage.load().publicSwapSetter, _newPublicSwapSetter); PBStorage.load().publicSwapSetter = _newPublicSwapSetter; } /** @notice Sets the token binder address. Can only be set by the controller @param _newTokenBinder Address of the new token binder */ function setTokenBinder(address _newTokenBinder) external override onlyController noReentry { emit TokenBinderChanged(PBStorage.load().tokenBinder, _newTokenBinder); PBStorage.load().tokenBinder = _newTokenBinder; } /** @notice Enables or disables public swapping on the underlying balancer pool. Can only be set by the controller. @param _public Public or not */ function setPublicSwap(bool _public) external override onlyPublicSwapSetter noReentry { emit PublicSwapSet(msg.sender, _public); PBStorage.load().bPool.setPublicSwap(_public); } /** @notice Set the swap fee on the underlying balancer pool. Can only be called by the controller. @param _swapFee The new swap fee */ function setSwapFee(uint256 _swapFee) external override onlyController noReentry { emit SwapFeeSet(msg.sender, _swapFee); PBStorage.load().bPool.setSwapFee(_swapFee); } /** @notice Set the maximum cap of the contract @param _cap New cap in wei */ function setCap(uint256 _cap) external override onlyController noReentry { emit CapChanged(msg.sender, PCSStorage.load().cap, _cap); PCSStorage.load().cap = _cap; } /** @notice Enable or disable joining and exiting @param _newValue enabled or not */ function setJoinExitEnabled(bool _newValue) external override onlyController noReentry { emit JoinExitEnabledChanged(msg.sender, P2Storage.load().joinExitEnabled, _newValue); P2Storage.load().joinExitEnabled = _newValue; } /** @notice Set the circuit breaker address. Can only be called by the controller @param _newCircuitBreaker Address of the new circuit breaker */ function setCircuitBreaker( address _newCircuitBreaker ) external override onlyController noReentry { emit CircuitBreakerChanged(P2Storage.load().circuitBreaker, _newCircuitBreaker); P2Storage.load().circuitBreaker = _newCircuitBreaker; } /** @notice Set the annual fee. Can only be called by the controller @param _newFee new fee 10**18 == 100% per 365 days. Max 10% */ function setAnnualFee(uint256 _newFee) external override onlyController noReentry { LibFees.setAnnualFee(_newFee); } /** @notice Charge the outstanding annual fee */ function chargeOutstandingAnnualFee() external override noReentry { LibFees.chargeOutstandingAnnualFee(); } /** @notice Set the address that receives the annual fee. Can only be called by the controller */ function setFeeRecipient(address _newRecipient) external override onlyController noReentry { LibFees.setFeeRecipient(_newRecipient); } /** @notice Trip the circuit breaker which disabled exit, join and swaps */ function tripCircuitBreaker() external override onlyCircuitBreaker { P2Storage.load().joinExitEnabled = false; PBStorage.load().bPool.setPublicSwap(false); emit CircuitBreakerTripped(); } // TOKEN AND WEIGHT FUNCTIONS ------------------------------- /** @notice Update the weight of a token. Can only be called by the controller @param _token Token to adjust the weight of @param _newWeight New denormalized weight */ function updateWeight(address _token, uint256 _newWeight) external override noReentry onlyController { LibWeights.updateWeight(_token, _newWeight); } /** @notice Gradually adjust the weights of a token. Can only be called by the controller @param _newWeights Target weights @param _startBlock Block to start weight adjustment @param _endBlock Block to finish weight adjustment */ function updateWeightsGradually( uint256[] calldata _newWeights, uint256 _startBlock, uint256 _endBlock ) external override noReentry onlyController { LibWeights.updateWeightsGradually(_newWeights, _startBlock, _endBlock); } /** @notice Poke the weight adjustment */ function pokeWeights() external override noReentry { LibWeights.pokeWeights(); } /** @notice Apply the adding of a token. Can only be called by the controller */ function applyAddToken() external override noReentry onlyController { LibAddRemoveToken.applyAddToken(); } /** @notice Commit a token to be added. Can only be called by the controller @param _token Address of the token to add @param _balance Amount of token to add @param _denormalizedWeight Denormalized weight */ function commitAddToken( address _token, uint256 _balance, uint256 _denormalizedWeight ) external override noReentry onlyController { LibAddRemoveToken.commitAddToken(_token, _balance, _denormalizedWeight); } /** @notice Remove a token from the smart pool. Can only be called by the controller @param _token Address of the token to remove */ function removeToken(address _token) external override noReentry onlyController { LibAddRemoveToken.removeToken(_token); } // VIEW FUNCTIONS ------------------------------------------- /** @notice Gets the underlying assets and amounts to mint specific pool shares. @param _amount Amount of pool shares to calculate the values for @return tokens The addresses of the tokens @return amounts The amounts of tokens needed to mint that amount of pool shares */ function calcTokensForAmount(uint256 _amount) external override view returns (address[] memory tokens, uint256[] memory amounts) { return LibPoolMath.calcTokensForAmount(_amount); } /** @notice Calculate the amount of pool tokens out for a given amount in @param _token Address of the input token @param _amount Amount of input token @return Amount of pool token */ function calcPoolOutGivenSingleIn(address _token, uint256 _amount) external override view returns (uint256) { return LibPoolMath.calcPoolOutGivenSingleIn(_token, _amount); } /** @notice Calculate single in given pool out @param _token Address of the input token @param _amount Amount of pool out token @return Amount of token in */ function calcSingleInGivenPoolOut(address _token, uint256 _amount) external override view returns (uint256) { return LibPoolMath.calcSingleInGivenPoolOut(_token, _amount); } /** @notice Calculate single out given pool in @param _token Address of output token @param _amount Amount of pool in @return Amount of token in */ function calcSingleOutGivenPoolIn(address _token, uint256 _amount) external override view returns (uint256) { return LibPoolMath.calcSingleOutGivenPoolIn(_token, _amount); } /** @notice Calculate pool in given single token out @param _token Address of output token @param _amount Amount of output token @return Amount of pool in */ function calcPoolInGivenSingleOut(address _token, uint256 _amount) external override view returns (uint256) { return LibPoolMath.calcPoolInGivenSingleOut(_token, _amount); } /** @notice Get the current tokens in the smart pool @return Addresses of the tokens in the smart pool */ function getTokens() external override view returns (address[] memory) { return PBStorage.load().bPool.getCurrentTokens(); } /** @notice Get the address of the controller @return The address of the pool */ function getController() external override view returns (address) { return PBStorage.load().controller; } /** @notice Get the address of the public swap setter @return The public swap setter address */ function getPublicSwapSetter() external override view returns (address) { return PBStorage.load().publicSwapSetter; } /** @notice Get the address of the token binder @return The token binder address */ function getTokenBinder() external override view returns (address) { return PBStorage.load().tokenBinder; } /** @notice Get the address of the circuitBreaker @return The address of the circuitBreaker */ function getCircuitBreaker() external override view returns (address) { return P2Storage.load().circuitBreaker; } /** @notice Get if public swapping is enabled @return If public swapping is enabled */ function isPublicSwap() external override view returns (bool) { return PBStorage.load().bPool.isPublicSwap(); } /** @notice Get the current cap @return The current cap in wei */ function getCap() external override view returns (uint256) { return PCSStorage.load().cap; } function getAnnualFee() external override view returns (uint256) { return P2Storage.load().annualFee; } function getFeeRecipient() external override view returns (address) { return P2Storage.load().feeRecipient; } /** @notice Get the denormalized weight of a specific token in the underlying balancer pool @return the normalized weight of the token in uint */ function getDenormalizedWeight(address _token) external override view returns (uint256) { return PBStorage.load().bPool.getDenormalizedWeight(_token); } /** @notice Get all denormalized weights @return weights Denormalized weights */ function getDenormalizedWeights() external override view returns (uint256[] memory weights) { PBStorage.StorageStruct storage s = PBStorage.load(); address[] memory tokens = s.bPool.getCurrentTokens(); weights = new uint256[](tokens.length); for (uint256 i = 0; i < tokens.length; i++) { weights[i] = s.bPool.getDenormalizedWeight(tokens[i]); } } /** @notice Get the address of the underlying Balancer pool @return The address of the underlying balancer pool */ function getBPool() external override view returns (address) { return address(PBStorage.load().bPool); } /** @notice Get the current swap fee @return The current swap fee */ function getSwapFee() external override view returns (uint256) { return PBStorage.load().bPool.getSwapFee(); } /** @notice Get the target weights @return weights Target weights */ function getNewWeights() external override view returns (uint256[] memory weights) { return P2Storage.load().newWeights; } /** @notice Get weights at start of weight adjustment @return weights Start weights */ function getStartWeights() external override view returns (uint256[] memory weights) { return P2Storage.load().startWeights; } /** @notice Get start block of weight adjustment @return Start block */ function getStartBlock() external override view returns (uint256) { return P2Storage.load().startBlock; } /** @notice Get end block of weight adjustment @return End block */ function getEndBlock() external override view returns (uint256) { return P2Storage.load().endBlock; } /** @notice Get new token being added @return New token */ function getNewToken() external override view returns (P2Storage.NewToken memory) { return P2Storage.load().newToken; } /** @notice Get if joining and exiting is enabled @return Enabled or not */ function getJoinExitEnabled() external override view returns (bool) { return P2Storage.load().joinExitEnabled; } // UNSUPORTED METHODS --------------------------------------- /** @notice Not Supported in PieDAO implementation of Balancer Smart Pools */ function finalizeSmartPool() external override view { revert("PV2SmartPool.finalizeSmartPool: unsupported function"); } /** @notice Not Supported in PieDAO implementation of Balancer Smart Pools */ function createPool(uint256 initialSupply) external override view { revert("PV2SmartPool.createPool: unsupported function"); } } pragma solidity ^0.6.4; library PCappedSmartPoolStorage { bytes32 public constant pcsSlot = keccak256("PCappedSmartPool.storage.location"); struct StorageStruct { uint256 cap; } /** @notice Load PBasicPool storage @return s Pointer to the storage struct */ function load() internal pure returns (StorageStruct storage s) { bytes32 loc = pcsSlot; assembly { s_slot := loc } } } pragma experimental ABIEncoderV2; pragma solidity 0.6.4; import "../interfaces/IPV3SmartPool.sol"; import "../interfaces/IBPool.sol"; import "../PCToken.sol"; import "../ReentryProtection.sol"; import "../libraries/LibPoolToken.sol"; import "../libraries/LibAddRemoveToken.sol"; import "../libraries/LibPoolEntryExitV2.sol"; import "../libraries/LibPoolMath.sol"; import "../libraries/LibWeights.sol"; import "../libraries/LibSafeApprove.sol"; import {PBasicSmartPoolStorage as PBStorage} from "../storage/PBasicSmartPoolStorage.sol"; import {PCTokenStorage as PCStorage} from "../storage/PCTokenStorage.sol"; import {PCappedSmartPoolStorage as PCSStorage} from "../storage/PCappedSmartPoolStorage.sol"; import {PV2SmartPoolStorage as P2Storage} from "../storage/PV2SmartPoolStorage.sol"; contract PV3SmartPool is IPV3SmartPool, PCToken, ReentryProtection { using LibSafeApprove for IERC20; event TokensApproved(); event ControllerChanged(address indexed previousController, address indexed newController); event PublicSwapSetterChanged(address indexed previousSetter, address indexed newSetter); event TokenBinderChanged(address indexed previousTokenBinder, address indexed newTokenBinder); event PublicSwapSet(address indexed setter, bool indexed value); event SwapFeeSet(address indexed setter, uint256 newFee); event CapChanged(address indexed setter, uint256 oldCap, uint256 newCap); event CircuitBreakerTripped(); event JoinExitEnabledChanged(address indexed setter, bool oldValue, bool newValue); event CircuitBreakerChanged( address indexed _oldCircuitBreaker, address indexed _newCircuitBreaker ); modifier ready() { require(address(PBStorage.load().bPool) != address(0), "PV3SmartPool.ready: not ready"); _; } modifier onlyController() { require( msg.sender == PBStorage.load().controller, "PV3SmartPool.onlyController: not controller" ); _; } modifier onlyPublicSwapSetter() { require( msg.sender == PBStorage.load().publicSwapSetter, "PV3SmartPool.onlyPublicSwapSetter: not public swap setter" ); _; } modifier onlyTokenBinder() { require( msg.sender == PBStorage.load().tokenBinder, "PV3SmartPool.onlyTokenBinder: not token binder" ); _; } modifier onlyPublicSwap() { require( PBStorage.load().bPool.isPublicSwap(), "PV3SmartPool.onlyPublicSwap: swapping not enabled" ); _; } modifier onlyCircuitBreaker() { require( msg.sender == P2Storage.load().circuitBreaker, "PV3SmartPool.onlyCircuitBreaker: not circuit breaker" ); _; } modifier onlyJoinExitEnabled() { require( P2Storage.load().joinExitEnabled, "PV3SmartPool.onlyJoinExitEnabled: join and exit not enabled" ); _; } modifier withinCap() { _; require(totalSupply() < PCSStorage.load().cap, "PV3SmartPool.withinCap: Cap limit reached"); } /** @notice Initialises the contract @param _bPool Address of the underlying balancer pool @param _name Name for the smart pool token @param _symbol Symbol for the smart pool token @param _initialSupply Initial token supply to mint */ function init( address _bPool, string calldata _name, string calldata _symbol, uint256 _initialSupply ) external override { PBStorage.StorageStruct storage s = PBStorage.load(); require(address(s.bPool) == address(0), "PV3SmartPool.init: already initialised"); require(_bPool != address(0), "PV3SmartPool.init: _bPool cannot be 0x00....000"); require(_initialSupply != 0, "PV3SmartPool.init: _initialSupply can not zero"); s.bPool = IBPool(_bPool); s.controller = msg.sender; s.publicSwapSetter = msg.sender; s.tokenBinder = msg.sender; PCStorage.load().name = _name; PCStorage.load().symbol = _symbol; LibPoolToken._mint(msg.sender, _initialSupply); } /** @notice Sets approval to all tokens to the underlying balancer pool @dev It uses this function to save on gas in joinPool */ function approveTokens() public override noReentry { IBPool bPool = PBStorage.load().bPool; address[] memory tokens = bPool.getCurrentTokens(); for (uint256 i = 0; i < tokens.length; i++) { IERC20(tokens[i]).safeApprove(address(bPool), uint256(-1)); } emit TokensApproved(); } // POOL EXIT ------------------------------------------------ /** @notice Burns pool shares and sends back the underlying assets leaving some in the pool @param _amount Amount of pool tokens to burn @param _lossTokens Tokens skipped on redemption */ function exitPoolTakingloss(uint256 _amount, address[] calldata _lossTokens) external override ready noReentry onlyJoinExitEnabled { LibPoolEntryExitV2.exitPoolTakingloss(_amount, _lossTokens); } /** @notice Burns pool shares and sends back the underlying assets @param _amount Amount of pool tokens to burn */ function exitPool(uint256 _amount) external override ready noReentry onlyJoinExitEnabled { LibPoolEntryExitV2.exitPool(_amount); } /** @notice Burn pool tokens and redeem underlying assets. With front running protection @param _amount Amount of pool tokens to burn @param _minAmountsOut Minimum amounts of underlying assets */ function exitPool(uint256 _amount, uint256[] calldata _minAmountsOut) external override ready noReentry onlyJoinExitEnabled { LibPoolEntryExitV2.exitPool(_amount, _minAmountsOut); } /** @notice Exitswap single asset pool exit given pool amount in @param _token Address of exit token @param _poolAmountIn Amount of pool tokens sending to the pool @return tokenAmountOut amount of exit tokens being withdrawn */ function exitswapPoolAmountIn( address _token, uint256 _poolAmountIn, uint256 _minAmountOut ) external override ready noReentry onlyPublicSwap onlyJoinExitEnabled returns (uint256 tokenAmountOut) { return LibPoolEntryExitV2.exitswapPoolAmountIn(_token, _poolAmountIn, _minAmountOut); } /** @notice Exitswap single asset pool entry given token amount out @param _token Address of exit token @param _tokenAmountOut Amount of exit tokens @return poolAmountIn amount of pool tokens being deposited */ function exitswapExternAmountOut( address _token, uint256 _tokenAmountOut, uint256 _maxPoolAmountIn ) external override ready noReentry onlyPublicSwap onlyJoinExitEnabled returns (uint256 poolAmountIn) { return LibPoolEntryExitV2.exitswapExternAmountOut(_token, _tokenAmountOut, _maxPoolAmountIn); } // POOL ENTRY ----------------------------------------------- /** @notice Takes underlying assets and mints smart pool tokens. Enforces the cap @param _amount Amount of pool tokens to mint */ function joinPoolExpress(uint256 _amount, uint16 _referral) external override withinCap ready noReentry onlyJoinExitEnabled { LibPoolEntryExitV2.joinPoolExpress(_amount, _referral); } /** @notice Takes underlying assets and mints smart pool tokens. Enforces the cap. Allows you to specify the maximum amounts of underlying assets @param _amount Amount of pool tokens to mint */ function joinPool( uint256 _amount, uint256[] calldata _maxAmountsIn, uint16 _referral ) external override withinCap ready noReentry onlyJoinExitEnabled { LibPoolEntryExitV2.joinPool(_amount, _maxAmountsIn, _referral); } /** @notice Joinswap single asset pool entry given token amount in @param _token Address of entry token @param _amountIn Amount of entry tokens @return poolAmountOut */ function joinswapExternAmountIn( address _token, uint256 _amountIn, uint256 _minPoolAmountOut, uint16 _referral ) external override ready withinCap onlyPublicSwap noReentry onlyJoinExitEnabled returns (uint256 poolAmountOut) { return LibPoolEntryExitV2.joinswapExternAmountIn(_token, _amountIn, _minPoolAmountOut, _referral); } /** @notice Joinswap single asset pool entry given pool amount out @param _token Address of entry token @param _amountOut Amount of entry tokens to deposit into the pool @return tokenAmountIn */ function joinswapPoolAmountOut( address _token, uint256 _amountOut, uint256 _maxAmountIn, uint16 _referral ) external override ready withinCap onlyPublicSwap noReentry onlyJoinExitEnabled returns (uint256 tokenAmountIn) { return LibPoolEntryExitV2.joinswapPoolAmountOut(_token, _amountOut, _maxAmountIn, _referral); } // ADMIN FUNCTIONS ------------------------------------------ /** @notice Bind a token to the underlying balancer pool. Can only be called by the token binder @param _token Token to bind @param _balance Amount to bind @param _denorm Denormalised weight */ function bind( address _token, uint256 _balance, uint256 _denorm ) external override onlyTokenBinder noReentry { P2Storage.StorageStruct storage ws = P2Storage.load(); IBPool bPool = PBStorage.load().bPool; IERC20 token = IERC20(_token); require( token.transferFrom(msg.sender, address(this), _balance), "PV3SmartPool.bind: transferFrom failed" ); // Cancel potential weight adjustment process. ws.startBlock = 0; token.safeApprove(address(bPool), uint256(-1)); bPool.bind(_token, _balance, _denorm); } /** @notice Rebind a token to the pool @param _token Token to bind @param _balance Amount to bind @param _denorm Denormalised weight */ function rebind( address _token, uint256 _balance, uint256 _denorm ) external override onlyTokenBinder noReentry { P2Storage.StorageStruct storage ws = P2Storage.load(); IBPool bPool = PBStorage.load().bPool; IERC20 token = IERC20(_token); // gulp old non acounted for token balance in the contract bPool.gulp(_token); uint256 oldBalance = token.balanceOf(address(bPool)); // If tokens need to be pulled from msg.sender if (_balance > oldBalance) { require( token.transferFrom(msg.sender, address(this), _balance.bsub(oldBalance)), "PV3SmartPool.rebind: transferFrom failed" ); token.safeApprove(address(bPool), uint256(-1)); } bPool.rebind(_token, _balance, _denorm); // Cancel potential weight adjustment process. ws.startBlock = 0; // If any tokens are in this contract send them to msg.sender uint256 tokenBalance = token.balanceOf(address(this)); if (tokenBalance > 0) { require(token.transfer(msg.sender, tokenBalance), "PV3SmartPool.rebind: transfer failed"); } } /** @notice Unbind a token @param _token Token to unbind */ function unbind(address _token) external override onlyTokenBinder noReentry { P2Storage.StorageStruct storage ws = P2Storage.load(); IBPool bPool = PBStorage.load().bPool; IERC20 token = IERC20(_token); // unbind the token in the bPool bPool.unbind(_token); // Cancel potential weight adjustment process. ws.startBlock = 0; // If any tokens are in this contract send them to msg.sender uint256 tokenBalance = token.balanceOf(address(this)); if (tokenBalance > 0) { require(token.transfer(msg.sender, tokenBalance), "PV3SmartPool.unbind: transfer failed"); } } /** @notice Sets the controller address. Can only be set by the current controller @param _controller Address of the new controller */ function setController(address _controller) external override onlyController noReentry { emit ControllerChanged(PBStorage.load().controller, _controller); PBStorage.load().controller = _controller; } /** @notice Sets public swap setter address. Can only be set by the controller @param _newPublicSwapSetter Address of the new public swap setter */ function setPublicSwapSetter(address _newPublicSwapSetter) external override onlyController noReentry { emit PublicSwapSetterChanged(PBStorage.load().publicSwapSetter, _newPublicSwapSetter); PBStorage.load().publicSwapSetter = _newPublicSwapSetter; } /** @notice Sets the token binder address. Can only be set by the controller @param _newTokenBinder Address of the new token binder */ function setTokenBinder(address _newTokenBinder) external override onlyController noReentry { emit TokenBinderChanged(PBStorage.load().tokenBinder, _newTokenBinder); PBStorage.load().tokenBinder = _newTokenBinder; } /** @notice Enables or disables public swapping on the underlying balancer pool. Can only be set by the controller. @param _public Public or not */ function setPublicSwap(bool _public) external override onlyPublicSwapSetter noReentry { emit PublicSwapSet(msg.sender, _public); PBStorage.load().bPool.setPublicSwap(_public); } /** @notice Set the swap fee on the underlying balancer pool. Can only be called by the controller. @param _swapFee The new swap fee */ function setSwapFee(uint256 _swapFee) external override onlyController noReentry { emit SwapFeeSet(msg.sender, _swapFee); PBStorage.load().bPool.setSwapFee(_swapFee); } /** @notice Set the maximum cap of the contract @param _cap New cap in wei */ function setCap(uint256 _cap) external override onlyController noReentry { emit CapChanged(msg.sender, PCSStorage.load().cap, _cap); PCSStorage.load().cap = _cap; } /** @notice Enable or disable joining and exiting @param _newValue enabled or not */ function setJoinExitEnabled(bool _newValue) external override onlyController noReentry { emit JoinExitEnabledChanged(msg.sender, P2Storage.load().joinExitEnabled, _newValue); P2Storage.load().joinExitEnabled = _newValue; } /** @notice Set the circuit breaker address. Can only be called by the controller @param _newCircuitBreaker Address of the new circuit breaker */ function setCircuitBreaker(address _newCircuitBreaker) external override onlyController noReentry { emit CircuitBreakerChanged(P2Storage.load().circuitBreaker, _newCircuitBreaker); P2Storage.load().circuitBreaker = _newCircuitBreaker; } /** @notice Set the annual fee. Can only be called by the controller @param _newFee new fee 10**18 == 100% per 365 days. Max 10% */ function setAnnualFee(uint256 _newFee) external override onlyController noReentry { LibFees.setAnnualFee(_newFee); } /** @notice Charge the outstanding annual fee */ function chargeOutstandingAnnualFee() external override noReentry { LibFees.chargeOutstandingAnnualFee(); } /** @notice Set the address that receives the annual fee. Can only be called by the controller */ function setFeeRecipient(address _newRecipient) external override onlyController noReentry { LibFees.setFeeRecipient(_newRecipient); } /** @notice Trip the circuit breaker which disabled exit, join and swaps */ function tripCircuitBreaker() external override onlyCircuitBreaker { P2Storage.load().joinExitEnabled = false; PBStorage.load().bPool.setPublicSwap(false); emit CircuitBreakerTripped(); } // TOKEN AND WEIGHT FUNCTIONS ------------------------------- /** @notice Update the weight of a token. Can only be called by the controller @param _token Token to adjust the weight of @param _newWeight New denormalized weight */ function updateWeight(address _token, uint256 _newWeight) external override noReentry onlyController { LibWeights.updateWeight(_token, _newWeight); } /** @notice Gradually adjust the weights of a token. Can only be called by the controller @param _newWeights Target weights @param _startBlock Block to start weight adjustment @param _endBlock Block to finish weight adjustment */ function updateWeightsGradually( uint256[] calldata _newWeights, uint256 _startBlock, uint256 _endBlock ) external override noReentry onlyController { LibWeights.updateWeightsGradually(_newWeights, _startBlock, _endBlock); } /** @notice Poke the weight adjustment */ function pokeWeights() external override noReentry { LibWeights.pokeWeights(); } /** @notice Apply the adding of a token. Can only be called by the controller */ function applyAddToken() external override noReentry onlyController { LibAddRemoveToken.applyAddToken(); } /** @notice Commit a token to be added. Can only be called by the controller @param _token Address of the token to add @param _balance Amount of token to add @param _denormalizedWeight Denormalized weight */ function commitAddToken( address _token, uint256 _balance, uint256 _denormalizedWeight ) external override noReentry onlyController { LibAddRemoveToken.commitAddToken(_token, _balance, _denormalizedWeight); } /** @notice Remove a token from the smart pool. Can only be called by the controller @param _token Address of the token to remove */ function removeToken(address _token) external override noReentry onlyController { LibAddRemoveToken.removeToken(_token); } // VIEW FUNCTIONS ------------------------------------------- /** @notice Gets the underlying assets and amounts to mint specific pool shares. @param _amount Amount of pool shares to calculate the values for @return tokens The addresses of the tokens @return amounts The amounts of tokens needed to mint that amount of pool shares */ function calcTokensForAmount(uint256 _amount) external view override returns (address[] memory tokens, uint256[] memory amounts) { return LibPoolMath.calcTokensForAmount(_amount); } /** @notice Calculate the amount of pool tokens out for a given amount in @param _token Address of the input token @param _amount Amount of input token @return Amount of pool token */ function calcPoolOutGivenSingleIn(address _token, uint256 _amount) external view override returns (uint256) { return LibPoolMath.calcPoolOutGivenSingleIn(_token, _amount); } /** @notice Calculate single in given pool out @param _token Address of the input token @param _amount Amount of pool out token @return Amount of token in */ function calcSingleInGivenPoolOut(address _token, uint256 _amount) external view override returns (uint256) { return LibPoolMath.calcSingleInGivenPoolOut(_token, _amount); } /** @notice Calculate single out given pool in @param _token Address of output token @param _amount Amount of pool in @return Amount of token in */ function calcSingleOutGivenPoolIn(address _token, uint256 _amount) external view override returns (uint256) { return LibPoolMath.calcSingleOutGivenPoolIn(_token, _amount); } /** @notice Calculate pool in given single token out @param _token Address of output token @param _amount Amount of output token @return Amount of pool in */ function calcPoolInGivenSingleOut(address _token, uint256 _amount) external view override returns (uint256) { return LibPoolMath.calcPoolInGivenSingleOut(_token, _amount); } /** @notice Get the current tokens in the smart pool @return Addresses of the tokens in the smart pool */ function getTokens() external view override returns (address[] memory) { return PBStorage.load().bPool.getCurrentTokens(); } /** @notice Get the address of the controller @return The address of the pool */ function getController() external view override returns (address) { return PBStorage.load().controller; } /** @notice Get the address of the public swap setter @return The public swap setter address */ function getPublicSwapSetter() external view override returns (address) { return PBStorage.load().publicSwapSetter; } /** @notice Get the address of the token binder @return The token binder address */ function getTokenBinder() external view override returns (address) { return PBStorage.load().tokenBinder; } /** @notice Get the address of the circuitBreaker @return The address of the circuitBreaker */ function getCircuitBreaker() external view override returns (address) { return P2Storage.load().circuitBreaker; } /** @notice Get if public swapping is enabled @return If public swapping is enabled */ function isPublicSwap() external view override returns (bool) { return PBStorage.load().bPool.isPublicSwap(); } /** @notice Get the current cap @return The current cap in wei */ function getCap() external view override returns (uint256) { return PCSStorage.load().cap; } function getAnnualFee() external view override returns (uint256) { return P2Storage.load().annualFee; } function getFeeRecipient() external view override returns (address) { return P2Storage.load().feeRecipient; } /** @notice Get the denormalized weight of a specific token in the underlying balancer pool @return the normalized weight of the token in uint */ function getDenormalizedWeight(address _token) external view override returns (uint256) { return PBStorage.load().bPool.getDenormalizedWeight(_token); } /** @notice Get all denormalized weights @return weights Denormalized weights */ function getDenormalizedWeights() external view override returns (uint256[] memory weights) { PBStorage.StorageStruct storage s = PBStorage.load(); address[] memory tokens = s.bPool.getCurrentTokens(); weights = new uint256[](tokens.length); for (uint256 i = 0; i < tokens.length; i++) { weights[i] = s.bPool.getDenormalizedWeight(tokens[i]); } } /** @notice Get the address of the underlying Balancer pool @return The address of the underlying balancer pool */ function getBPool() external view override returns (address) { return address(PBStorage.load().bPool); } /** @notice Get the current swap fee @return The current swap fee */ function getSwapFee() external view override returns (uint256) { return PBStorage.load().bPool.getSwapFee(); } /** @notice Get the target weights @return weights Target weights */ function getNewWeights() external view override returns (uint256[] memory weights) { return P2Storage.load().newWeights; } /** @notice Get weights at start of weight adjustment @return weights Start weights */ function getStartWeights() external view override returns (uint256[] memory weights) { return P2Storage.load().startWeights; } /** @notice Get start block of weight adjustment @return Start block */ function getStartBlock() external view override returns (uint256) { return P2Storage.load().startBlock; } /** @notice Get end block of weight adjustment @return End block */ function getEndBlock() external view override returns (uint256) { return P2Storage.load().endBlock; } /** @notice Get new token being added @return New token */ function getNewToken() external view override returns (P2Storage.NewToken memory) { return P2Storage.load().newToken; } /** @notice Get if joining and exiting is enabled @return Enabled or not */ function getJoinExitEnabled() external view override returns (bool) { return P2Storage.load().joinExitEnabled; } // UNSUPORTED METHODS --------------------------------------- /** @notice Not Supported in PieDAO implementation of Balancer Smart Pools */ function finalizeSmartPool() external view override { revert("PV3SmartPool.finalizeSmartPool: unsupported function"); } /** @notice Not Supported in PieDAO implementation of Balancer Smart Pools */ function createPool(uint256 initialSupply) external view override { revert("PV3SmartPool.createPool: unsupported function"); } } pragma solidity 0.6.4; import "../libraries/LibSafeApprove.sol"; import "../interfaces/IERC20.sol"; contract TestLibSafeApprove { using LibSafeApprove for IERC20; function doubleApprovalUnsafe(address _token) external { IERC20 token = IERC20(_token); token.approve(msg.sender, 1337); token.approve(msg.sender, 42); } function doubleApprovalSafe(address _token) external { IERC20 token = IERC20(_token); token.safeApprove(msg.sender, 1337); token.safeApprove(msg.sender, 42); } } pragma solidity 0.6.4; import "../PCToken.sol"; contract TestPCToken is PCToken { constructor(string memory _name, string memory _symbol) public { PCStorage.load().name = _name; PCStorage.load().symbol = _symbol; } function mint(address _to, uint256 _amount) external { _mint(_amount); _push(_to, _amount); } function burn(address _from, uint256 _amount) external { _pull(_from, _amount); _burn(_amount); } } pragma solidity 0.6.4; import "../ReentryProtection.sol"; contract TestReentryProtection is ReentryProtection { // This should fail function test() external noReentry { reenter(); } function reenter() public noReentry { // Do nothing } }
If weight goes down we need to pull tokens and burn pool shares New balance cannot be lower than MIN_BALANCE First gets the tokens from this contract (Pool Controller) to msg.sender Now with the tokens this contract can send them to msg.sender Cancel potential weight adjustment process. This means the controller will deposit tokens to keep the price. They will be minted and given PCTokens First gets the tokens from msg.sender to this contract (Pool Controller) Now with the tokens this contract can bind them to the pool it controls Cancel potential weight adjustment process.
function updateWeight(address _token, uint256 _newWeight) external { PBStorage.StorageStruct storage s = PBStorage.load(); P2Storage.StorageStruct storage ws = P2Storage.load(); require(_newWeight >= constants.MIN_WEIGHT, "ERR_MIN_WEIGHT"); require(_newWeight <= constants.MAX_WEIGHT, "ERR_MAX_WEIGHT"); uint256 currentWeight = s.bPool.getDenormalizedWeight(_token); uint256 currentBalance = s.bPool.getBalance(_token); uint256 poolShares; uint256 deltaBalance; uint256 deltaWeight; uint256 totalSupply = PCStorage.load().totalSupply; uint256 totalWeight = s.bPool.getTotalDenormalizedWeight(); if (_newWeight < currentWeight) { require( totalWeight.badd(currentWeight.bsub(_newWeight)) <= constants.MAX_TOTAL_WEIGHT, "ERR_MAX_TOTAL_WEIGHT" ); deltaWeight = currentWeight.bsub(_newWeight); poolShares = totalSupply.bmul(deltaWeight.bdiv(totalWeight)); deltaBalance = currentBalance.bmul(deltaWeight.bdiv(currentWeight)); require(currentBalance.bsub(deltaBalance) >= constants.MIN_BALANCE, "ERR_MIN_BALANCE"); s.bPool.rebind(_token, currentBalance.bsub(deltaBalance), _newWeight); require(IERC20(_token).transfer(msg.sender, deltaBalance), "ERR_ERC20_FALSE"); ws.startBlock = 0; LibPoolToken._burn(msg.sender, poolShares); require( totalWeight.badd(_newWeight.bsub(currentWeight)) <= constants.MAX_TOTAL_WEIGHT, "ERR_MAX_TOTAL_WEIGHT" ); deltaWeight = _newWeight.bsub(currentWeight); poolShares = totalSupply.bmul(deltaWeight.bdiv(totalWeight)); deltaBalance = currentBalance.bmul(deltaWeight.bdiv(currentWeight)); require( IERC20(_token).transferFrom(msg.sender, address(this), deltaBalance), "TRANSFER_FAILED" ); s.bPool.rebind(_token, currentBalance.badd(deltaBalance), _newWeight); ws.startBlock = 0; LibPoolToken._mint(msg.sender, poolShares); } }
189,133
./full_match/4/0x3119FB10878E8B80b57cc5C5348788C54F89b358/sources/ERC1155Tradable.sol
Mints some amount of tokens to an address _to Address of the future owner of the token _id Token ID to mint _quantity Amount of tokens to mint _data Data to pass if receiver is contract/
function mint( address _to, uint256 _id, uint256 _quantity, string memory metadata, bytes memory _data )public returns (uint256){ creators[_id] = _msgSender(); if (bytes(metadata).length > 0) { customUri[_id] = metadata; emit URI(metadata, _id); } _mint(_to, _id, _quantity, _data); tokenSupply[_id] = tokenSupply[_id].add(_quantity); return _id; }
757,662
./partial_match/137/0xD1178fC23853c2d469fddf5303F1bB026FbD3DB9/sources/WildcardSteward_matic_v1.sol
if credit balance exists, if amount owed > creidt credit zero add amount else reduce credit by certain amount. else if credit balance doesn't exist add amount to balance TODO: this function should have an event
function _updateBenefactorBalance(address benefactor) public { uint256 patronageDueForBenefactor = patronageDueBenefactor(benefactor); if (patronageDueForBenefactor > 0) { _increaseBenefactorBalance(benefactor, patronageDueForBenefactor); } timeLastCollectedBenefactor[benefactor] = now; }
3,527,423
./full_match/1/0xFe37f99cd0597164BFdaBFB7c9f98E4fc44BeF52/sources/src/lender/assessor.sol
returns the total balance including unused creditline from adapters which means the total balance if the creditline were fully used return _totalBalance total balance
function totalBalance() public view returns (uint256 _totalBalance) { return safeAdd(reserve.totalBalance(), remainingCredit()); }
16,433,459
./full_match/1/0xE100D280DEc73D47328D074A22e9bEa744DaF195/sources/browser/Treasury-flattened.sol
return the principal that has been been added to the contract. This can never be withdrawn./
function principle() public view returns (uint256) { return _principle; }
8,391,802
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; pragma abicoder v2; // OpenZeppelin v4 import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { StorageSlot } from "@openzeppelin/contracts/utils/StorageSlot.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import { SNARK_SCALAR_FIELD, TokenType, WithdrawType, TokenData, CommitmentCiphertext, CommitmentPreimage, Transaction } from "./Globals.sol"; import { Verifier } from "./Verifier.sol"; import { Commitments } from "./Commitments.sol"; import { TokenBlacklist } from "./TokenBlacklist.sol"; import { PoseidonT4 } from "./Poseidon.sol"; /** * @title Railgun Logic * @author Railgun Contributors * @notice Functions to interact with the railgun contract * @dev Wallets for Railgun will only need to interact with functions specified in this contract. * This contract is written to be run behind a ERC1967-like proxy. Upon deployment of proxy the _data parameter should * call the initializeRailgunLogic function. */ contract RailgunLogic is Initializable, OwnableUpgradeable, Commitments, TokenBlacklist, Verifier { using SafeERC20 for IERC20; // NOTE: The order of instantiation MUST stay the same across upgrades // add new variables to the bottom of the list // See https://docs.openzeppelin.com/learn/upgrading-smart-contracts#upgrading // Treasury variables address payable public treasury; // Treasury contract uint120 private constant BASIS_POINTS = 10000; // Number of basis points that equal 100% // % fee in 100ths of a %. 100 = 1%. uint120 public depositFee; uint120 public withdrawFee; // Flat fee in wei that applies to NFT transactions uint256 public nftFee; // Safety vectors mapping(uint256 => bool) public snarkSafetyVector; // Treasury events event TreasuryChange(address treasury); event FeeChange(uint256 depositFee, uint256 withdrawFee, uint256 nftFee); // Transaction events event CommitmentBatch( uint256 treeNumber, uint256 startPosition, uint256[] hash, CommitmentCiphertext[] ciphertext ); event GeneratedCommitmentBatch( uint256 treeNumber, uint256 startPosition, CommitmentPreimage[] commitments, uint256[2][] encryptedRandom ); event Nullifiers(uint256 treeNumber, uint256[] nullifier); /** * @notice Initialize Railgun contract * @dev OpenZeppelin initializer ensures this can only be called once * This function also calls initializers on inherited contracts * @param _treasury - address to send usage fees to * @param _depositFee - Deposit fee * @param _withdrawFee - Withdraw fee * @param _nftFee - Flat fee in wei that applies to NFT transactions * @param _owner - governance contract */ function initializeRailgunLogic( address payable _treasury, uint120 _depositFee, uint120 _withdrawFee, uint256 _nftFee, address _owner ) external initializer { // Call initializers OwnableUpgradeable.__Ownable_init(); Commitments.initializeCommitments(); // Set treasury and fee changeTreasury(_treasury); changeFee(_depositFee, _withdrawFee, _nftFee); // Change Owner OwnableUpgradeable.transferOwnership(_owner); // Set safety vectors snarkSafetyVector[11991246288605609459798790887503763024866871101] = true; snarkSafetyVector[135932600361240492381964832893378343190771392134] = true; snarkSafetyVector[1165567609304106638376634163822860648671860889162] = true; } /** * @notice Change treasury address, only callable by owner (governance contract) * @dev This will change the address of the contract we're sending the fees to in the future * it won't transfer tokens already in the treasury * @param _treasury - Address of new treasury contract */ function changeTreasury(address payable _treasury) public onlyOwner { // Do nothing if the new treasury address is same as the old if (treasury != _treasury) { // Change treasury treasury = _treasury; // Emit treasury change event emit TreasuryChange(_treasury); } } /** * @notice Change fee rate for future transactions * @param _depositFee - Deposit fee * @param _withdrawFee - Withdraw fee * @param _nftFee - Flat fee in wei that applies to NFT transactions */ function changeFee( uint120 _depositFee, uint120 _withdrawFee, uint256 _nftFee ) public onlyOwner { if ( _depositFee != depositFee || _withdrawFee != withdrawFee || nftFee != _nftFee ) { require(_depositFee <= BASIS_POINTS, "RailgunLogic: Deposit Fee exceeds 100%"); require(_withdrawFee <= BASIS_POINTS, "RailgunLogic: Withdraw Fee exceeds 100%"); // Change fee depositFee = _depositFee; withdrawFee = _withdrawFee; nftFee = _nftFee; // Emit fee change event emit FeeChange(_depositFee, _withdrawFee, _nftFee); } } /** * @notice Get base and fee amount * @param _amount - Amount to calculate for * @param _isInclusive - Whether the amount passed in is inclusive of the fee * @param _feeBP - Fee basis points * @return base, fee */ function getFee(uint136 _amount, bool _isInclusive, uint120 _feeBP) public pure returns (uint120, uint120) { // Expand width of amount to uint136 to accomodate full size of (2**120-1)*BASIS_POINTS uint136 amountExpanded = _amount; // Base is the amount deposited into the railgun contract or withdrawn to the target eth address // for deposits and withdraws respectively uint136 base; // Fee is the amount sent to the treasury uint136 fee; if (_isInclusive) { base = amountExpanded - (amountExpanded * _feeBP) / BASIS_POINTS; fee = amountExpanded - base; } else { base = amountExpanded; fee = (BASIS_POINTS * base) / (BASIS_POINTS - _feeBP) - base; } return (uint120(base), uint120(fee)); } /** * @notice Gets token field value from tokenData * @param _tokenData - tokenData to calculate token field from * @return token field */ function getTokenField(TokenData memory _tokenData) public pure returns (uint256) { if (_tokenData.tokenType == TokenType.ERC20) { return uint256(uint160(_tokenData.tokenAddress)); } else if (_tokenData.tokenType == TokenType.ERC721) { revert("RailgunLogic: ERC721 not yet supported"); } else if (_tokenData.tokenType == TokenType.ERC1155) { revert("RailgunLogic: ERC1155 not yet supported"); } else { revert("RailgunLogic: Unknown token type"); } } /** * @notice Hashes a commitment * @param _commitmentPreimage - commitment to hash * @return commitment hash */ function hashCommitment(CommitmentPreimage memory _commitmentPreimage) public pure returns (uint256) { return PoseidonT4.poseidon([ _commitmentPreimage.npk, getTokenField(_commitmentPreimage.token), _commitmentPreimage.value ]); } /** * @notice Deposits requested amount and token, creates a commitment hash from supplied values and adds to tree * @param _notes - list of commitments to deposit */ function generateDeposit(CommitmentPreimage[] calldata _notes, uint256[2][] calldata _encryptedRandom) external { // Get notes length uint256 notesLength = _notes.length; // Insertion and event arrays uint256[] memory insertionLeaves = new uint256[](notesLength); CommitmentPreimage[] memory generatedCommitments = new CommitmentPreimage[](notesLength); require(_notes.length == _encryptedRandom.length, "RailgunLogic: notes and encrypted random length doesn't match"); for (uint256 notesIter = 0; notesIter < notesLength; notesIter++) { // Retrieve note CommitmentPreimage calldata note = _notes[notesIter]; // Check deposit amount is not 0 require(note.value > 0, "RailgunLogic: Cannot deposit 0 tokens"); // Check if token is on the blacklist require( !TokenBlacklist.tokenBlacklist[note.token.tokenAddress], "RailgunLogic: Token is blacklisted" ); // Check ypubkey is in snark scalar field require(note.npk < SNARK_SCALAR_FIELD, "RailgunLogic: npk out of range"); // Process deposit request if (note.token.tokenType == TokenType.ERC20) { // ERC20 // Get ERC20 interface IERC20 token = IERC20(address(uint160(note.token.tokenAddress))); // Get base and fee amounts (uint120 base, uint120 fee) = getFee(note.value, true, depositFee); // Add GeneratedCommitment to event array generatedCommitments[notesIter] = CommitmentPreimage({ npk: note.npk, value: base, token: note.token }); // Calculate commitment hash uint256 hash = hashCommitment(generatedCommitments[notesIter]); // Add to insertion array insertionLeaves[notesIter] = hash; // Transfer base to output address token.safeTransferFrom( address(msg.sender), address(this), base ); // Transfer fee to treasury token.safeTransferFrom( address(msg.sender), treasury, fee ); } else if (note.token.tokenType == TokenType.ERC721) { // ERC721 token revert("RailgunLogic: ERC721 not yet supported"); } else if (note.token.tokenType == TokenType.ERC1155) { // ERC1155 token revert("RailgunLogic: ERC1155 not yet supported"); } else { // Invalid token type, revert revert("RailgunLogic: Unknown token type"); } } // Emit GeneratedCommitmentAdded events (for wallets) for the commitments emit GeneratedCommitmentBatch(Commitments.treeNumber, Commitments.nextLeafIndex, generatedCommitments, _encryptedRandom); // Push new commitments to merkle tree Commitments.insertLeaves(insertionLeaves); } /** * @notice Safety check for badly behaving code */ function checkSafetyVectors() external { // Set safety bit StorageSlot.getBooleanSlot(0x8dea8703c3cf94703383ce38a9c894669dccd4ca8e65ddb43267aa0248711450).value = true; // Setup behaviour check bool result = false; // Execute behaviour check // solhint-disable-next-line no-inline-assembly assembly { mstore(0, caller()) mstore(32, snarkSafetyVector.slot) let hash := keccak256(0, 64) result := sload(hash) } require(result, "RailgunLogic: Unsafe vectors"); } /** * @notice Adds safety vector */ function addVector(uint256 vector) external onlyOwner { snarkSafetyVector[vector] = true; } /** * @notice Removes safety vector */ function removeVector(uint256 vector) external onlyOwner { snarkSafetyVector[vector] = false; } /** * @notice Execute batch of Railgun snark transactions * @param _transactions - Transactions to execute */ function transact( Transaction[] calldata _transactions ) external { // Accumulate total number of insertion commitments uint256 insertionCommitmentCount = 0; // Loop through each transaction uint256 transactionLength = _transactions.length; for(uint256 transactionIter = 0; transactionIter < transactionLength; transactionIter++) { // Retrieve transaction Transaction calldata transaction = _transactions[transactionIter]; // If adaptContract is not zero check that it matches the caller require( transaction.boundParams.adaptContract == address (0) || transaction.boundParams.adaptContract == msg.sender, "AdaptID doesn't match caller contract" ); // Retrieve treeNumber uint256 treeNumber = transaction.boundParams.treeNumber; // Check merkle root is valid require(Commitments.rootHistory[treeNumber][transaction.merkleRoot], "RailgunLogic: Invalid Merkle Root"); // Loop through each nullifier uint256 nullifiersLength = transaction.nullifiers.length; for (uint256 nullifierIter = 0; nullifierIter < nullifiersLength; nullifierIter++) { // Retrieve nullifier uint256 nullifier = transaction.nullifiers[nullifierIter]; // Check if nullifier has been seen before require(!Commitments.nullifiers[treeNumber][nullifier], "RailgunLogic: Nullifier already seen"); // Push to nullifiers Commitments.nullifiers[treeNumber][nullifier] = true; } // Emit nullifiers event emit Nullifiers(treeNumber, transaction.nullifiers); // Verify proof require( Verifier.verify(transaction), "RailgunLogic: Invalid SNARK proof" ); if (transaction.boundParams.withdraw != WithdrawType.NONE) { // Last output is marked as withdraw, process // Hash the withdraw commitment preimage uint256 commitmentHash = hashCommitment(transaction.withdrawPreimage); // Make sure the commitment hash matches the withdraw transaction output require( commitmentHash == transaction.commitments[transaction.commitments.length - 1], "RailgunLogic: Withdraw commitment preimage is invalid" ); // Fetch output address address output = address(uint160(transaction.withdrawPreimage.npk)); // Check if we've been asked to override the withdraw destination if(transaction.overrideOutput != address(0)) { // Withdraw must == 2 and msg.sender must be the original recepient to change the output destination require( msg.sender == output && transaction.boundParams.withdraw == WithdrawType.REDIRECT, "RailgunLogic: Can't override destination address" ); // Override output address output = transaction.overrideOutput; } // Process withdrawal request if (transaction.withdrawPreimage.token.tokenType == TokenType.ERC20) { // ERC20 // Get ERC20 interface IERC20 token = IERC20(address(uint160(transaction.withdrawPreimage.token.tokenAddress))); // Get base and fee amounts (uint120 base, uint120 fee) = getFee(transaction.withdrawPreimage.value, true, withdrawFee); // Transfer base to output address token.safeTransfer( output, base ); // Transfer fee to treasury token.safeTransfer( treasury, fee ); } else if (transaction.withdrawPreimage.token.tokenType == TokenType.ERC721) { // ERC721 token revert("RailgunLogic: ERC721 not yet supported"); } else if (transaction.withdrawPreimage.token.tokenType == TokenType.ERC1155) { // ERC1155 token revert("RailgunLogic: ERC1155 not yet supported"); } else { // Invalid token type, revert revert("RailgunLogic: Unknown token type"); } // Ensure ciphertext length matches the commitments length (minus 1 for withdrawn output) require( transaction.boundParams.commitmentCiphertext.length == transaction.commitments.length - 1, "RailgunLogic: Ciphertexts and commitments count mismatch" ); // Increment insertion commitment count (minus 1 for withdrawn output) insertionCommitmentCount += transaction.commitments.length - 1; } else { // Ensure ciphertext length matches the commitments length require( transaction.boundParams.commitmentCiphertext.length == transaction.commitments.length, "RailgunLogic: Ciphertexts and commitments count mismatch" ); // Increment insertion commitment count insertionCommitmentCount += transaction.commitments.length; } } // Create insertion array uint256[] memory hashes = new uint256[](insertionCommitmentCount); // Create ciphertext array CommitmentCiphertext[] memory ciphertext = new CommitmentCiphertext[](insertionCommitmentCount); // Track insert position uint256 insertPosition = 0; // Loop through each transaction and accumulate commitments for(uint256 transactionIter = 0; transactionIter < _transactions.length; transactionIter++) { // Retrieve transaction Transaction calldata transaction = _transactions[transactionIter]; // Loop through commitments and push to array uint256 commitmentLength = transaction.boundParams.commitmentCiphertext.length; for(uint256 commitmentIter = 0; commitmentIter < commitmentLength; commitmentIter++) { // Push commitment hash to array hashes[insertPosition] = transaction.commitments[commitmentIter]; // Push ciphertext to array ciphertext[insertPosition] = transaction.boundParams.commitmentCiphertext[commitmentIter]; // Increment insert position insertPosition++; } } // Emit commitment state update emit CommitmentBatch(Commitments.treeNumber, Commitments.nextLeafIndex, hashes, ciphertext); // Push new commitments to merkle tree after event due to insertLeaves causing side effects Commitments.insertLeaves(hashes); } } // SPDX-License-Identifier: MIT // 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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; pragma abicoder v2; // Constants uint256 constant SNARK_SCALAR_FIELD = 21888242871839275222246405745257275088548364400416034343698204186575808495617; uint256 constant CIPHERTEXT_WORDS = 4; enum TokenType { ERC20, ERC721, ERC1155 } // Transaction token data struct TokenData { TokenType tokenType; address tokenAddress; uint256 tokenSubID; } // Commitment ciphertext struct CommitmentCiphertext { uint256[CIPHERTEXT_WORDS] ciphertext; // Ciphertext order: iv & tag (16 bytes each), recipient master public key (packedPoint) (uint256), packedField (uint256) {sign, random, amount}, token (uint256) uint256[2] ephemeralKeys; // Sender first, receipient second (packed points 32 bytes each) uint256[] memo; } enum WithdrawType { NONE, WITHDRAW, REDIRECT } // Transaction bound parameters struct BoundParams { uint16 treeNumber; WithdrawType withdraw; address adaptContract; bytes32 adaptParams; // For withdraws do not include an element in ciphertext array // Ciphertext array length = commitments - withdraws CommitmentCiphertext[] commitmentCiphertext; } // Transaction struct struct Transaction { SnarkProof proof; uint256 merkleRoot; uint256[] nullifiers; uint256[] commitments; BoundParams boundParams; CommitmentPreimage withdrawPreimage; address overrideOutput; // Only allowed if original destination == msg.sender & boundParams.withdraw == 2 } // Commitment hash preimage struct CommitmentPreimage { uint256 npk; // Poseidon(mpk, random), mpk = Poseidon(spending public key, nullifier) TokenData token; // Token field uint120 value; // Note value } struct G1Point { uint256 x; uint256 y; } // Encoding of field elements is: X[0] * z + X[1] struct G2Point { uint256[2] x; uint256[2] y; } // Verification key for SNARK struct VerifyingKey { string artifactsIPFSHash; G1Point alpha1; G2Point beta2; G2Point gamma2; G2Point delta2; G1Point[] ic; } // Snark proof for transaction struct SnarkProof { G1Point a; G2Point b; G1Point c; } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; pragma abicoder v2; // OpenZeppelin v4 import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import { SnarkProof, Transaction, BoundParams, VerifyingKey, SNARK_SCALAR_FIELD } from "./Globals.sol"; import { Snark } from "./Snark.sol"; /** * @title Verifier * @author Railgun Contributors * @notice Verifies snark proof * @dev Functions in this contract statelessly verify proofs, nullifiers and adaptID should be checked in RailgunLogic. */ contract Verifier is OwnableUpgradeable { // NOTE: The order of instantiation MUST stay the same across upgrades // add new variables to the bottom of the list and decrement __gap // See https://docs.openzeppelin.com/learn/upgrading-smart-contracts#upgrading // Snark bypass address, can't be address(0) as many burn prevention mechanisms will disallow transfers to 0 // Use 0x000000000000000000000000000000000000dEaD as an alternative address constant public SNARK_BYPASS = 0x000000000000000000000000000000000000dEaD; // Verifying key set event event VerifyingKeySet(uint256 nullifiers, uint256 commitments, VerifyingKey verifyingKey); // Nullifiers => Commitments => Verification Key mapping(uint256 => mapping(uint256 => VerifyingKey)) private verificationKeys; /** * @notice Sets verification key * @param _nullifiers - number of nullifiers this verification key is for * @param _commitments - number of commitmets out this verification key is for * @param _verifyingKey - verifyingKey to set */ function setVerificationKey( uint256 _nullifiers, uint256 _commitments, VerifyingKey calldata _verifyingKey ) public onlyOwner { verificationKeys[_nullifiers][_commitments] = _verifyingKey; emit VerifyingKeySet(_nullifiers, _commitments, _verifyingKey); } /** * @notice Gets verification key * @param _nullifiers - number of nullifiers this verification key is for * @param _commitments - number of commitmets out this verification key is for */ function getVerificationKey( uint256 _nullifiers, uint256 _commitments ) public view returns (VerifyingKey memory) { // Manually add getter so dynamic IC array is included in response return verificationKeys[_nullifiers][_commitments]; } /** * @notice Calculates hash of transaction bound params for snark verification * @param _boundParams - bound parameters * @return bound parameters hash */ function hashBoundParams(BoundParams calldata _boundParams) public pure returns (uint256) { return uint256(keccak256(abi.encode( _boundParams ))) % SNARK_SCALAR_FIELD; } /** * @notice Verifies inputs against a verification key * @param _verifyingKey - verifying key to verify with * @param _proof - proof to verify * @param _inputs - input to verify * @return proof validity */ function verifyProof( VerifyingKey memory _verifyingKey, SnarkProof calldata _proof, uint256[] memory _inputs ) public view returns (bool) { return Snark.verify( _verifyingKey, _proof, _inputs ); } /** * @notice Verifies a transaction * @param _transaction to verify * @return transaction validity */ function verify(Transaction calldata _transaction) public view returns (bool) { uint256 nullifiersLength = _transaction.nullifiers.length; uint256 commitmentsLength = _transaction.commitments.length; // Retrieve verification key VerifyingKey memory verifyingKey = verificationKeys [nullifiersLength] [commitmentsLength]; // Check if verifying key is set require(verifyingKey.alpha1.x != 0, "Verifier: Key not set"); // Calculate inputs uint256[] memory inputs = new uint256[](2 + nullifiersLength + commitmentsLength); inputs[0] = _transaction.merkleRoot; // Hash bound parameters inputs[1] = hashBoundParams(_transaction.boundParams); // Loop through nullifiers and add to inputs for (uint i = 0; i < nullifiersLength; i++) { inputs[2 + i] = _transaction.nullifiers[i]; } // Loop through commitments and add to inputs for (uint i = 0; i < commitmentsLength; i++) { inputs[2 + nullifiersLength + i] = _transaction.commitments[i]; } // Verify snark proof bool validity = verifyProof( verifyingKey, _transaction.proof, inputs ); // Always return true in gas estimation transaction // This is so relayer fees can be calculated without needing to compute a proof // solhint-disable-next-line avoid-tx-origin if (tx.origin == SNARK_BYPASS) { return true; } else { return validity; } } uint256[49] private __gap; } // SPDX-License-Identifier: UNLICENSED // Based on code from MACI (https://github.com/appliedzkp/maci/blob/7f36a915244a6e8f98bacfe255f8bd44193e7919/contracts/sol/IncrementalMerkleTree.sol) pragma solidity ^0.8.0; pragma abicoder v2; // OpenZeppelin v4 import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import { SNARK_SCALAR_FIELD } from "./Globals.sol"; import { PoseidonT3 } from "./Poseidon.sol"; /** * @title Commitments * @author Railgun Contributors * @notice Batch Incremental Merkle Tree for commitments * @dev Publically accessible functions to be put in RailgunLogic * Relevent external contract calls should be in those functions, not here */ contract Commitments is Initializable { // NOTE: The order of instantiation MUST stay the same across upgrades // add new variables to the bottom of the list and decrement the __gap // variable at the end of this file // See https://docs.openzeppelin.com/learn/upgrading-smart-contracts#upgrading // Commitment nullifiers (treenumber -> nullifier -> seen) mapping(uint256 => mapping(uint256 => bool)) public nullifiers; // The tree depth uint256 internal constant TREE_DEPTH = 16; // Tree zero value uint256 public constant ZERO_VALUE = uint256(keccak256("Railgun")) % SNARK_SCALAR_FIELD; // Next leaf index (number of inserted leaves in the current tree) uint256 internal nextLeafIndex; // The Merkle root uint256 public merkleRoot; // Store new tree root to quickly migrate to a new tree uint256 private newTreeRoot; // Tree number uint256 public treeNumber; // The Merkle path to the leftmost leaf upon initialisation. It *should // not* be modified after it has been set by the initialize function. // Caching these values is essential to efficient appends. uint256[TREE_DEPTH] public zeros; // Right-most elements at each level // Used for efficient upodates of the merkle tree uint256[TREE_DEPTH] private filledSubTrees; // Whether the contract has already seen a particular Merkle tree root // treeNumber -> root -> seen mapping(uint256 => mapping(uint256 => bool)) public rootHistory; /** * @notice Calculates initial values for Merkle Tree * @dev OpenZeppelin initializer ensures this can only be called once */ function initializeCommitments() internal onlyInitializing { /* To initialise the Merkle tree, we need to calculate the Merkle root assuming that each leaf is the zero value. H(H(a,b), H(c,d)) / \ H(a,b) H(c,d) / \ / \ a b c d `zeros` and `filledSubTrees` will come in handy later when we do inserts or updates. e.g when we insert a value in index 1, we will need to look up values from those arrays to recalculate the Merkle root. */ // Calculate zero values zeros[0] = ZERO_VALUE; // Store the current zero value for the level we just calculated it for uint256 currentZero = ZERO_VALUE; // Loop through each level for (uint256 i = 0; i < TREE_DEPTH; i++) { // Push it to zeros array zeros[i] = currentZero; // Calculate the zero value for this level currentZero = hashLeftRight(currentZero, currentZero); } // Set merkle root and store root to quickly retrieve later newTreeRoot = merkleRoot = currentZero; rootHistory[treeNumber][currentZero] = true; } /** * @notice Hash 2 uint256 values * @param _left - Left side of hash * @param _right - Right side of hash * @return hash result */ function hashLeftRight(uint256 _left, uint256 _right) public pure returns (uint256) { return PoseidonT3.poseidon([ _left, _right ]); } /** * @notice Calculates initial values for Merkle Tree * @dev Insert leaves into the current merkle tree * Note: this function INTENTIONALLY causes side effects to save on gas. * _leafHashes and _count should never be reused. * @param _leafHashes - array of leaf hashes to be added to the merkle tree */ function insertLeaves(uint256[] memory _leafHashes) internal { /* Loop through leafHashes at each level, if the leaf is on the left (index is even) then hash with zeros value and update subtree on this level, if the leaf is on the right (index is odd) then hash with subtree value. After calculating each hash push to relevent spot on leafHashes array. For gas efficiency we reuse the same array and use the count variable to loop to the right index each time. Example of updating a tree of depth 4 with elements 13, 14, and 15 [1,7,15] {1} 1 | [3,7,15] {1} 2-------------------3 | | [6,7,15] {2} 4---------5 6---------7 / \ / \ / \ / \ [13,14,15] {3} 08 09 10 11 12 13 14 15 [] = leafHashes array {} = count variable */ // Get initial count uint256 count = _leafHashes.length; // Create new tree if current one can't contain new leaves // We insert all new commitment into a new tree to ensure they can be spent in the same transaction if ((nextLeafIndex + count) >= (2 ** TREE_DEPTH)) { newTree(); } // Current index is the index at each level to insert the hash uint256 levelInsertionIndex = nextLeafIndex; // Update nextLeafIndex nextLeafIndex += count; // Variables for starting point at next tree level uint256 nextLevelHashIndex; uint256 nextLevelStartIndex; // Loop through each level of the merkle tree and update for (uint256 level = 0; level < TREE_DEPTH; level++) { // Calculate the index to start at for the next level // >> is equivilent to / 2 rounded down nextLevelStartIndex = levelInsertionIndex >> 1; uint256 insertionElement = 0; // If we're on the right, hash and increment to get on the left if (levelInsertionIndex % 2 == 1) { // Calculate index to insert hash into leafHashes[] // >> is equivilent to / 2 rounded down nextLevelHashIndex = (levelInsertionIndex >> 1) - nextLevelStartIndex; // Calculate the hash for the next level _leafHashes[nextLevelHashIndex] = hashLeftRight(filledSubTrees[level], _leafHashes[insertionElement]); // Increment insertionElement += 1; levelInsertionIndex += 1; } // We'll always be on the left side now for (insertionElement; insertionElement < count; insertionElement += 2) { uint256 right; // Calculate right value if (insertionElement < count - 1) { right = _leafHashes[insertionElement + 1]; } else { right = zeros[level]; } // If we've created a new subtree at this level, update if (insertionElement == count - 1 || insertionElement == count - 2) { filledSubTrees[level] = _leafHashes[insertionElement]; } // Calculate index to insert hash into leafHashes[] // >> is equivilent to / 2 rounded down nextLevelHashIndex = (levelInsertionIndex >> 1) - nextLevelStartIndex; // Calculate the hash for the next level _leafHashes[nextLevelHashIndex] = hashLeftRight(_leafHashes[insertionElement], right); // Increment level insertion index levelInsertionIndex += 2; } // Get starting levelInsertionIndex value for next level levelInsertionIndex = nextLevelStartIndex; // Get count of elements for next level count = nextLevelHashIndex + 1; } // Update the Merkle tree root merkleRoot = _leafHashes[0]; rootHistory[treeNumber][merkleRoot] = true; } /** * @notice Creates new merkle tree */ function newTree() private { // Restore merkleRoot to newTreeRoot merkleRoot = newTreeRoot; // Existing values in filledSubtrees will never be used so overwriting them is unnecessary // Reset next leaf index to 0 nextLeafIndex = 0; // Increment tree number treeNumber++; } uint256[10] private __gap; } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; pragma abicoder v2; // OpenZeppelin v4 import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; /** * @title Token Blacklist * @author Railgun Contributors * @notice Blacklist of tokens that are incompatible with the protocol * @dev Tokens on this blacklist can't be deposited to railgun. * Tokens on this blacklist will still be transferrable * internally (as internal transactions have a shielded token ID) and * withdrawable (to prevent user funds from being locked) * THIS WILL ALWAYS BE A NON-EXHAUSTIVE LIST, DO NOT RELY ON IT BLOCKING ALL * INCOMPATIBLE TOKENS */ contract TokenBlacklist is OwnableUpgradeable { // Events for offchain building of blacklist index event AddToBlacklist(address indexed token); event RemoveFromBlacklist(address indexed token); // NOTE: The order of instantiation MUST stay the same across upgrades // add new variables to the bottom of the list and decrement the __gap // variable at the end of this file // See https://docs.openzeppelin.com/learn/upgrading-smart-contracts#upgrading mapping(address => bool) public tokenBlacklist; /** * @notice Adds tokens to blacklist, only callable by owner (governance contract) * @dev This function will ignore tokens that are already in the blacklist * no events will be emitted in this case * @param _tokens - List of tokens to add to blacklist */ function addToBlacklist(address[] calldata _tokens) external onlyOwner { // Loop through token array for (uint256 i = 0; i < _tokens.length; i++) { // Don't do anything if the token is already blacklisted if (!tokenBlacklist[_tokens[i]]) { // Set token address in blacklist map to true tokenBlacklist[_tokens[i]] = true; // Emit event for building index of blacklisted tokens offchain emit AddToBlacklist(_tokens[i]); } } } /** * @notice Removes token from blacklist, only callable by owner (governance contract) * @dev This function will ignore tokens that aren't in the blacklist * no events will be emitted in this case * @param _tokens - List of tokens to remove from blacklist */ function removeFromBlacklist(address[] calldata _tokens) external onlyOwner { // Loop through token array for (uint256 i = 0; i < _tokens.length; i++) { // Don't do anything if the token isn't blacklisted if (tokenBlacklist[_tokens[i]]) { // Set token address in blacklisted map to false (default value) delete tokenBlacklist[_tokens[i]]; // Emit event for building index of blacklisted tokens offchain emit RemoveFromBlacklist(_tokens[i]); } } } uint256[49] private __gap; } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; pragma abicoder v2; /* Functions here are stubs for the solidity compiler to generate the right interface. The deployed library is generated bytecode from the circomlib toolchain */ library PoseidonT3 { // solhint-disable-next-line no-empty-blocks function poseidon(uint256[2] memory input) public pure returns (uint256) {} } library PoseidonT4 { // solhint-disable-next-line no-empty-blocks function poseidon(uint256[3] memory input) public pure returns (uint256) {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; pragma abicoder v2; import { G1Point, G2Point, VerifyingKey, SnarkProof, SNARK_SCALAR_FIELD } from "./Globals.sol"; library Snark { uint256 private constant PRIME_Q = 21888242871839275222246405745257275088696311157297823662689037894645226208583; uint256 private constant PAIRING_INPUT_SIZE = 24; uint256 private constant PAIRING_INPUT_WIDTH = 768; // PAIRING_INPUT_SIZE * 32 /** * @notice Computes the negation of point p * @dev The negation of p, i.e. p.plus(p.negate()) should be zero. * @return result */ function negate(G1Point memory p) internal pure returns (G1Point memory) { if (p.x == 0 && p.y == 0) return G1Point(0, 0); // check for valid points y^2 = x^3 +3 % PRIME_Q uint256 rh = mulmod(p.x, p.x, PRIME_Q); //x^2 rh = mulmod(rh, p.x, PRIME_Q); //x^3 rh = addmod(rh, 3, PRIME_Q); //x^3 + 3 uint256 lh = mulmod(p.y, p.y, PRIME_Q); //y^2 require(lh == rh, "Snark: Invalid negation"); return G1Point(p.x, PRIME_Q - (p.y % PRIME_Q)); } /** * @notice Adds 2 G1 points * @return result */ function add(G1Point memory p1, G1Point memory p2) internal view returns (G1Point memory) { // Format inputs uint256[4] memory input; input[0] = p1.x; input[1] = p1.y; input[2] = p2.x; input[3] = p2.y; // Setup output variables bool success; G1Point memory result; // Add points // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(sub(gas(), 2000), 6, input, 0x80, result, 0x40) } // Check if operation succeeded require(success, "Snark: Add Failed"); return result; } /** * @notice Scalar multiplies two G1 points p, s * @dev The product of a point on G1 and a scalar, i.e. * p == p.scalar_mul(1) and p.plus(p) == p.scalar_mul(2) for all * points p. * @return r - result */ function scalarMul(G1Point memory p, uint256 s) internal view returns (G1Point memory r) { uint256[3] memory input; input[0] = p.x; input[1] = p.y; input[2] = s; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(sub(gas(), 2000), 7, input, 0x60, r, 0x40) } // Check multiplication succeeded require(success, "Snark: Scalar Multiplication Failed"); } /** * @notice Performs pairing check on points * @dev The result of computing the pairing check * e(p1[0], p2[0]) * .... * e(p1[n], p2[n]) == 1 * For example, * pairing([P1(), P1().negate()], [P2(), P2()]) should return true. * @return if pairing check passed */ function pairing( G1Point memory _a1, G2Point memory _a2, G1Point memory _b1, G2Point memory _b2, G1Point memory _c1, G2Point memory _c2, G1Point memory _d1, G2Point memory _d2 ) internal view returns (bool) { uint256[PAIRING_INPUT_SIZE] memory input = [ _a1.x, _a1.y, _a2.x[0], _a2.x[1], _a2.y[0], _a2.y[1], _b1.x, _b1.y, _b2.x[0], _b2.x[1], _b2.y[0], _b2.y[1], _c1.x, _c1.y, _c2.x[0], _c2.x[1], _c2.y[0], _c2.y[1], _d1.x, _d1.y, _d2.x[0], _d2.x[1], _d2.y[0], _d2.y[1] ]; uint256[1] memory out; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall( sub(gas(), 2000), 8, input, PAIRING_INPUT_WIDTH, out, 0x20 ) } // Check if operation succeeded require(success, "Snark: Pairing Verification Failed"); return out[0] != 0; } /** * @notice Verifies snark proof against proving key * @param _vk - Verification Key * @param _proof - snark proof * @param _inputs - inputs */ function verify( VerifyingKey memory _vk, SnarkProof memory _proof, uint256[] memory _inputs ) internal view returns (bool) { // Compute the linear combination vkX G1Point memory vkX = G1Point(0, 0); // Loop through every input for (uint i = 0; i < _inputs.length; i++) { // Make sure inputs are less than SNARK_SCALAR_FIELD require(_inputs[i] < SNARK_SCALAR_FIELD, "Snark: Input > SNARK_SCALAR_FIELD"); // Add to vkX point vkX = add(vkX, scalarMul(_vk.ic[i + 1], _inputs[i])); } // Compute final vkX point vkX = add(vkX, _vk.ic[0]); // Verify pairing and return return pairing( negate(_proof.a), _proof.b, _vk.alpha1, _vk.beta2, vkX, _vk.gamma2, _proof.c, _vk.delta2 ); } }
Adds 2 G1 points return result/ Format inputs Setup output variables Add points solhint-disable-next-line no-inline-assembly
function add(G1Point memory p1, G1Point memory p2) internal view returns (G1Point memory) { uint256[4] memory input; input[0] = p1.x; input[1] = p1.y; input[2] = p2.x; input[3] = p2.y; bool success; G1Point memory result; assembly { success := staticcall(sub(gas(), 2000), 6, input, 0x80, result, 0x40) } return result; }
5,809,640
// SPDX-License-Identifier: GPL-3.0-or-later Or MIT /** *Submitted for verification at BscScan.com on 2021-05-28 */ pragma solidity ^0.6.0; 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) { // 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; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } 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; } } interface IBEP20 { /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @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 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 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 from, address to, uint256 value ) external returns (bool ok); } contract SATOSHIPrivateSale { using SafeMath for uint256; IBEP20 public SATOSHI; address payable public owner; uint256 public startDate = 1633651200; // 2021/10/08 00:00:00 UTC uint256 public endDate = 1635551999; // 2021/10/29 23:59:59 UTC uint256 public totalTokensToSell = 30000000 * 10**18; // 30000000 SATOSHI tokens for sell uint256 public satoshiPerBnb = 10000 * 10**18; // 1 BNB = 10000 SATOSHI uint256 public minPerTransaction = 2500 * 10**18; // min amount per transaction (0.25BNB) uint256 public maxPerUser = 100000 * 10**18; // max amount per user (10BNB) uint256 public totalSold; bool public saleEnded; mapping(address => uint256) public satoshiPerAddresses; event tokensBought(address indexed user, uint256 amountSpent, uint256 amountBought, string tokenName, uint256 date); event tokensClaimed(address indexed user, uint256 amount, uint256 date); modifier checkSaleRequirements(uint256 buyAmount) { require(now >= startDate && now < endDate, 'Presale time passed'); require(saleEnded == false, 'Sale ended'); require( buyAmount > 0 && buyAmount <= unsoldTokens(), 'Insufficient buy amount' ); _; } constructor( address _SATOSHI ) public { owner = msg.sender; SATOSHI = IBEP20(_SATOSHI); } // Function to buy SATOSHI using BNB token function buyWithBNB(uint256 buyAmount) public payable checkSaleRequirements(buyAmount) { uint256 amount = calculateBNBAmount(buyAmount); require(msg.value >= amount, 'Insufficient BNB balance'); require(buyAmount >= minPerTransaction, 'Lower than the minimal transaction amount'); uint256 sumSoFar = satoshiPerAddresses[msg.sender].add(buyAmount); require(sumSoFar <= maxPerUser, 'Greater than the maximum purchase limit'); satoshiPerAddresses[msg.sender] = sumSoFar; totalSold = totalSold.add(buyAmount); SATOSHI.transfer(msg.sender, buyAmount); emit tokensBought(msg.sender, amount, buyAmount, 'BNB', now); } //function to change the owner //only owner can call this function function changeOwner(address payable _owner) public { require(msg.sender == owner); owner = _owner; } // function to set the presale start date // only owner can call this function function setStartDate(uint256 _startDate) public { require(msg.sender == owner && saleEnded == false); startDate = _startDate; } // function to set the presale end date // only owner can call this function function setEndDate(uint256 _endDate) public { require(msg.sender == owner && saleEnded == false); endDate = _endDate; } // function to set the total tokens to sell // only owner can call this function function setTotalTokensToSell(uint256 _totalTokensToSell) public { require(msg.sender == owner); totalTokensToSell = _totalTokensToSell; } // function to set the minimal transaction amount // only owner can call this function function setMinPerTransaction(uint256 _minPerTransaction) public { require(msg.sender == owner); minPerTransaction = _minPerTransaction; } // function to set the maximum amount which a user can buy // only owner can call this function function setMaxPerUser(uint256 _maxPerUser) public { require(msg.sender == owner); maxPerUser = _maxPerUser; } // function to set the total tokens to sell // only owner can call this function function setTokenPricePerBNB(uint256 _satoshiPerBnb) public { require(msg.sender == owner); require(_satoshiPerBnb > 0, "Invalid SATOSHI price per BNB"); satoshiPerBnb = _satoshiPerBnb; } //function to end the sale //only owner can call this function function endSale() public { require(msg.sender == owner && saleEnded == false); saleEnded = true; } //function to withdraw collected tokens by sale. //only owner can call this function function withdrawCollectedTokens() public { require(msg.sender == owner); require(address(this).balance > 0, "Insufficient balance"); owner.transfer(address(this).balance); } //function to withdraw unsold tokens //only owner can call this function function withdrawUnsoldTokens() public { require(msg.sender == owner); uint256 remainedTokens = unsoldTokens(); require(remainedTokens > 0, "No remained tokens"); SATOSHI.transfer(owner, remainedTokens); } //function to return the amount of unsold tokens function unsoldTokens() public view returns (uint256) { // return totalTokensToSell.sub(totalSold); return SATOSHI.balanceOf(address(this)); } //function to calculate the quantity of SATOSHI token based on the SATOSHI price of bnbAmount function calculateSATOSHIAmount(uint256 bnbAmount) public view returns (uint256) { uint256 satoshiAmount = satoshiPerBnb.mul(bnbAmount).div(10**18); return satoshiAmount; } //function to calculate the quantity of bnb needed using its SATOSHI price to buy `buyAmount` of SATOSHI tokens. function calculateBNBAmount(uint256 satoshiAmount) public view returns (uint256) { require(satoshiPerBnb > 0, "SATOSHI price per BNB should be greater than 0"); uint256 bnbAmount = satoshiAmount.mul(10**18).div(satoshiPerBnb); return bnbAmount; } }
function to set the total tokens to sell only owner can call this function
function setTotalTokensToSell(uint256 _totalTokensToSell) public { require(msg.sender == owner); totalTokensToSell = _totalTokensToSell; }
6,429,563
./full_match/5/0x5256308608B6865F486b59136e7826ACF648a2a1/sources/lib/dynamic-contracts/src/presets/ExtensionManager.sol
Fully replace an existing extension of the router. The extension with name `extension.name` is the extension being replaced. _extension The extension to replace or overwrite./
function replaceExtension(Extension memory _extension) public virtual onlyAuthorizedCall { _replaceExtension(_extension); }
1,960,816
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; import "./storage/EternalStorage.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Context, EternalStorage { string internal _owner_ = "bsf_own_owner"; string internal _new_owner_ = "bsf_own_new_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() external view virtual returns (address) { return _owner(); } function _owner() internal view virtual returns (address){ return addressStorage[keccak256(abi.encode(_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() external virtual onlyOwner { _setOwner(address(0)); } function _setOwner(address _no) internal { address oldOwner = addressStorage[keccak256(abi.encode(_owner_))]; addressStorage[keccak256(abi.encode(_new_owner_))] = _no; emit OwnershipTransferred(oldOwner, _no); } function newOwner() external view returns (address) { return _newOwner(); } function _newOwner() internal view returns (address){ return addressStorage[keccak256(abi.encode(_new_owner_))]; } /** * @dev Modifier throws if called by any account other than the newOwner. */ modifier onlyNewOwner() { require(msg.sender == _newOwner()); _; } /** * @dev Allows the current owner to set the newOwner address. * @param _no The address to transfer ownership to. */ function transferOwnership(address _no) external onlyOwner { require(_no != address(0), "Ownable: new owner is the zero address"); _setOwner(_no); } /** * @dev Allows the newOwner address to finalize the transfer. */ function claimOwnership() external onlyNewOwner { emit OwnershipTransferred(_owner(), _newOwner()); addressStorage[keccak256(abi.encode(_owner_))] = addressStorage[keccak256(abi.encode(_new_owner_))]; addressStorage[keccak256(abi.encode(_new_owner_))] = address(0); } }
Allows the newOwner address to finalize the transfer./
function claimOwnership() external onlyNewOwner { emit OwnershipTransferred(_owner(), _newOwner()); addressStorage[keccak256(abi.encode(_owner_))] = addressStorage[keccak256(abi.encode(_new_owner_))]; addressStorage[keccak256(abi.encode(_new_owner_))] = address(0); }
12,865,122
pragma solidity ^0.5.0; import "../interfaces/IAaveLendingPool.sol"; import "./MockERC20.sol"; // import '@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol'; import "@nomiclabs/buidler/console.sol"; contract AaveLendingPool is IAaveLendingPool { using SafeMath for uint256; MockERC20 public aDai; MockERC20 public dai; constructor(MockERC20 aDaiAddress, MockERC20 daiAddress) public { aDai = aDaiAddress; dai = daiAddress; } function deposit( address _reserve, uint256 _amount, uint16 _referralCode ) public { //console.log(' **** deposit into Aave lendingPool by *****', msg.sender); dai.burnFrom(msg.sender, _amount); //console.log('This amount of dai is being deposited ', _amount); uint256 amount = _amount.mul(2); // console.log( // 'sending this amount of aDAi is being sent back in return:', // amount // ); aDai.mint(msg.sender, amount); //console.log(' **** Aave deposit finished successfully *****'); } }
console.log(' deposit into Aave lendingPool by ', msg.sender);console.log('This amount of dai is being deposited ', _amount); console.log( 'sending this amount of aDAi is being sent back in return:', amount );console.log(' Aave deposit finished successfully ');
function deposit( address _reserve, uint256 _amount, uint16 _referralCode ) public { dai.burnFrom(msg.sender, _amount); uint256 amount = _amount.mul(2); aDai.mint(msg.sender, amount); }
14,116,934
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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/math/Math.sol pragma solidity >=0.6.0 <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, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // 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/Initializable.sol // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !Address.isContract(address(this)); } } // File: contracts/governance/Governable.sol pragma solidity ^0.6.0; /// @title Governable /// @dev Governable is contract for governance role. Why don't use an AccessControl? Because the only one member exists contract Governable { /// @notice The government address getter address public governance; /// @notice Simple contstructor that initialize the governance address constructor() public { governance = msg.sender; } /// @dev Prevents other msg.sender than governance address modifier onlyGovernance { require(msg.sender == governance, "!governance"); _; } /// @notice Setter for governance address /// @param _newGovernance New value function setGovernance(address _newGovernance) public onlyGovernance { governance = _newGovernance; } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/governance/LPTokenWrapper.sol pragma solidity ^0.6.0; /// @title LPTokenWrapper /// @notice Used as utility to simplify governance token operations in Governance contract contract LPTokenWrapper { using SafeMath for uint256; using SafeERC20 for IERC20; /// @notice Wrapped governance token IERC20 public governanceToken; /// @notice Current balances mapping(address => uint256) private _balances; /// @notice Current total supply uint256 private _totalSupply; /// @notice Standard totalSupply method function totalSupply() public view returns(uint256) { return _totalSupply; } /// @notice Standard balanceOf method /// @param _account User address function balanceOf(address _account) public view returns(uint256) { return _balances[_account]; } /// @notice Standard deposit (stake) method /// @param _amount Amount governance tokens to stake (deposit) function stake(uint256 _amount) public virtual { _totalSupply = _totalSupply.add(_amount); _balances[msg.sender] = _balances[msg.sender].add(_amount); governanceToken.safeTransferFrom(msg.sender, address(this), _amount); } /// @notice Standard withdraw method /// @param _amount Amount governance tokens to withdraw function withdraw(uint256 _amount) public virtual { _totalSupply = _totalSupply.sub(_amount); _balances[msg.sender] = _balances[msg.sender].sub(_amount); governanceToken.transfer(msg.sender, _amount); } /// @notice Simple governance setter /// @param _newGovernanceToken New value function _setGovernanceToken(address _newGovernanceToken) internal { governanceToken = IERC20(_newGovernanceToken); } } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/interfaces/IRewardDistributionRecipient.sol pragma solidity ^0.6.0; abstract contract IRewardDistributionRecipient is Ownable { address public rewardDistribution; function notifyRewardAmount(uint256 reward) external virtual; modifier onlyRewardDistribution { require(msg.sender == rewardDistribution, "!rewardDistribution"); _; } function setRewardDistribution(address _rewardDistribution) public onlyOwner { rewardDistribution = _rewardDistribution; } } // File: contracts/interfaces/IExecutor.sol pragma solidity ^0.6.0; interface IExecutor { function execute(uint256 _id, uint256 _for, uint256 _against, uint256 _quorum) external; } // File: contracts/governance/Governance.sol pragma solidity ^0.6.0; /// @title Governance /// @notice /// @dev contract Governance is Governable, IRewardDistributionRecipient, LPTokenWrapper, Initializable { /// @notice The Proposal struct used to represent vote process. struct Proposal { uint256 id; // Unique ID of the proposal (here Counter lib can be used) address proposer; // An address who created the proposal mapping(address => uint256) forVotes; // Percentage (in base points) of governance token (votes) of 'for' side mapping(address => uint256) againstVotes; // Percentage (in base points) of governance token (votes) of 'against' side uint256 totalForVotes; // Total amount of governance token (votes) in side 'for' uint256 totalAgainstVotes; // Total amount of governance token (votes) in side 'against' uint256 start; // Block start uint256 end; // Start + period address executor; // Custom contract which can execute changes regarding to voting process end string hash; // An IPFS hash of the proposal document uint256 totalVotesAvailable; // Total amount votes that are not in voting process uint256 quorum; // Current quorum (in base points) uint256 quorumRequired; // Quorum to end the voting process bool open; // Proposal status } /// @notice Emits when new proposal is created /// @param _id ID of the proposal /// @param _creator Address of proposal creator /// @param _start Voting process start timestamp /// @param _duration Seconds during which the voting process occurs /// @param _executor Address of the the executor contract event NewProposal(uint256 _id, address _creator, uint256 _start, uint256 _duration, address _executor); /// @notice Emits when someone votes in proposal /// @param _id ID of the proposal /// @param _voter Voter address /// @param _vote 'For' or 'Against' vote type /// @param _weight Vote weight in percents (in base points) event Vote(uint256 indexed _id, address indexed _voter, bool _vote, uint256 _weight); /// @notice Emits when voting process finished /// @param _id ID of the proposal /// @param _for 'For' votes percentage in base points /// @param _against 'Against' votes percentage in base points /// @param _quorumReached Is quorum percents are above or equal to required quorum? (bool) event ProposalFinished(uint256 indexed _id, uint256 _for, uint256 _against, bool _quorumReached); /// @notice Emits when voter invoke registration method /// @param _voter Voter address /// @param _votes Governance tokens number to be placed as votes /// @param _totalVotes Total governance token placed as votes for all users event RegisterVoter(address _voter, uint256 _votes, uint256 _totalVotes); /// @notice Emits when voter invoke revoke method /// @param _voter Voter address /// @param _votes Governance tokens number to be removed as votes /// @param _totalVotes Total governance token removed as votes for all users event RevokeVoter(address _voter, uint256 _votes, uint256 _totalVotes); /// @notice Emits when reward for participation in voting processes is sent to governance contract /// @param _reward Amount of staking reward tokens event RewardAdded(uint256 _reward); /// @notice Emits when sum of governance token staked to governance contract /// @param _user User who stakes /// @param _amount Amount of governance token to stake event Staked(address indexed _user, uint256 _amount); /// @notice Emits when sum of governance token withdrawn from governance contract /// @param _user User who withdraw /// @param _amount Amount of governance token to withdraw event Withdrawn(address indexed _user, uint256 _amount); /// @notice Emits when reward for participation in voting processes is sent to user. /// @param _user Voter who receive rewards /// @param _reward Amount of staking reward tokens event RewardPaid(address indexed _user, uint256 _reward); /// @notice Period that your sake is locked to keep it for voting /// @dev voter => lock period mapping(address => uint256) public voteLock; /// @notice Exists to store proposals /// @dev id => proposal struct mapping(uint256 => Proposal) public proposals; /// @notice Amount of governance tokens staked as votes for each voter /// @dev voter => token amount mapping(address => uint256) public votes; /// @notice Exists to check if voter registered /// @dev user => is voter? mapping(address => bool) public voters; /// @notice Exists to keep history of rewards paid /// @dev voter => reward paid mapping(address => uint256) public userRewardPerTokenPaid; /// @notice Exists to track amounts of reward to be paid /// @dev voter => reward to pay mapping(address => uint256) public rewards; /// @notice Allow users to claim rewards instantly regardless of any voting process /// @dev Link (https://gov.yearn.finance/t/yip-47-release-fee-rewards/6013) bool public breaker = false; /// @notice Exists to generate ids for new proposals uint256 public proposalCount; /// @notice Voting period in blocks ~ 17280 3 days for 15s/block uint256 public period = 17280; /// @notice Vote lock in blocks ~ 17280 3 days for 15s/block uint256 public lock = 17280; /// @notice Minimal amount of governance token to allow proposal creation uint256 public minimum = 1e18; /// @notice Default quorum required in base points uint256 public quorum = 2000; /// @notice Total amount of governance tokens staked uint256 public totalVotes; /// @notice Token in which reward for voting will be paid IERC20 public rewardsToken; /// @notice Default duration of the voting process in seconds uint256 public constant DURATION = 7 days; /// @notice Time period in seconds during which rewards are paid uint256 public periodFinish = 0; /// @notice This variable regulates amount of staking reward token to be paid, it depends from period finish. The last claims the lowest reward uint256 public rewardRate = 0; /// @notice Amount of staking reward token per governance token staked uint256 public rewardPerTokenStored = 0; /// @notice Last time when rewards was added and recalculated uint256 public lastUpdateTime; /// @notice Default initialize method for solving migration linearization problem /// @dev Called once only by deployer /// @param _startId Starting ID (default 0) /// @param _rewardsTokenAddress Token in which rewards are paid /// @param _governance Governance address /// @param _governanceToken Governance token address function configure( uint256 _startId, address _rewardsTokenAddress, address _governance, address _governanceToken, address _rewardDistribution ) external initializer { proposalCount = _startId; rewardsToken = IERC20(_rewardsTokenAddress); _setGovernanceToken(_governanceToken); setGovernance(_governance); setRewardDistribution(_rewardDistribution); } /// @dev This methods evacuates given funds to governance address /// @param _token Exact token to evacuate /// @param _amount Amount of token to evacuate function seize(IERC20 _token, uint256 _amount) external onlyGovernance { require(_token != rewardsToken, "!rewardsToken"); require(_token != governanceToken, "!governanceToken"); _token.safeTransfer(governance, _amount); } /// @notice Usual setter /// @param _breaker New value function setBreaker(bool _breaker) external onlyGovernance { breaker = _breaker; } /// @notice Usual setter /// @param _quorum New value function setQuorum(uint256 _quorum) external onlyGovernance { quorum = _quorum; } /// @notice Usual setter /// @param _minimum New value function setMinimum(uint256 _minimum) external onlyGovernance { minimum = _minimum; } /// @notice Usual setter /// @param _period New value function setPeriod(uint256 _period) external onlyGovernance { period = _period; } /// @notice Usual setter /// @param _lock New value function setLock(uint256 _lock) external onlyGovernance { lock = _lock; } /// @notice Allows msg.sender exit from the whole governance process and withdraw all his rewards and governance tokens function exit() external { withdraw(balanceOf(_msgSender())); getReward(); } /// @notice Adds to governance contract staking reward tokens to be sent to vote process participants. /// @param _reward Amount of staking rewards token in wei function notifyRewardAmount(uint256 _reward) external onlyRewardDistribution override updateReward(address(0)) { IERC20(rewardsToken).safeTransferFrom(_msgSender(), address(this), _reward); if (block.timestamp >= periodFinish) { rewardRate = _reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = _reward.add(leftover).div(DURATION); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(_reward); } /// @notice Creates a proposal to vote /// @param _executor Executor contract address /// @param _hash IPFS hash of the proposal document function propose(address _executor, string memory _hash) public { require(votesOf(_msgSender()) > minimum, "<minimum"); proposals[proposalCount] = Proposal({ id: proposalCount, proposer: _msgSender(), totalForVotes: 0, totalAgainstVotes: 0, start: block.number, end: period.add(block.number), executor: _executor, hash: _hash, totalVotesAvailable: totalVotes, quorum: 0, quorumRequired: quorum, open: true }); emit NewProposal( proposalCount, _msgSender(), block.number, period, _executor ); proposalCount++; voteLock[_msgSender()] = lock.add(block.number); } /// @notice Called by third party to execute the proposal conditions /// @param _id ID of the proposal function execute(uint256 _id) public { (uint256 _for, uint256 _against, uint256 _quorum) = getStats(_id); require(proposals[_id].quorumRequired < _quorum, "!quorum"); require(proposals[_id].end < block.number , "!end"); if (proposals[_id].open) { tallyVotes(_id); } IExecutor(proposals[_id].executor).execute(_id, _for, _against, _quorum); } /// @notice Called by anyone to obtain the voting process statistics for specific proposal /// @param _id ID of the proposal /// @return _for 'For' percentage in base points /// @return _against 'Against' percentage in base points /// @return _quorum Current quorum percentage in base points function getStats(uint256 _id) public view returns( uint256 _for, uint256 _against, uint256 _quorum ) { _for = proposals[_id].totalForVotes; _against = proposals[_id].totalAgainstVotes; uint256 _total = _for.add(_against); if (_total == 0) { _quorum = 0; } else { _for = _for.mul(10000).div(_total); _against = _against.mul(10000).div(_total); _quorum = _total.mul(10000).div(proposals[_id].totalVotesAvailable); } } /// @notice Synonimus name countVotes, called to stop voting process /// @param _id ID of the proposal to be closed function tallyVotes(uint256 _id) public { require(proposals[_id].open, "!open"); require(proposals[_id].end < block.number, "!end"); (uint256 _for, uint256 _against,) = getStats(_id); proposals[_id].open = false; emit ProposalFinished( _id, _for, _against, proposals[_id].quorum >= proposals[_id].quorumRequired ); } /// @notice Called to obtain votes count for specific voter /// @param _voter To whom votes related /// @return Governance token staked to governance contract as votes function votesOf(address _voter) public view returns(uint256) { return votes[_voter]; } /// @notice Registers new user as voter and adds his votes function register() public { require(!voters[_msgSender()], "voter"); voters[_msgSender()] = true; votes[_msgSender()] = balanceOf(_msgSender()); totalVotes = totalVotes.add(votes[_msgSender()]); emit RegisterVoter(_msgSender(), votes[_msgSender()], totalVotes); } /// @notice Nullify (revoke) all the votes staked by msg.sender function revoke() public { require(voters[_msgSender()], "!voter"); voters[_msgSender()] = false; /// @notice Edge case dealt with in openzeppelin trySub methods. /// The case should be impossible, but this is defi. (,totalVotes) = totalVotes.trySub(votes[_msgSender()]); emit RevokeVoter(_msgSender(), votes[_msgSender()], totalVotes); votes[_msgSender()] = 0; } /// @notice Allow registered voter to vote 'for' proposal /// @param _id Proposal id function voteFor(uint256 _id) public { require(proposals[_id].start < block.number, "<start"); require(proposals[_id].end > block.number, ">end"); uint256 _against = proposals[_id].againstVotes[_msgSender()]; if (_against > 0) { proposals[_id].totalAgainstVotes = proposals[_id].totalAgainstVotes.sub(_against); proposals[_id].againstVotes[_msgSender()] = 0; } uint256 vote = votesOf(_msgSender()).sub(proposals[_id].forVotes[_msgSender()]); proposals[_id].totalForVotes = proposals[_id].totalForVotes.add(vote); proposals[_id].forVotes[_msgSender()] = votesOf(_msgSender()); proposals[_id].totalVotesAvailable = totalVotes; uint256 _votes = proposals[_id].totalForVotes.add(proposals[_id].totalAgainstVotes); proposals[_id].quorum = _votes.mul(10000).div(totalVotes); voteLock[_msgSender()] = lock.add(block.number); emit Vote(_id, _msgSender(), true, vote); } /// @notice Allow registered voter to vote 'against' proposal /// @param _id Proposal id function voteAgainst(uint256 _id) public { require(proposals[_id].start < block.number, "<start"); require(proposals[_id].end > block.number, ">end"); uint256 _for = proposals[_id].forVotes[_msgSender()]; if (_for > 0) { proposals[_id].totalForVotes = proposals[_id].totalForVotes.sub(_for); proposals[_id].forVotes[_msgSender()] = 0; } uint256 vote = votesOf(_msgSender()).sub(proposals[_id].againstVotes[_msgSender()]); proposals[_id].totalAgainstVotes = proposals[_id].totalAgainstVotes.add(vote); proposals[_id].againstVotes[_msgSender()] = votesOf(_msgSender()); proposals[_id].totalVotesAvailable = totalVotes; uint256 _votes = proposals[_id].totalForVotes.add(proposals[_id].totalAgainstVotes); proposals[_id].quorum = _votes.mul(10000).div(totalVotes); voteLock[_msgSender()] = lock.add(block.number); emit Vote(_id, _msgSender(), false, vote); } /// @dev Modifier to update stats when reward either sent to governance contract or to voter modifier updateReward(address _account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (_account != address(0)) { rewards[_account] = earned(_account); userRewardPerTokenPaid[_account] = rewardPerTokenStored; } _; } /// @notice Dynamic finish time getter /// @return Recalculated time when voting process needs to be finished function lastTimeRewardApplicable() public view returns(uint256) { return Math.min(block.timestamp, periodFinish); } /// @notice Dynamic reward per token amount getter /// @return Recalculated amount of staking reward tokens per governance token function rewardPerToken() public view returns(uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalSupply()) ); } /// @notice Calculate the size of reward for voter /// @param _account Voter address /// @return Amount of exact staking reward tokens to be paid function earned(address _account) public view returns(uint256) { return balanceOf(_account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[_account])) .div(1e18) .add(rewards[_account]); } /// @notice Allow to add new governance tokens to voter weight, simultaneosly it recalculates reward size according to new weight /// @param _amount Amount of governance token to stake function stake(uint256 _amount) public override updateReward(_msgSender()) { require(_amount > 0, "!stake 0"); if (voters[_msgSender()]) { votes[_msgSender()] = votes[_msgSender()].add(_amount); totalVotes = totalVotes.add(_amount); } super.stake(_amount); emit Staked(_msgSender(), _amount); } /// @notice Allow to remove old governance tokens from voter weight, simultaneosly it recalculates reward size according to new weight /// @param _amount Amount of governance token to withdraw function withdraw(uint256 _amount) public override updateReward(_msgSender()) { require(_amount > 0, "!withdraw 0"); if (voters[_msgSender()]) { votes[_msgSender()] = votes[_msgSender()].sub(_amount); totalVotes = totalVotes.sub(_amount); } if (!breaker) { require(voteLock[_msgSender()] < block.number, "!locked"); } super.withdraw(_amount); emit Withdrawn(_msgSender(), _amount); } /// @notice Transfer staking reward tokens to voter (msg.sender), simultaneosly it recalculates reward size according to new weight and rewards remaining function getReward() public updateReward(_msgSender()) { if (!breaker) { require(voteLock[_msgSender()] > block.number, "!voted"); } uint256 reward = earned(_msgSender()); if (reward > 0) { rewards[_msgSender()] = 0; rewardsToken.transfer(_msgSender(), reward); emit RewardPaid(_msgSender(), reward); } } }
Usual setter _minimum New value
function setMinimum(uint256 _minimum) external onlyGovernance { minimum = _minimum; }
6,919,391
// SPDX-License-Identifier: AGPL-3.0-only /** * DepositBoxERC721.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Artem Payvin * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "../DepositBox.sol"; import "../../Messages.sol"; // This contract runs on the main net and accepts deposits contract DepositBoxERC721 is DepositBox { using AddressUpgradeable for address; // schainHash => address of ERC on Mainnet mapping(bytes32 => mapping(address => bool)) public schainToERC721; mapping(address => mapping(uint256 => bytes32)) public transferredAmount; /** * @dev Emitted when token is mapped in LockAndDataForMainnetERC721. */ event ERC721TokenAdded(string schainName, address indexed contractOnMainnet); event ERC721TokenReady(address indexed contractOnMainnet, uint256 tokenId); function depositERC721( string calldata schainName, address erc721OnMainnet, uint256 tokenId ) external rightTransaction(schainName, msg.sender) whenNotKilled(keccak256(abi.encodePacked(schainName))) { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); address contractReceiver = schainLinks[schainHash]; require(contractReceiver != address(0), "Unconnected chain"); require( IERC721Upgradeable(erc721OnMainnet).getApproved(tokenId) == address(this), "DepositBox was not approved for ERC721 token" ); bytes memory data = _receiveERC721( schainName, erc721OnMainnet, msg.sender, tokenId ); if (!linker.interchainConnections(schainHash)) _saveTransferredAmount(schainHash, erc721OnMainnet, tokenId); IERC721Upgradeable(erc721OnMainnet).transferFrom(msg.sender, address(this), tokenId); messageProxy.postOutgoingMessage( schainHash, contractReceiver, data ); } function postMessage( bytes32 schainHash, address sender, bytes calldata data ) external override onlyMessageProxy whenNotKilled(schainHash) checkReceiverChain(schainHash, sender) returns (address) { Messages.TransferErc721Message memory message = Messages.decodeTransferErc721Message(data); require(message.token.isContract(), "Given address is not a contract"); require(IERC721Upgradeable(message.token).ownerOf(message.tokenId) == address(this), "Incorrect tokenId"); if (!linker.interchainConnections(schainHash)) _removeTransferredAmount(message.token, message.tokenId); IERC721Upgradeable(message.token).transferFrom(address(this), message.receiver, message.tokenId); return message.receiver; } function gasPayer( bytes32 schainHash, address sender, bytes calldata data ) external view override checkReceiverChain(schainHash, sender) returns (address) { Messages.TransferErc721Message memory message = Messages.decodeTransferErc721Message(data); return message.receiver; } /** * @dev Allows Schain owner to add an ERC721 token to LockAndDataForMainnetERC20. */ function addERC721TokenByOwner(string calldata schainName, address erc721OnMainnet) external onlySchainOwner(schainName) whenNotKilled(keccak256(abi.encodePacked(schainName))) { _addERC721ForSchain(schainName, erc721OnMainnet); } function getFunds(string calldata schainName, address erc721OnMainnet, address receiver, uint tokenId) external onlySchainOwner(schainName) whenKilled(keccak256(abi.encodePacked(schainName))) { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require(transferredAmount[erc721OnMainnet][tokenId] == schainHash, "Incorrect tokenId"); _removeTransferredAmount(erc721OnMainnet, tokenId); IERC721Upgradeable(erc721OnMainnet).transferFrom(address(this), receiver, tokenId); } /** * @dev Should return true if token in whitelist. */ function getSchainToERC721(string calldata schainName, address erc721OnMainnet) external view returns (bool) { return schainToERC721[keccak256(abi.encodePacked(schainName))][erc721OnMainnet]; } /// Create a new deposit box function initialize( IContractManager contractManagerOfSkaleManagerValue, Linker linkerValue, MessageProxyForMainnet messageProxyValue ) public override initializer { DepositBox.initialize(contractManagerOfSkaleManagerValue, linkerValue, messageProxyValue); } function _saveTransferredAmount(bytes32 schainHash, address erc721Token, uint256 tokenId) private { transferredAmount[erc721Token][tokenId] = schainHash; } function _removeTransferredAmount(address erc721Token, uint256 tokenId) private { transferredAmount[erc721Token][tokenId] = bytes32(0); } /** * @dev Allows DepositBox to receive ERC721 tokens. * * Emits an {ERC721TokenAdded} event. */ function _receiveERC721( string calldata schainName, address erc721OnMainnet, address to, uint256 tokenId ) private returns (bytes memory data) { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); bool isERC721AddedToSchain = schainToERC721[schainHash][erc721OnMainnet]; if (!isERC721AddedToSchain) { require(!isWhitelisted(schainName), "Whitelist is enabled"); _addERC721ForSchain(schainName, erc721OnMainnet); data = Messages.encodeTransferErc721AndTokenInfoMessage( erc721OnMainnet, to, tokenId, _getTokenInfo(IERC721MetadataUpgradeable(erc721OnMainnet)) ); } else { data = Messages.encodeTransferErc721Message(erc721OnMainnet, to, tokenId); } emit ERC721TokenReady(erc721OnMainnet, tokenId); } /** * @dev Allows ERC721ModuleForMainnet to add an ERC721 token to * LockAndDataForMainnetERC721. */ function _addERC721ForSchain(string calldata schainName, address erc721OnMainnet) private { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require(erc721OnMainnet.isContract(), "Given address is not a contract"); schainToERC721[schainHash][erc721OnMainnet] = true; emit ERC721TokenAdded(schainName, erc721OnMainnet); } function _getTokenInfo(IERC721MetadataUpgradeable erc721) private view returns (Messages.Erc721TokenInfo memory) { return Messages.Erc721TokenInfo({ name: erc721.name(), symbol: erc721.symbol() }); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: AGPL-3.0-only /** * DepositBox.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Artem Payvin * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "./Linker.sol"; import "./MessageProxyForMainnet.sol"; /** * @title ProxyConnectorMainnet - connected module for Upgradeable approach, knows ContractManager * @author Artem Payvin */ abstract contract DepositBox is IGasReimbursable, Twin { Linker public linker; mapping(bytes32 => bool) private _automaticDeploy; bytes32 public constant DEPOSIT_BOX_MANAGER_ROLE = keccak256("DEPOSIT_BOX_MANAGER_ROLE"); modifier whenNotKilled(bytes32 schainHash) { require(linker.isNotKilled(schainHash), "Schain is killed"); _; } modifier whenKilled(bytes32 schainHash) { require(!linker.isNotKilled(schainHash), "Schain is not killed"); _; } modifier rightTransaction(string memory schainName, address to) { require( keccak256(abi.encodePacked(schainName)) != keccak256(abi.encodePacked("Mainnet")), "SKALE chain name cannot be Mainnet" ); require(to != address(0), "Receiver address cannot be null"); _; } modifier checkReceiverChain(bytes32 schainHash, address sender) { require( schainHash != keccak256(abi.encodePacked("Mainnet")) && sender == schainLinks[schainHash], "Receiver chain is incorrect" ); _; } /** * @dev Allows Schain owner turn on whitelist of tokens. */ function enableWhitelist(string memory schainName) external onlySchainOwner(schainName) { _automaticDeploy[keccak256(abi.encodePacked(schainName))] = false; } /** * @dev Allows Schain owner turn off whitelist of tokens. */ function disableWhitelist(string memory schainName) external onlySchainOwner(schainName) { _automaticDeploy[keccak256(abi.encodePacked(schainName))] = true; } function initialize( IContractManager contractManagerOfSkaleManagerValue, Linker newLinker, MessageProxyForMainnet messageProxyValue ) public virtual initializer { Twin.initialize(contractManagerOfSkaleManagerValue, messageProxyValue); _setupRole(LINKER_ROLE, address(newLinker)); linker = newLinker; } /** * @dev Returns is whitelist enabled on schain */ function isWhitelisted(string memory schainName) public view returns (bool) { return !_automaticDeploy[keccak256(abi.encodePacked(schainName))]; } } // SPDX-License-Identifier: AGPL-3.0-only /** * Messages.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Dmytro Stebaeiv * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; library Messages { enum MessageType { EMPTY, TRANSFER_ETH, TRANSFER_ERC20, TRANSFER_ERC20_AND_TOTAL_SUPPLY, TRANSFER_ERC20_AND_TOKEN_INFO, TRANSFER_ERC721, TRANSFER_ERC721_AND_TOKEN_INFO, USER_STATUS, INTERCHAIN_CONNECTION, TRANSFER_ERC1155, TRANSFER_ERC1155_AND_TOKEN_INFO, TRANSFER_ERC1155_BATCH, TRANSFER_ERC1155_BATCH_AND_TOKEN_INFO } struct BaseMessage { MessageType messageType; } struct TransferEthMessage { BaseMessage message; address receiver; uint256 amount; } struct UserStatusMessage { BaseMessage message; address receiver; bool isActive; } struct TransferErc20Message { BaseMessage message; address token; address receiver; uint256 amount; } struct Erc20TokenInfo { string name; uint8 decimals; string symbol; } struct TransferErc20AndTotalSupplyMessage { TransferErc20Message baseErc20transfer; uint256 totalSupply; } struct TransferErc20AndTokenInfoMessage { TransferErc20Message baseErc20transfer; uint256 totalSupply; Erc20TokenInfo tokenInfo; } struct TransferErc721Message { BaseMessage message; address token; address receiver; uint256 tokenId; } struct Erc721TokenInfo { string name; string symbol; } struct TransferErc721AndTokenInfoMessage { TransferErc721Message baseErc721transfer; Erc721TokenInfo tokenInfo; } struct InterchainConnectionMessage { BaseMessage message; bool isAllowed; } struct TransferErc1155Message { BaseMessage message; address token; address receiver; uint256 id; uint256 amount; } struct TransferErc1155BatchMessage { BaseMessage message; address token; address receiver; uint256[] ids; uint256[] amounts; } struct Erc1155TokenInfo { string uri; } struct TransferErc1155AndTokenInfoMessage { TransferErc1155Message baseErc1155transfer; Erc1155TokenInfo tokenInfo; } struct TransferErc1155BatchAndTokenInfoMessage { TransferErc1155BatchMessage baseErc1155Batchtransfer; Erc1155TokenInfo tokenInfo; } function getMessageType(bytes calldata data) internal pure returns (MessageType) { uint256 firstWord = abi.decode(data, (uint256)); if (firstWord % 32 == 0) { return getMessageType(data[firstWord:]); } else { return abi.decode(data, (Messages.MessageType)); } } function encodeTransferEthMessage(address receiver, uint256 amount) internal pure returns (bytes memory) { TransferEthMessage memory message = TransferEthMessage( BaseMessage(MessageType.TRANSFER_ETH), receiver, amount ); return abi.encode(message); } function decodeTransferEthMessage( bytes calldata data ) internal pure returns (TransferEthMessage memory) { require(getMessageType(data) == MessageType.TRANSFER_ETH, "Message type is not ETH transfer"); return abi.decode(data, (TransferEthMessage)); } function encodeTransferErc20Message( address token, address receiver, uint256 amount ) internal pure returns (bytes memory) { TransferErc20Message memory message = TransferErc20Message( BaseMessage(MessageType.TRANSFER_ERC20), token, receiver, amount ); return abi.encode(message); } function encodeTransferErc20AndTotalSupplyMessage( address token, address receiver, uint256 amount, uint256 totalSupply ) internal pure returns (bytes memory) { TransferErc20AndTotalSupplyMessage memory message = TransferErc20AndTotalSupplyMessage( TransferErc20Message( BaseMessage(MessageType.TRANSFER_ERC20_AND_TOTAL_SUPPLY), token, receiver, amount ), totalSupply ); return abi.encode(message); } function decodeTransferErc20Message( bytes calldata data ) internal pure returns (TransferErc20Message memory) { require(getMessageType(data) == MessageType.TRANSFER_ERC20, "Message type is not ERC20 transfer"); return abi.decode(data, (TransferErc20Message)); } function decodeTransferErc20AndTotalSupplyMessage( bytes calldata data ) internal pure returns (TransferErc20AndTotalSupplyMessage memory) { require( getMessageType(data) == MessageType.TRANSFER_ERC20_AND_TOTAL_SUPPLY, "Message type is not ERC20 transfer and total supply" ); return abi.decode(data, (TransferErc20AndTotalSupplyMessage)); } function encodeTransferErc20AndTokenInfoMessage( address token, address receiver, uint256 amount, uint256 totalSupply, Erc20TokenInfo memory tokenInfo ) internal pure returns (bytes memory) { TransferErc20AndTokenInfoMessage memory message = TransferErc20AndTokenInfoMessage( TransferErc20Message( BaseMessage(MessageType.TRANSFER_ERC20_AND_TOKEN_INFO), token, receiver, amount ), totalSupply, tokenInfo ); return abi.encode(message); } function decodeTransferErc20AndTokenInfoMessage( bytes calldata data ) internal pure returns (TransferErc20AndTokenInfoMessage memory) { require( getMessageType(data) == MessageType.TRANSFER_ERC20_AND_TOKEN_INFO, "Message type is not ERC20 transfer with token info" ); return abi.decode(data, (TransferErc20AndTokenInfoMessage)); } function encodeTransferErc721Message( address token, address receiver, uint256 tokenId ) internal pure returns (bytes memory) { TransferErc721Message memory message = TransferErc721Message( BaseMessage(MessageType.TRANSFER_ERC721), token, receiver, tokenId ); return abi.encode(message); } function decodeTransferErc721Message( bytes calldata data ) internal pure returns (TransferErc721Message memory) { require(getMessageType(data) == MessageType.TRANSFER_ERC721, "Message type is not ERC721 transfer"); return abi.decode(data, (TransferErc721Message)); } function encodeTransferErc721AndTokenInfoMessage( address token, address receiver, uint256 tokenId, Erc721TokenInfo memory tokenInfo ) internal pure returns (bytes memory) { TransferErc721AndTokenInfoMessage memory message = TransferErc721AndTokenInfoMessage( TransferErc721Message( BaseMessage(MessageType.TRANSFER_ERC721_AND_TOKEN_INFO), token, receiver, tokenId ), tokenInfo ); return abi.encode(message); } function decodeTransferErc721AndTokenInfoMessage( bytes calldata data ) internal pure returns (TransferErc721AndTokenInfoMessage memory) { require( getMessageType(data) == MessageType.TRANSFER_ERC721_AND_TOKEN_INFO, "Message type is not ERC721 transfer with token info" ); return abi.decode(data, (TransferErc721AndTokenInfoMessage)); } function encodeActivateUserMessage(address receiver) internal pure returns (bytes memory){ return _encodeUserStatusMessage(receiver, true); } function encodeLockUserMessage(address receiver) internal pure returns (bytes memory){ return _encodeUserStatusMessage(receiver, false); } function decodeUserStatusMessage(bytes calldata data) internal pure returns (UserStatusMessage memory) { require(getMessageType(data) == MessageType.USER_STATUS, "Message type is not User Status"); return abi.decode(data, (UserStatusMessage)); } function encodeInterchainConnectionMessage(bool isAllowed) internal pure returns (bytes memory) { InterchainConnectionMessage memory message = InterchainConnectionMessage( BaseMessage(MessageType.INTERCHAIN_CONNECTION), isAllowed ); return abi.encode(message); } function decodeInterchainConnectionMessage(bytes calldata data) internal pure returns (InterchainConnectionMessage memory) { require(getMessageType(data) == MessageType.INTERCHAIN_CONNECTION, "Message type is not Interchain connection"); return abi.decode(data, (InterchainConnectionMessage)); } function encodeTransferErc1155Message( address token, address receiver, uint256 id, uint256 amount ) internal pure returns (bytes memory) { TransferErc1155Message memory message = TransferErc1155Message( BaseMessage(MessageType.TRANSFER_ERC1155), token, receiver, id, amount ); return abi.encode(message); } function decodeTransferErc1155Message( bytes calldata data ) internal pure returns (TransferErc1155Message memory) { require(getMessageType(data) == MessageType.TRANSFER_ERC1155, "Message type is not ERC1155 transfer"); return abi.decode(data, (TransferErc1155Message)); } function encodeTransferErc1155AndTokenInfoMessage( address token, address receiver, uint256 id, uint256 amount, Erc1155TokenInfo memory tokenInfo ) internal pure returns (bytes memory) { TransferErc1155AndTokenInfoMessage memory message = TransferErc1155AndTokenInfoMessage( TransferErc1155Message( BaseMessage(MessageType.TRANSFER_ERC1155_AND_TOKEN_INFO), token, receiver, id, amount ), tokenInfo ); return abi.encode(message); } function decodeTransferErc1155AndTokenInfoMessage( bytes calldata data ) internal pure returns (TransferErc1155AndTokenInfoMessage memory) { require( getMessageType(data) == MessageType.TRANSFER_ERC1155_AND_TOKEN_INFO, "Message type is not ERC1155AndTokenInfo transfer" ); return abi.decode(data, (TransferErc1155AndTokenInfoMessage)); } function encodeTransferErc1155BatchMessage( address token, address receiver, uint256[] memory ids, uint256[] memory amounts ) internal pure returns (bytes memory) { TransferErc1155BatchMessage memory message = TransferErc1155BatchMessage( BaseMessage(MessageType.TRANSFER_ERC1155_BATCH), token, receiver, ids, amounts ); return abi.encode(message); } function decodeTransferErc1155BatchMessage( bytes calldata data ) internal pure returns (TransferErc1155BatchMessage memory) { require( getMessageType(data) == MessageType.TRANSFER_ERC1155_BATCH, "Message type is not ERC1155Batch transfer" ); return abi.decode(data, (TransferErc1155BatchMessage)); } function encodeTransferErc1155BatchAndTokenInfoMessage( address token, address receiver, uint256[] memory ids, uint256[] memory amounts, Erc1155TokenInfo memory tokenInfo ) internal pure returns (bytes memory) { TransferErc1155BatchAndTokenInfoMessage memory message = TransferErc1155BatchAndTokenInfoMessage( TransferErc1155BatchMessage( BaseMessage(MessageType.TRANSFER_ERC1155_BATCH_AND_TOKEN_INFO), token, receiver, ids, amounts ), tokenInfo ); return abi.encode(message); } function decodeTransferErc1155BatchAndTokenInfoMessage( bytes calldata data ) internal pure returns (TransferErc1155BatchAndTokenInfoMessage memory) { require( getMessageType(data) == MessageType.TRANSFER_ERC1155_BATCH_AND_TOKEN_INFO, "Message type is not ERC1155BatchAndTokenInfo transfer" ); return abi.decode(data, (TransferErc1155BatchAndTokenInfoMessage)); } function _encodeUserStatusMessage(address receiver, bool isActive) private pure returns (bytes memory) { UserStatusMessage memory message = UserStatusMessage( BaseMessage(MessageType.USER_STATUS), receiver, isActive ); return abi.encode(message); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /** * Linker.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Artem Payvin * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "../Messages.sol"; import "./Twin.sol"; import "./MessageProxyForMainnet.sol"; /** * @title Linker For Mainnet * @dev Runs on Mainnet, holds deposited ETH, and contains mappings and * balances of ETH tokens received through DepositBox. */ contract Linker is Twin { using AddressUpgradeable for address; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; enum KillProcess {NotKilled, PartiallyKilledBySchainOwner, PartiallyKilledByContractOwner, Killed} EnumerableSetUpgradeable.AddressSet private _mainnetContracts; mapping(bytes32 => bool) public interchainConnections; mapping(bytes32 => KillProcess) public statuses; modifier onlyLinker() { require(hasRole(LINKER_ROLE, msg.sender), "Linker role is required"); _; } function registerMainnetContract(address newMainnetContract) external onlyLinker { require(_mainnetContracts.add(newMainnetContract), "The contracts was not registered"); } function removeMainnetContract(address mainnetContract) external onlyLinker { require(_mainnetContracts.remove(mainnetContract), "The contract was not removed"); } function connectSchain(string calldata schainName, address[] calldata schainContracts) external onlyLinker { require(schainContracts.length == _mainnetContracts.length(), "Incorrect number of addresses"); for (uint i = 0; i < schainContracts.length; i++) { Twin(_mainnetContracts.at(i)).addSchainContract(schainName, schainContracts[i]); } messageProxy.addConnectedChain(schainName); } function allowInterchainConnections(string calldata schainName) external onlySchainOwner(schainName) { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require(statuses[schainHash] == KillProcess.NotKilled, "Schain is in kill process"); interchainConnections[schainHash] = true; messageProxy.postOutgoingMessage( schainHash, schainLinks[schainHash], Messages.encodeInterchainConnectionMessage(true) ); } function kill(string calldata schainName) external { require(!interchainConnections[keccak256(abi.encodePacked(schainName))], "Interchain connections turned on"); bytes32 schainHash = keccak256(abi.encodePacked(schainName)); if (statuses[schainHash] == KillProcess.NotKilled) { if (hasRole(DEFAULT_ADMIN_ROLE, msg.sender)) { statuses[schainHash] = KillProcess.PartiallyKilledByContractOwner; } else if (isSchainOwner(msg.sender, schainHash)) { statuses[schainHash] = KillProcess.PartiallyKilledBySchainOwner; } else { revert("Not allowed"); } } else if ( ( statuses[schainHash] == KillProcess.PartiallyKilledBySchainOwner && hasRole(DEFAULT_ADMIN_ROLE, msg.sender) ) || ( statuses[schainHash] == KillProcess.PartiallyKilledByContractOwner && isSchainOwner(msg.sender, schainHash) ) ) { statuses[schainHash] = KillProcess.Killed; } else { revert("Already killed or incorrect sender"); } } function disconnectSchain(string calldata schainName) external onlyLinker { uint length = _mainnetContracts.length(); for (uint i = 0; i < length; i++) { Twin(_mainnetContracts.at(i)).removeSchainContract(schainName); } messageProxy.removeConnectedChain(schainName); } function isNotKilled(bytes32 schainHash) external view returns (bool) { return statuses[schainHash] != KillProcess.Killed; } function hasMainnetContract(address mainnetContract) external view returns (bool) { return _mainnetContracts.contains(mainnetContract); } function hasSchain(string calldata schainName) external view returns (bool connected) { uint length = _mainnetContracts.length(); connected = messageProxy.isConnectedChain(schainName); for (uint i = 0; connected && i < length; i++) { connected = connected && Twin(_mainnetContracts.at(i)).hasSchainContract(schainName); } } function initialize( IContractManager contractManagerOfSkaleManagerValue, MessageProxyForMainnet messageProxyValue ) public override initializer { Twin.initialize(contractManagerOfSkaleManagerValue, messageProxyValue); _setupRole(LINKER_ROLE, msg.sender); _setupRole(LINKER_ROLE, address(this)); } } // SPDX-License-Identifier: AGPL-3.0-only /** * MessageProxyForMainnet.sol - SKALE Interchain Messaging Agent * Copyright (C) 2019-Present SKALE Labs * @author Artem Payvin * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@skalenetwork/skale-manager-interfaces/IWallets.sol"; import "@skalenetwork/skale-manager-interfaces/ISchains.sol"; import "../MessageProxy.sol"; import "./SkaleManagerClient.sol"; import "./CommunityPool.sol"; /** * @title Message Proxy for Mainnet * @dev Runs on Mainnet, contains functions to manage the incoming messages from * `targetSchainName` and outgoing messages to `fromSchainName`. Every SKALE chain with * IMA is therefore connected to MessageProxyForMainnet. * * Messages from SKALE chains are signed using BLS threshold signatures from the * nodes in the chain. Since Ethereum Mainnet has no BLS public key, mainnet * messages do not need to be signed. */ contract MessageProxyForMainnet is SkaleManagerClient, MessageProxy { using AddressUpgradeable for address; /** * 16 Agents * Synchronize time with time.nist.gov * Every agent checks if it is his time slot * Time slots are in increments of 10 seconds * At the start of his slot each agent: * For each connected schain: * Read incoming counter on the dst chain * Read outgoing counter on the src chain * Calculate the difference outgoing - incoming * Call postIncomingMessages function passing (un)signed message array * ID of this schain, Chain 0 represents ETH mainnet, */ CommunityPool public communityPool; uint256 public headerMessageGasCost; uint256 public messageGasCost; event GasCostMessageHeaderWasChanged( uint256 oldValue, uint256 newValue ); event GasCostMessageWasChanged( uint256 oldValue, uint256 newValue ); /** * @dev Allows LockAndData to add a `schainName`. * * Requirements: * * - `msg.sender` must be SKALE Node address. * - `schainName` must not be "Mainnet". * - `schainName` must not already be added. */ function addConnectedChain(string calldata schainName) external override { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require(schainHash != MAINNET_HASH, "SKALE chain name is incorrect"); _addConnectedChain(schainHash); } function setCommunityPool(CommunityPool newCommunityPoolAddress) external { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Not authorized caller"); require(address(newCommunityPoolAddress) != address(0), "CommunityPool address has to be set"); communityPool = newCommunityPoolAddress; } function registerExtraContract(string memory schainName, address extraContract) external { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require( hasRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender) || isSchainOwner(msg.sender, schainHash), "Not enough permissions to register extra contract" ); require(schainHash != MAINNET_HASH, "Schain hash can not be equal Mainnet"); _registerExtraContract(schainHash, extraContract); } function removeExtraContract(string memory schainName, address extraContract) external { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require( hasRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender) || isSchainOwner(msg.sender, schainHash), "Not enough permissions to register extra contract" ); require(schainHash != MAINNET_HASH, "Schain hash can not be equal Mainnet"); _removeExtraContract(schainHash, extraContract); } /** * @dev Posts incoming message from `fromSchainName`. * * Requirements: * * - `msg.sender` must be authorized caller. * - `fromSchainName` must be initialized. * - `startingCounter` must be equal to the chain's incoming message counter. * - If destination chain is Mainnet, message signature must be valid. */ function postIncomingMessages( string calldata fromSchainName, uint256 startingCounter, Message[] calldata messages, Signature calldata sign ) external override { uint256 gasTotal = gasleft(); bytes32 fromSchainHash = keccak256(abi.encodePacked(fromSchainName)); require(_checkSchainBalance(fromSchainHash), "Schain wallet has not enough funds"); require(connectedChains[fromSchainHash].inited, "Chain is not initialized"); require(messages.length <= MESSAGES_LENGTH, "Too many messages"); require( startingCounter == connectedChains[fromSchainHash].incomingMessageCounter, "Starting counter is not equal to incoming message counter"); require(_verifyMessages(fromSchainName, _hashedArray(messages), sign), "Signature is not verified"); uint additionalGasPerMessage = (gasTotal - gasleft() + headerMessageGasCost + messages.length * messageGasCost) / messages.length; uint notReimbursedGas = 0; for (uint256 i = 0; i < messages.length; i++) { gasTotal = gasleft(); if (registryContracts[bytes32(0)][messages[i].destinationContract]) { address receiver = _getGasPayer(fromSchainHash, messages[i], startingCounter + i); _callReceiverContract(fromSchainHash, messages[i], startingCounter + i); notReimbursedGas += communityPool.refundGasByUser( fromSchainHash, payable(msg.sender), receiver, gasTotal - gasleft() + additionalGasPerMessage ); } else { _callReceiverContract(fromSchainHash, messages[i], startingCounter + i); notReimbursedGas += gasTotal - gasleft() + additionalGasPerMessage; } } connectedChains[fromSchainHash].incomingMessageCounter += messages.length; communityPool.refundGasBySchainWallet(fromSchainHash, payable(msg.sender), notReimbursedGas); } /** * @dev Sets headerMessageGasCost to a new value * * Requirements: * * - `msg.sender` must be granted as CONSTANT_SETTER_ROLE. */ function setNewHeaderMessageGasCost(uint256 newHeaderMessageGasCost) external onlyConstantSetter { emit GasCostMessageHeaderWasChanged(headerMessageGasCost, newHeaderMessageGasCost); headerMessageGasCost = newHeaderMessageGasCost; } /** * @dev Sets messageGasCost to a new value * * Requirements: * * - `msg.sender` must be granted as CONSTANT_SETTER_ROLE. */ function setNewMessageGasCost(uint256 newMessageGasCost) external onlyConstantSetter { emit GasCostMessageWasChanged(messageGasCost, newMessageGasCost); messageGasCost = newMessageGasCost; } /** * @dev Checks whether chain is currently connected. * * Note: Mainnet chain does not have a public key, and is implicitly * connected to MessageProxy. * * Requirements: * * - `schainName` must not be Mainnet. */ function isConnectedChain( string memory schainName ) public view override returns (bool) { require(keccak256(abi.encodePacked(schainName)) != MAINNET_HASH, "Schain id can not be equal Mainnet"); return super.isConnectedChain(schainName); } // Create a new message proxy function initialize(IContractManager contractManagerOfSkaleManagerValue) public virtual override initializer { SkaleManagerClient.initialize(contractManagerOfSkaleManagerValue); MessageProxy.initializeMessageProxy(1e6); headerMessageGasCost = 70000; messageGasCost = 8790; } /** * @dev Converts calldata structure to memory structure and checks * whether message BLS signature is valid. */ function _verifyMessages( string calldata fromSchainName, bytes32 hashedMessages, MessageProxyForMainnet.Signature calldata sign ) internal view returns (bool) { return ISchains( contractManagerOfSkaleManager.getContract("Schains") ).verifySchainSignature( sign.blsSignature[0], sign.blsSignature[1], hashedMessages, sign.counter, sign.hashA, sign.hashB, fromSchainName ); } function _checkSchainBalance(bytes32 schainHash) internal view returns (bool) { return IWallets( contractManagerOfSkaleManager.getContract("Wallets") ).getSchainBalance(schainHash) >= (MESSAGES_LENGTH + 1) * gasLimit * tx.gasprice; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: AGPL-3.0-only /** * Twin.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Artem Payvin * @author Dmytro Stebaiev * @author Vadim Yavorsky * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "./MessageProxyForMainnet.sol"; import "./SkaleManagerClient.sol"; abstract contract Twin is SkaleManagerClient { MessageProxyForMainnet public messageProxy; mapping(bytes32 => address) public schainLinks; bytes32 public constant LINKER_ROLE = keccak256("LINKER_ROLE"); modifier onlyMessageProxy() { require(msg.sender == address(messageProxy), "Sender is not a MessageProxy"); _; } /** * @dev Binds a contract on mainnet with his twin on schain * * Requirements: * * - `msg.sender` must be schain owner or has required role. * - SKALE chain must not already be added. * - Address of contract on schain must be non-zero. */ function addSchainContract(string calldata schainName, address contractReceiver) external { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require( hasRole(LINKER_ROLE, msg.sender) || isSchainOwner(msg.sender, schainHash), "Not authorized caller" ); require(schainLinks[schainHash] == address(0), "SKALE chain is already set"); require(contractReceiver != address(0), "Incorrect address of contract receiver on Schain"); schainLinks[schainHash] = contractReceiver; } /** * @dev Removes connection with contract on schain * * Requirements: * * - `msg.sender` must be schain owner or has required role * - SKALE chain must already be set. */ function removeSchainContract(string calldata schainName) external { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require( hasRole(LINKER_ROLE, msg.sender) || isSchainOwner(msg.sender, schainHash), "Not authorized caller" ); require(schainLinks[schainHash] != address(0), "SKALE chain is not set"); delete schainLinks[schainHash]; } function hasSchainContract(string calldata schainName) external view returns (bool) { return schainLinks[keccak256(abi.encodePacked(schainName))] != address(0); } function initialize( IContractManager contractManagerOfSkaleManagerValue, MessageProxyForMainnet newMessageProxy ) public virtual initializer { SkaleManagerClient.initialize(contractManagerOfSkaleManagerValue); messageProxy = newMessageProxy; } } // SPDX-License-Identifier: AGPL-3.0-only /** * SkaleManagerClient.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Artem Payvin * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@skalenetwork/skale-manager-interfaces/IContractManager.sol"; import "@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol"; /** * @title SkaleManagerClient - contract that knows ContractManager * and makes calls to SkaleManager contracts * @author Artem Payvin * @author Dmytro Stebaiev */ contract SkaleManagerClient is Initializable, AccessControlEnumerableUpgradeable { IContractManager public contractManagerOfSkaleManager; modifier onlySchainOwner(string memory schainName) { require( isSchainOwner(msg.sender, keccak256(abi.encodePacked(schainName))), "Sender is not an Schain owner" ); _; } /** * @dev Checks whether sender is owner of SKALE chain */ function isSchainOwner(address sender, bytes32 schainHash) public view returns (bool) { address skaleChainsInternal = contractManagerOfSkaleManager.getContract("SchainsInternal"); return ISchainsInternal(skaleChainsInternal).isOwnerAddress(sender, schainHash); } /** * @dev initialize - sets current address of ContractManager of SkaleManager * @param newContractManagerOfSkaleManager - current address of ContractManager of SkaleManager */ function initialize( IContractManager newContractManagerOfSkaleManager ) public virtual initializer { AccessControlEnumerableUpgradeable.__AccessControlEnumerable_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); contractManagerOfSkaleManager = newContractManagerOfSkaleManager; } } // SPDX-License-Identifier: AGPL-3.0-only /* IWallets - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IWallets { function refundGasBySchain(bytes32 schainId, address payable spender, uint spentGas, bool isDebt) external; function rechargeSchainWallet(bytes32 schainId) external payable; function getSchainBalance(bytes32 schainHash) external view returns (uint); } // SPDX-License-Identifier: AGPL-3.0-only /* ISchains.sol - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface ISchains { function verifySchainSignature( uint256 signA, uint256 signB, bytes32 hash, uint256 counter, uint256 hashA, uint256 hashB, string calldata schainName ) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /** * MessageProxy.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "./interfaces/IMessageReceiver.sol"; import "./interfaces/IGasReimbursable.sol"; abstract contract MessageProxy is AccessControlEnumerableUpgradeable { using AddressUpgradeable for address; bytes32 public constant MAINNET_HASH = keccak256(abi.encodePacked("Mainnet")); bytes32 public constant CHAIN_CONNECTOR_ROLE = keccak256("CHAIN_CONNECTOR_ROLE"); bytes32 public constant EXTRA_CONTRACT_REGISTRAR_ROLE = keccak256("EXTRA_CONTRACT_REGISTRAR_ROLE"); bytes32 public constant CONSTANT_SETTER_ROLE = keccak256("CONSTANT_SETTER_ROLE"); uint256 public constant MESSAGES_LENGTH = 10; struct ConnectedChainInfo { // message counters start with 0 uint256 incomingMessageCounter; uint256 outgoingMessageCounter; bool inited; } struct Message { address sender; address destinationContract; bytes data; } struct Signature { uint256[2] blsSignature; uint256 hashA; uint256 hashB; uint256 counter; } // schainHash => ConnectedChainInfo mapping(bytes32 => ConnectedChainInfo) public connectedChains; // schainHash => contract address => allowed mapping(bytes32 => mapping(address => bool)) public registryContracts; uint256 public gasLimit; /** * @dev Emitted for every outgoing message to `dstChain`. */ event OutgoingMessage( bytes32 indexed dstChainHash, uint256 indexed msgCounter, address indexed srcContract, address dstContract, bytes data ); event PostMessageError( uint256 indexed msgCounter, bytes message ); event GasLimitWasChanged( uint256 oldValue, uint256 newValue ); modifier onlyChainConnector() { require(hasRole(CHAIN_CONNECTOR_ROLE, msg.sender), "CHAIN_CONNECTOR_ROLE is required"); _; } modifier onlyExtraContractRegistrar() { require(hasRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender), "EXTRA_CONTRACT_REGISTRAR_ROLE is required"); _; } modifier onlyConstantSetter() { require(hasRole(CONSTANT_SETTER_ROLE, msg.sender), "Not enough permissions to set constant"); _; } function initializeMessageProxy(uint newGasLimit) public initializer { AccessControlEnumerableUpgradeable.__AccessControlEnumerable_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(CHAIN_CONNECTOR_ROLE, msg.sender); _setupRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender); _setupRole(CONSTANT_SETTER_ROLE, msg.sender); emit GasLimitWasChanged(gasLimit, newGasLimit); gasLimit = newGasLimit; } // Registration state detection function isConnectedChain( string memory schainName ) public view virtual returns (bool) { return connectedChains[keccak256(abi.encodePacked(schainName))].inited; } /** * @dev Allows LockAndData to add a `schainName`. * * Requirements: * * - `msg.sender` must be SKALE Node address. * - `schainName` must not be "Mainnet". * - `schainName` must not already be added. */ function addConnectedChain(string calldata schainName) external virtual; /** * @dev Allows LockAndData to remove connected chain from this contract. * * Requirements: * * - `msg.sender` must be LockAndData contract. * - `schainName` must be initialized. */ function removeConnectedChain(string memory schainName) public virtual onlyChainConnector { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require(connectedChains[schainHash].inited, "Chain is not initialized"); delete connectedChains[schainHash]; } /** * @dev Sets gasLimit to a new value * * Requirements: * * - `msg.sender` must be granted CONSTANT_SETTER_ROLE. */ function setNewGasLimit(uint256 newGasLimit) external onlyConstantSetter { emit GasLimitWasChanged(gasLimit, newGasLimit); gasLimit = newGasLimit; } /** * @dev Posts message from this contract to `targetSchainName` MessageProxy contract. * This is called by a smart contract to make a cross-chain call. * * Requirements: * * - `targetSchainName` must be initialized. */ function postOutgoingMessage( bytes32 targetChainHash, address targetContract, bytes memory data ) public virtual { require(connectedChains[targetChainHash].inited, "Destination chain is not initialized"); require( registryContracts[bytes32(0)][msg.sender] || registryContracts[targetChainHash][msg.sender], "Sender contract is not registered" ); emit OutgoingMessage( targetChainHash, connectedChains[targetChainHash].outgoingMessageCounter, msg.sender, targetContract, data ); connectedChains[targetChainHash].outgoingMessageCounter += 1; } function postIncomingMessages( string calldata fromSchainName, uint256 startingCounter, Message[] calldata messages, Signature calldata sign ) external virtual; function registerExtraContractForAll(address extraContract) external onlyExtraContractRegistrar { require(extraContract.isContract(), "Given address is not a contract"); require(!registryContracts[bytes32(0)][extraContract], "Extra contract is already registered"); registryContracts[bytes32(0)][extraContract] = true; } function removeExtraContractForAll(address extraContract) external onlyExtraContractRegistrar { require(registryContracts[bytes32(0)][extraContract], "Extra contract is not registered"); delete registryContracts[bytes32(0)][extraContract]; } /** * @dev Checks whether contract is currently connected to * send messages to chain or receive messages from chain. */ function isContractRegistered( string calldata schainName, address contractAddress ) external view returns (bool) { return registryContracts[keccak256(abi.encodePacked(schainName))][contractAddress] || registryContracts[bytes32(0)][contractAddress]; } /** * @dev Returns number of outgoing messages to some schain * * Requirements: * * - `targetSchainName` must be initialized. */ function getOutgoingMessagesCounter(string calldata targetSchainName) external view returns (uint256) { bytes32 dstChainHash = keccak256(abi.encodePacked(targetSchainName)); require(connectedChains[dstChainHash].inited, "Destination chain is not initialized"); return connectedChains[dstChainHash].outgoingMessageCounter; } /** * @dev Returns number of incoming messages from some schain * * Requirements: * * - `fromSchainName` must be initialized. */ function getIncomingMessagesCounter(string calldata fromSchainName) external view returns (uint256) { bytes32 srcChainHash = keccak256(abi.encodePacked(fromSchainName)); require(connectedChains[srcChainHash].inited, "Source chain is not initialized"); return connectedChains[srcChainHash].incomingMessageCounter; } // private function _addConnectedChain(bytes32 schainHash) internal onlyChainConnector { require(!connectedChains[schainHash].inited,"Chain is already connected"); connectedChains[schainHash] = ConnectedChainInfo({ incomingMessageCounter: 0, outgoingMessageCounter: 0, inited: true }); } function _callReceiverContract( bytes32 schainHash, Message calldata message, uint counter ) internal returns (address) { try IMessageReceiver(message.destinationContract).postMessage{gas: gasLimit}( schainHash, message.sender, message.data ) returns (address receiver) { return receiver; } catch Error(string memory reason) { emit PostMessageError( counter, bytes(reason) ); return address(0); } catch (bytes memory revertData) { emit PostMessageError( counter, revertData ); return address(0); } } function _registerExtraContract( bytes32 chainHash, address extraContract ) internal { require(extraContract.isContract(), "Given address is not a contract"); require(!registryContracts[chainHash][extraContract], "Extra contract is already registered"); require(!registryContracts[bytes32(0)][extraContract], "Extra contract is already registered for all chains"); registryContracts[chainHash][extraContract] = true; } function _removeExtraContract( bytes32 chainHash, address extraContract ) internal { require(registryContracts[chainHash][extraContract], "Extra contract is not registered"); delete registryContracts[chainHash][extraContract]; } function _getGasPayer( bytes32 schainHash, Message calldata message, uint counter ) internal returns (address) { try IGasReimbursable(message.destinationContract).gasPayer{gas: gasLimit}( schainHash, message.sender, message.data ) returns (address receiver) { return receiver; } catch Error(string memory reason) { emit PostMessageError( counter, bytes(reason) ); return address(0); } catch (bytes memory revertData) { emit PostMessageError( counter, revertData ); return address(0); } } /** * @dev Returns hash of message array. */ function _hashedArray(Message[] calldata messages) internal pure returns (bytes32) { bytes memory data; for (uint256 i = 0; i < messages.length; i++) { data = abi.encodePacked( data, bytes32(bytes20(messages[i].sender)), bytes32(bytes20(messages[i].destinationContract)), messages[i].data ); } return keccak256(data); } } // SPDX-License-Identifier: AGPL-3.0-only /* CommunityPool.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "@skalenetwork/skale-manager-interfaces/IWallets.sol"; import "../Messages.sol"; import "./MessageProxyForMainnet.sol"; import "./Linker.sol"; /** * @title CommunityPool * @dev Contract contains logic to perform automatic self-recharging ether for nodes */ contract CommunityPool is Twin { using AddressUpgradeable for address payable; bytes32 public constant CONSTANT_SETTER_ROLE = keccak256("CONSTANT_SETTER_ROLE"); mapping(address => mapping(bytes32 => uint)) private _userWallets; mapping(address => mapping(bytes32 => bool)) public activeUsers; uint public minTransactionGas; event MinTransactionGasWasChanged( uint oldValue, uint newValue ); function initialize( IContractManager contractManagerOfSkaleManagerValue, Linker linker, MessageProxyForMainnet messageProxyValue ) external initializer { Twin.initialize(contractManagerOfSkaleManagerValue, messageProxyValue); _setupRole(LINKER_ROLE, address(linker)); minTransactionGas = 1e6; } function refundGasByUser( bytes32 schainHash, address payable node, address user, uint gas ) external onlyMessageProxy returns (uint) { require(node != address(0), "Node address must be set"); if (!activeUsers[user][schainHash]) { return gas; } uint amount = tx.gasprice * gas; if (amount > _userWallets[user][schainHash]) { amount = _userWallets[user][schainHash]; } _userWallets[user][schainHash] = _userWallets[user][schainHash] - amount; if (!_balanceIsSufficient(schainHash, user, 0)) { activeUsers[user][schainHash] = false; messageProxy.postOutgoingMessage( schainHash, schainLinks[schainHash], Messages.encodeLockUserMessage(user) ); } node.sendValue(amount); return (tx.gasprice * gas - amount) / tx.gasprice; } function refundGasBySchainWallet( bytes32 schainHash, address payable node, uint gas ) external onlyMessageProxy returns (bool) { if (gas > 0) { IWallets(contractManagerOfSkaleManager.getContract("Wallets")).refundGasBySchain( schainHash, node, gas, false ); } return true; } /** * @dev Allows `msg.sender` to recharge their wallet for further gas reimbursement. * * Requirements: * * - 'msg.sender` should recharge their gas wallet for amount that enough to reimburse any * transaction from schain to mainnet. */ function rechargeUserWallet(string calldata schainName, address user) external payable { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require( _balanceIsSufficient(schainHash, msg.sender, msg.value), "Not enough ETH for transaction" ); _userWallets[user][schainHash] = _userWallets[user][schainHash] + msg.value; if (!activeUsers[user][schainHash]) { activeUsers[user][schainHash] = true; messageProxy.postOutgoingMessage( schainHash, schainLinks[schainHash], Messages.encodeActivateUserMessage(user) ); } } function withdrawFunds(string calldata schainName, uint amount) external { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require(amount <= _userWallets[msg.sender][schainHash], "Balance is too low"); _userWallets[msg.sender][schainHash] = _userWallets[msg.sender][schainHash] - amount; if ( !_balanceIsSufficient(schainHash, msg.sender, 0) && activeUsers[msg.sender][schainHash] ) { activeUsers[msg.sender][schainHash] = false; messageProxy.postOutgoingMessage( schainHash, schainLinks[schainHash], Messages.encodeLockUserMessage(msg.sender) ); } payable(msg.sender).sendValue(amount); } function setMinTransactionGas(uint newMinTransactionGas) external { require(hasRole(CONSTANT_SETTER_ROLE, msg.sender), "CONSTANT_SETTER_ROLE is required"); emit MinTransactionGasWasChanged(minTransactionGas, newMinTransactionGas); minTransactionGas = newMinTransactionGas; } function getBalance(address user, string calldata schainName) external view returns (uint) { return _userWallets[user][keccak256(abi.encodePacked(schainName))]; } function checkUserBalance(bytes32 schainHash, address receiver) external view returns (bool) { return activeUsers[receiver][schainHash] && _balanceIsSufficient(schainHash, receiver, 0); } function _balanceIsSufficient(bytes32 schainHash, address receiver, uint256 delta) private view returns (bool) { return delta + _userWallets[receiver][schainHash] >= minTransactionGas * tx.gasprice; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./AccessControlUpgradeable.sol"; import "../utils/structs/EnumerableSetUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerableUpgradeable { function getRoleMember(bytes32 role, uint256 index) external view returns (address); function getRoleMemberCount(bytes32 role) external view returns (uint256); } /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable { function __AccessControlEnumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); } function __AccessControlEnumerable_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {grantRole} to track enumerable memberships */ function grantRole(bytes32 role, address account) public virtual override { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {renounceRole} to track enumerable memberships */ function renounceRole(bytes32 role, address account) public virtual override { super.renounceRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {_setupRole} to track enumerable memberships */ function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } uint256[49] private __gap; } // SPDX-License-Identifier: AGPL-3.0-only /** * IMessageReceiver.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Dmytro Stebaiev * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; interface IMessageReceiver { function postMessage( bytes32 schainHash, address sender, bytes calldata data ) external returns (address); } // SPDX-License-Identifier: AGPL-3.0-only /** * IGasReimbursable.sol - SKALE Interchain Messaging Agent * Copyright (C) 2021-Present SKALE Labs * @author Artem Payvin * * SKALE IMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SKALE IMA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.8.6; import "./IMessageReceiver.sol"; interface IGasReimbursable is IMessageReceiver { function gasPayer( bytes32 schainHash, address sender, bytes calldata data ) external returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: AGPL-3.0-only /* IContractManager.sol - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IContractManager { function setContractsAddress(string calldata contractsName, address newContractsAddress) external; function getContract(string calldata name) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-only /* ISchainsInternal - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface ISchainsInternal { function isNodeAddressesInGroup(bytes32 schainId, address sender) external view returns (bool); function isOwnerAddress(address from, bytes32 schainId) external view returns (bool); }
Sets messageGasCost to a new value Requirements: - `msg.sender` must be granted as CONSTANT_SETTER_ROLE./
function setNewMessageGasCost(uint256 newMessageGasCost) external onlyConstantSetter { emit GasCostMessageWasChanged(messageGasCost, newMessageGasCost); messageGasCost = newMessageGasCost; }
22,512
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./SwapUtils.sol"; /** * @title AmplificationUtils library * @notice A library to calculate and ramp the A parameter of a given `SwapUtils.Swap` struct. * This library assumes the struct is fully validated. */ library AmplificationUtils { using SafeMath for uint256; event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); // Constant values used in ramping A calculations uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days; /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function getA(SwapUtils.Swap storage self) external view returns (uint256) { return _getAPrecise(self).div(A_PRECISION); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function getAPrecise(SwapUtils.Swap storage self) external view returns (uint256) { return _getAPrecise(self); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function _getAPrecise(SwapUtils.Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } } /** * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_ * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param self Swap struct to update * @param futureA_ the new A to ramp towards * @param futureTime_ timestamp when the new A should be reached */ function rampA( SwapUtils.Swap storage self, uint256 futureA_, uint256 futureTime_ ) external { require( block.timestamp >= self.initialATime.add(1 days), "Wait 1 day before starting ramp" ); require( futureTime_ >= block.timestamp.add(MIN_RAMP_TIME), "Insufficient ramp time" ); require( futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A" ); uint256 initialAPrecise = _getAPrecise(self); uint256 futureAPrecise = futureA_.mul(A_PRECISION); if (futureAPrecise < initialAPrecise) { require( futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise, "futureA_ is too small" ); } else { require( futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE), "futureA_ is too large" ); } self.initialA = initialAPrecise; self.futureA = futureAPrecise; self.initialATime = block.timestamp; self.futureATime = futureTime_; emit RampA( initialAPrecise, futureAPrecise, block.timestamp, futureTime_ ); } /** * @notice Stops ramping A immediately. Once this function is called, rampA() * cannot be called for another 24 hours * @param self Swap struct to update */ function stopRampA(SwapUtils.Swap storage self) external { require(self.futureATime > block.timestamp, "Ramp is already stopped"); uint256 currentA = _getAPrecise(self); self.initialA = currentA; self.futureA = currentA; self.initialATime = block.timestamp; self.futureATime = block.timestamp; emit StopRampA(currentA, block.timestamp); } } // 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.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./AmplificationUtils.sol"; import "./LPToken.sol"; import "./MathUtils.sol"; /** * @title SwapUtils library * @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities. * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library SwapUtils { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); struct Swap { // variables around the ramp management of A, // the amplification coefficient * n * (n - 1) // see https://www.curve.fi/stableswap-paper.pdf for details uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime; // fee calculation uint256 swapFee; uint256 adminFee; LPToken lpToken; // contract references for all tokens being pooled IERC20[] pooledTokens; // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 uint256[] tokenPrecisionMultipliers; // the pool balance of each token, in the token's precision // the contract's actual token balance might differ uint256[] balances; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; } // Struct storing variables used in calculations in the // {add,remove}Liquidity functions to avoid stack too deep errors struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; LPToken lpToken; uint256 totalSupply; uint256[] balances; uint256[] multipliers; } // the precision all pools tokens will be converted to uint8 public constant POOL_PRECISION_DECIMALS = 18; // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Max swap fee is 1% or 100bps of each swap uint256 public constant MAX_SWAP_FEE = 10**8; // Max adminFee is 100% of the swapFee // adminFee does not add additional fee on top of swapFee // Instead it takes a certain % of the swapFee. Therefore it has no impact on the // users but only on the earnings of LPs uint256 public constant MAX_ADMIN_FEE = 10**10; // Constant value used as max loop limit uint256 private constant MAX_LOOP_LIMIT = 256; /*** VIEW & PURE FUNCTIONS ***/ function _getAPrecise(Swap storage self) internal view returns (uint256) { return AmplificationUtils._getAPrecise(self); } /** * @notice Calculate the dy, the amount of selected token that user receives and * the fee of withdrawing in one token * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @param self Swap struct to read from * @return the amount of token user will receive */ function calculateWithdrawOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256) { (uint256 availableTokenAmount, ) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, self.lpToken.totalSupply() ); return availableTokenAmount; } function _calculateWithdrawOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 totalSupply ) internal view returns (uint256, uint256) { uint256 dy; uint256 newY; uint256 currentY; (dy, newY, currentY) = calculateWithdrawOneTokenDY( self, tokenIndex, tokenAmount, totalSupply ); // dy_0 (without fees) // dy, dy_0 - dy uint256 dySwapFee = currentY .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @return the d and the new y after withdrawing one token */ function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 totalSupply ) internal view returns ( uint256, uint256, uint256 ) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self); require(tokenIndex < xp.length, "Token index out of range"); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0); v.preciseA = _getAPrecise(self); v.d0 = getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply)); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = _feePerToken(self.swapFee, xp.length); for (uint256 i = 0; i < xp.length; i++) { uint256 xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = xpi.sub( ( (i == tokenIndex) ? xpi.mul(v.d1).div(v.d0).sub(v.newY) : xpi.sub(xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY, xp[tokenIndex]); } /** * @notice Calculate the price of a token in the pool with given * precision-adjusted balances and a particular D. * * @dev This is accomplished via solving the invariant iteratively. * See the StableSwap paper and Curve.fi implementation for further details. * * x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A) * x_1**2 + b*x_1 = c * x_1 = (x_1**2 + c) / (2*x_1 + b) * * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details. * @param tokenIndex Index of token we are calculating for. * @param xp a precision-adjusted set of pool balances. Array should be * the same cardinality as the pool. * @param d the stableswap invariant * @return the price of the token, in the same precision as in xp */ function getYD( uint256 a, uint8 tokenIndex, uint256[] memory xp, uint256 d ) internal pure returns (uint256) { uint256 numTokens = xp.length; require(tokenIndex < numTokens, "Token not found"); uint256 c = d; uint256 s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < numTokens; i++) { if (i != tokenIndex) { s = s.add(xp[i]); c = c.mul(d).div(xp[i].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } } c = c.mul(d).mul(AmplificationUtils.A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(AmplificationUtils.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. * @param xp a precision-adjusted set of pool balances. Array should be the same cardinality * as the pool. * @param a the amplification coefficient * n * (n - 1) in A_PRECISION. * See the StableSwap paper for details * @return the invariant, at the precision of the pool */ function getD(uint256[] memory xp, uint256 a) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s; for (uint256 i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD; uint256 d = s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = d; for (uint256 j = 0; j < numTokens; j++) { dP = dP.mul(d).div(xp[j].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // dP = dP * D * D * D * ... overflow! } prevD = d; d = nA .mul(s) .div(AmplificationUtils.A_PRECISION) .add(dP.mul(numTokens)) .mul(d) .div( nA .sub(AmplificationUtils.A_PRECISION) .mul(d) .div(AmplificationUtils.A_PRECISION) .add(numTokens.add(1).mul(dP)) ); if (d.within1(prevD)) { return d; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("D does not converge"); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers ) internal pure returns (uint256[] memory) { uint256 numTokens = balances.length; require( numTokens == precisionMultipliers.length, "Balances must match multipliers" ); uint256[] memory xp = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { xp[i] = balances[i].mul(precisionMultipliers[i]); } return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenPrecisionMultipliers); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS */ function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); LPToken lpToken = self.lpToken; uint256 supply = lpToken.totalSupply(); if (supply > 0) { return d.mul(10**uint256(POOL_PRECISION_DECIMALS)).div(supply); } return 0; } /** * @notice Calculate the new balances of the tokens given the indexes of the token * that is swapped from (FROM) and the token that is swapped to (TO). * This function is used as a helper function to calculate how much TO token * the user should receive on swap. * * @param preciseA precise form of amplification coefficient * @param tokenIndexFrom index of FROM token * @param tokenIndexTo index of TO token * @param x the new total amount of FROM token * @param xp balances of the tokens in the pool * @return the amount of TO token that should remain in the pool */ function getY( uint256 preciseA, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 x, uint256[] memory xp ) internal pure returns (uint256) { uint256 numTokens = xp.length; require( tokenIndexFrom != tokenIndexTo, "Can't compare token to itself" ); require( tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool" ); uint256 d = getD(xp, preciseA); uint256 c = d; uint256 s; uint256 nA = numTokens.mul(preciseA); uint256 _x; for (uint256 i = 0; i < numTokens; i++) { if (i == tokenIndexFrom) { _x = x; } else if (i != tokenIndexTo) { _x = xp[i]; } else { continue; } s = s.add(_x); c = c.mul(d).div(_x.mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } c = c.mul(d).mul(AmplificationUtils.A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(AmplificationUtils.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; // iterative approximation for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Externally calculates a swap between two tokens. * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, self.balances ); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get * @return dyFee the associated fee */ function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256[] memory balances ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256[] memory xp = _xp(balances, multipliers); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 x = dx.mul(multipliers[tokenIndexFrom]).add(xp[tokenIndexFrom]); uint256 y = getY( _getAPrecise(self), tokenIndexFrom, tokenIndexTo, x, xp ); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(multipliers[tokenIndexTo]); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * * @param amount the amount of LP tokens that would to be burned on * withdrawal * @return array of amounts of tokens user will receive */ function calculateRemoveLiquidity(Swap storage self, uint256 amount) external view returns (uint256[] memory) { return _calculateRemoveLiquidity( self.balances, amount, self.lpToken.totalSupply() ); } function _calculateRemoveLiquidity( uint256[] memory balances, uint256 amount, uint256 totalSupply ) internal pure returns (uint256[] memory) { require(amount <= totalSupply, "Cannot exceed total supply"); uint256[] memory amounts = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { amounts[i] = balances[i].mul(amount).div(totalSupply); } return amounts; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( Swap storage self, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 a = _getAPrecise(self); uint256[] memory balances = self.balances; uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256 d0 = getD(_xp(balances, multipliers), a); for (uint256 i = 0; i < balances.length; i++) { if (deposit) { balances[i] = balances[i].add(amounts[i]); } else { balances[i] = balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } } uint256 d1 = getD(_xp(balances, multipliers), a); uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0); } } /** * @notice return accumulated amount of admin fees of the token with given index * @param self Swap struct to read from * @param index Index of the pooled token * @return admin balance in the token's precision */ function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) { require(index < self.pooledTokens.length, "Token index out of range"); return self.pooledTokens[index].balanceOf(address(this)).sub( self.balances[index] ); } /** * @notice internal helper function to calculate fee per token multiplier used in * swap fee calculations * @param swapFee swap fee for the tokens * @param numTokens number of tokens pooled */ function _feePerToken(uint256 swapFee, uint256 numTokens) internal pure returns (uint256) { return swapFee.mul(numTokens).div(numTokens.sub(1).mul(4)); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = tokenFrom.balanceOf(address(this)); tokenFrom.safeTransferFrom(msg.sender, address(this), dx); // Use the actual transferred amount for AMM math dx = tokenFrom.balanceOf(address(this)).sub(beforeBalance); } uint256 dy; uint256 dyFee; uint256[] memory balances = self.balances; (dy, dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, balances ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = balances[tokenIndexFrom].add(dx); self.balances[tokenIndexTo] = balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap(msg.sender, dx, dy, tokenIndexFrom, tokenIndexTo); return dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( Swap storage self, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); } uint256[] memory newBalances = new uint256[](pooledTokens.length); for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = pooledTokens[i].balanceOf( address(this) ); pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } newBalances[i] = v.balances[i].add(amounts[i]); } // invariant after change v.d1 = getD(_xp(newBalances, v.multipliers), v.preciseA); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; uint256[] memory fees = new uint256[](pooledTokens.length); if (v.totalSupply != 0) { uint256 feePerToken = _feePerToken( self.swapFee, pooledTokens.length ); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); newBalances[i] = newBalances[i].sub(fees[i]); } v.d2 = getD(_xp(newBalances, v.multipliers), v.preciseA); } else { // the initial depositor doesn't pay fees self.balances = newBalances; } uint256 toMint; if (v.totalSupply == 0) { toMint = v.d1; } else { toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0); } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens v.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, v.d1, v.totalSupply.add(toMint) ); return toMint; } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param self Swap struct to read from and write to * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @return amounts of tokens the user received */ function removeLiquidity( Swap storage self, uint256 amount, uint256[] calldata minAmounts ) external returns (uint256[] memory) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(amount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require( minAmounts.length == pooledTokens.length, "minAmounts must match poolTokens" ); uint256[] memory balances = self.balances; uint256 totalSupply = lpToken.totalSupply(); uint256[] memory amounts = _calculateRemoveLiquidity( balances, amount, totalSupply ); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]"); self.balances[i] = balances[i].sub(amounts[i]); pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } lpToken.burnFrom(msg.sender, amount); emit RemoveLiquidity(msg.sender, amounts, totalSupply.sub(amount)); return amounts; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < pooledTokens.length, "Token not found"); uint256 totalSupply = lpToken.totalSupply(); (uint256 dy, uint256 dyFee) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, totalSupply ); require(dy >= minAmount, "dy < minAmount"); self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); lpToken.burnFrom(msg.sender, tokenAmount); pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( Swap storage self, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts should match pool tokens" ); require( maxBurnAmount <= v.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf" ); uint256 feePerToken = _feePerToken(self.swapFee, pooledTokens.length); uint256[] memory fees = new uint256[](pooledTokens.length); { uint256[] memory balances1 = new uint256[](pooledTokens.length); v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { balances1[i] = v.balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = getD(_xp(balances1, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = getD(_xp(balances1, v.multipliers), v.preciseA); } uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); tokenAmount = tokenAmount.add(1); require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < pooledTokens.length; i++) { pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, v.totalSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice withdraw all admin fees to a given address * @param self Swap struct to withdraw fees from * @param to Address to send the fees to */ function withdrawAdminFees(Swap storage self, address to) external { IERC20[] memory pooledTokens = self.pooledTokens; for (uint256 i = 0; i < pooledTokens.length; i++) { IERC20 token = pooledTokens[i]; uint256 balance = token.balanceOf(address(this)).sub( self.balances[i] ); if (balance != 0) { token.safeTransfer(to, balance); } } } /** * @notice Sets the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * @param self Swap struct to update * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(Swap storage self, uint256 newAdminFee) external { require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high"); self.adminFee = newAdminFee; emit NewAdminFee(newAdminFee); } /** * @notice update the swap fee * @dev fee cannot be higher than 1% of each swap * @param self Swap struct to update * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(Swap storage self, uint256 newSwapFee) external { require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high"); self.swapFee = newSwapFee; emit NewSwapFee(newSwapFee); } } // 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; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/ISwap.sol"; /** * @title Liquidity Provider Token * @notice This token is an ERC20 detailed token with added capability to be minted by the owner. * It is used to represent user's shares when providing liquidity to swap contracts. * @dev Only Swap contracts should initialize and own LPToken contracts. */ contract LPToken is ERC20BurnableUpgradeable, OwnableUpgradeable { using SafeMathUpgradeable for uint256; /** * @notice Initializes this LPToken contract with the given name and symbol * @dev The caller of this function will become the owner. A Swap contract should call this * in its initializer function. * @param name name of this token * @param symbol symbol of this token */ function initialize(string memory name, string memory symbol) external initializer returns (bool) { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); __Ownable_init_unchained(); return true; } /** * @notice Mints the given amount of LPToken to the recipient. * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint */ function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "LPToken: cannot mint 0"); _mint(recipient, amount); } /** * @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including * minting and burning. This ensures that Swap.updateUserWithdrawFees are called everytime. * This assumes the owner is set to a Swap contract's address. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable) { super._beforeTokenTransfer(from, to, amount); require(to != address(this), "LPToken: cannot send to itself"); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title MathUtils library * @notice A library to be used in conjunction with SafeMath. Contains functions for calculating * differences between two uint256. */ library MathUtils { /** * @notice Compares a and b and returns true if the difference between a and b * is less than 1 or equal to each other. * @param a uint256 to compare with * @param b uint256 to compare with * @return True if the difference between a and b is less than 1 or equal, * otherwise return false */ function within1(uint256 a, uint256 b) internal pure returns (bool) { return (difference(a, b) <= 1); } /** * @notice Calculates absolute difference between a and b * @param a uint256 to compare with * @param b uint256 to compare with * @return Difference between a and b */ function difference(uint256 a, uint256 b) internal pure returns (uint256) { if (a > b) { return a - b; } return b - a; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./ERC20Upgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable { function __ERC20Burnable_init() internal initializer { __Context_init_unchained(); __ERC20Burnable_init_unchained(); } function __ERC20Burnable_init_unchained() internal initializer { } using SafeMathUpgradeable for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./IAllowlist.sol"; interface ISwap { // pool data view functions function getA() external view returns (uint256); function getAllowlist() external view returns (IAllowlist); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); function swapStorage() external view returns ( uint256, uint256, uint256, uint256, uint256, uint256, address ); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function initialize( IERC20[] memory pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 a, uint256 fee, uint256 adminFee, address lpTokenTargetAddress ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with 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 ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.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 SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IAllowlist { function getPoolAccountLimit(address poolAddress) external view returns (uint256); function getPoolCap(address poolAddress) external view returns (uint256); function verifyAddress(address account, bytes32[] calldata merkleProof) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "./OwnerPausableUpgradeable.sol"; import "./SwapUtils.sol"; import "./AmplificationUtils.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract Swap is OwnerPausableUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; using SwapUtils for SwapUtils.Swap; using AmplificationUtils for SwapUtils.Swap; // Struct storing data responsible for automatic market maker functionalities. In order to // access this data, this contract uses SwapUtils library. For more details, see SwapUtils.sol SwapUtils.Swap public swapStorage; // Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool. // getTokenIndex function also relies on this mapping to retrieve token index. mapping(address => uint8) private tokenIndexes; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) public virtual initializer { __OwnerPausable_init(); __ReentrancyGuard_init(); // Check _pooledTokens and precisions parameter require(_pooledTokens.length > 1, "_pooledTokens.length <= 1"); require(_pooledTokens.length <= 32, "_pooledTokens.length > 32"); require( _pooledTokens.length == decimals.length, "_pooledTokens decimals mismatch" ); uint256[] memory precisionMultipliers = new uint256[](decimals.length); for (uint8 i = 0; i < _pooledTokens.length; i++) { if (i > 0) { // Check if index is already used. Check if 0th element is a duplicate. require( tokenIndexes[address(_pooledTokens[i])] == 0 && _pooledTokens[0] != _pooledTokens[i], "Duplicate tokens" ); } require( address(_pooledTokens[i]) != address(0), "The 0 address isn't an ERC-20" ); require( decimals[i] <= SwapUtils.POOL_PRECISION_DECIMALS, "Token decimals exceeds max" ); precisionMultipliers[i] = 10 ** uint256(SwapUtils.POOL_PRECISION_DECIMALS).sub( uint256(decimals[i]) ); tokenIndexes[address(_pooledTokens[i])] = i; } // Check _a, _fee, _adminFee, _withdrawFee parameters require(_a < AmplificationUtils.MAX_A, "_a exceeds maximum"); require(_fee < SwapUtils.MAX_SWAP_FEE, "_fee exceeds maximum"); require( _adminFee < SwapUtils.MAX_ADMIN_FEE, "_adminFee exceeds maximum" ); // Clone and initialize a LPToken contract LPToken lpToken = LPToken(Clones.clone(lpTokenTargetAddress)); require( lpToken.initialize(lpTokenName, lpTokenSymbol), "could not init lpToken clone" ); // Initialize swapStorage struct swapStorage.lpToken = lpToken; swapStorage.pooledTokens = _pooledTokens; swapStorage.tokenPrecisionMultipliers = precisionMultipliers; swapStorage.balances = new uint256[](_pooledTokens.length); swapStorage.initialA = _a.mul(AmplificationUtils.A_PRECISION); swapStorage.futureA = _a.mul(AmplificationUtils.A_PRECISION); // swapStorage.initialATime = 0; // swapStorage.futureATime = 0; swapStorage.swapFee = _fee; swapStorage.adminFee = _adminFee; } /*** MODIFIERS ***/ /** * @notice Modifier to check deadline against current timestamp * @param deadline latest timestamp to accept this transaction */ modifier deadlineCheck(uint256 deadline) { require(block.timestamp <= deadline, "Deadline not met"); _; } /*** VIEW FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @return A parameter */ function getA() external view virtual returns (uint256) { return swapStorage.getA(); } /** * @notice Return A in its raw precision form * @dev See the StableSwap paper for details * @return A parameter in its raw precision form */ function getAPrecise() external view virtual returns (uint256) { return swapStorage.getAPrecise(); } /** * @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) public view virtual returns (IERC20) { require(index < swapStorage.pooledTokens.length, "Out of range"); return swapStorage.pooledTokens[index]; } /** * @notice Return the index of the given token address. Reverts if no matching * token is found. * @param tokenAddress address of the token * @return the index of the given token address */ function getTokenIndex(address tokenAddress) public view virtual returns (uint8) { uint8 index = tokenIndexes[tokenAddress]; require( address(getToken(index)) == tokenAddress, "Token does not exist" ); return index; } /** * @notice Return current balance of the pooled token at given index * @param index the index of the token * @return current balance of the pooled token at given index with token's native precision */ function getTokenBalance(uint8 index) external view virtual returns (uint256) { require(index < swapStorage.pooledTokens.length, "Index out of range"); return swapStorage.balances[index]; } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual returns (uint256) { return swapStorage.getVirtualPrice(); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view virtual returns (uint256) { return swapStorage.calculateTokenAmount(amounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(uint256 amount) external view virtual returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(amount); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view virtual returns (uint256 availableTokenAmount) { return swapStorage.calculateWithdrawOneToken(tokenAmount, tokenIndex); } /** * @notice This function reads the accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin's token balance in the token's precision */ function getAdminBalance(uint256 index) external view virtual returns (uint256) { return swapStorage.getAdminBalance(index); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.addLiquidity(amounts, minToMint); } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external virtual nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return swapStorage.removeLiquidity(amount, minAmounts); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /*** ADMIN FUNCTIONS ***/ /** * @notice Withdraw all admin fees to the contract owner */ function withdrawAdminFees() external onlyOwner { swapStorage.withdrawAdminFees(owner()); } /** * @notice Update the admin fee. Admin fee takes portion of the swap fee. * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(uint256 newAdminFee) external onlyOwner { swapStorage.setAdminFee(newAdminFee); } /** * @notice Update the swap fee to be applied on swaps * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(uint256 newSwapFee) external onlyOwner { swapStorage.setSwapFee(newSwapFee); } /** * @notice Start ramping up or down A parameter towards given futureA and futureTime * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param futureA the new A to ramp towards * @param futureTime timestamp when the new A should be reached */ function rampA(uint256 futureA, uint256 futureTime) external onlyOwner { swapStorage.rampA(futureA, futureTime); } /** * @notice Stop ramping A immediately. Reverts if ramp A is already stopped. */ function stopRampA() external onlyOwner { swapStorage.stopRampA(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `master`. * * This function uses the create opcode, which should never revert. */ function clone(address master) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `master`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `master` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address master, bytes32 salt, address deployer) internal pure returns (address predicted) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address master, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(master, salt, address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _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; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; /** * @title OwnerPausable * @notice An ownable contract allows the owner to pause and unpause the * contract without a delay. * @dev Only methods using the provided modifiers will be paused. */ abstract contract OwnerPausableUpgradeable is OwnableUpgradeable, PausableUpgradeable { function __OwnerPausable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); } /** * @notice Pause the contract. Revert if already paused. */ function pause() external onlyOwner { PausableUpgradeable._pause(); } /** * @notice Unpause the contract. Revert if already unpaused. */ function unpause() external onlyOwner { PausableUpgradeable._unpause(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT WITH AGPL-3.0-only pragma solidity 0.6.12; import "./Swap.sol"; import "./interfaces/IFlashLoanReceiver.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapFlashLoan is Swap { // Total fee that is charged on all flashloans in BPS. Borrowers must repay the amount plus the flash loan fee. // This fee is split between the protocol and the pool. uint256 public flashLoanFeeBPS; // Share of the flash loan fee that goes to the protocol in BPS. A portion of each flash loan fee is allocated // to the protocol rather than the pool. uint256 public protocolFeeShareBPS; // Max BPS for limiting flash loan fee settings. uint256 public constant MAX_BPS = 10000; /*** EVENTS ***/ event FlashLoan( address indexed receiver, uint8 tokenIndex, uint256 amount, uint256 amountFee, uint256 protocolFee ); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) public virtual override initializer { Swap.initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress ); flashLoanFeeBPS = 8; // 8 bps protocolFeeShareBPS = 0; // 0 bps } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Borrow the specified token from this pool for this transaction only. This function will call * `IFlashLoanReceiver(receiver).executeOperation` and the `receiver` must return the full amount of the token * and the associated fee by the end of the callback transaction. If the conditions are not met, this call * is reverted. * @param receiver the address of the receiver of the token. This address must implement the IFlashLoanReceiver * interface and the callback function `executeOperation`. * @param token the protocol fee in bps to be applied on the total flash loan fee * @param amount the total amount to borrow in this transaction * @param params optional data to pass along to the callback function */ function flashLoan( address receiver, IERC20 token, uint256 amount, bytes memory params ) external nonReentrant { uint8 tokenIndex = getTokenIndex(address(token)); uint256 availableLiquidityBefore = token.balanceOf(address(this)); uint256 protocolBalanceBefore = availableLiquidityBefore.sub( swapStorage.balances[tokenIndex] ); require( amount > 0 && availableLiquidityBefore >= amount, "invalid amount" ); // Calculate the additional amount of tokens the pool should end up with uint256 amountFee = amount.mul(flashLoanFeeBPS).div(10000); // Calculate the portion of the fee that will go to the protocol uint256 protocolFee = amountFee.mul(protocolFeeShareBPS).div(10000); require(amountFee > 0, "amount is small for a flashLoan"); // Transfer the requested amount of tokens token.safeTransfer(receiver, amount); // Execute callback function on receiver IFlashLoanReceiver(receiver).executeOperation( address(this), address(token), amount, amountFee, params ); uint256 availableLiquidityAfter = token.balanceOf(address(this)); require( availableLiquidityAfter >= availableLiquidityBefore.add(amountFee), "flashLoan fee is not met" ); swapStorage.balances[tokenIndex] = availableLiquidityAfter .sub(protocolBalanceBefore) .sub(protocolFee); emit FlashLoan(receiver, tokenIndex, amount, amountFee, protocolFee); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the flash loan fee parameters. This function can only be called by the owner. * @param newFlashLoanFeeBPS the total fee in bps to be applied on future flash loans * @param newProtocolFeeShareBPS the protocol fee in bps to be applied on the total flash loan fee */ function setFlashLoanFees( uint256 newFlashLoanFeeBPS, uint256 newProtocolFeeShareBPS ) external onlyOwner { require( newFlashLoanFeeBPS > 0 && newFlashLoanFeeBPS <= MAX_BPS && newProtocolFeeShareBPS <= MAX_BPS, "fees are not in valid range" ); flashLoanFeeBPS = newFlashLoanFeeBPS; protocolFeeShareBPS = newProtocolFeeShareBPS; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity 0.6.12; /** * @title IFlashLoanReceiver interface * @notice Interface for the Saddle fee IFlashLoanReceiver. Modified from Aave's IFlashLoanReceiver interface. * https://github.com/aave/aave-protocol/blob/4b4545fb583fd4f400507b10f3c3114f45b8a037/contracts/flashloan/interfaces/IFlashLoanReceiver.sol * @author Aave * @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract **/ interface IFlashLoanReceiver { function executeOperation( address pool, address token, uint256 amount, uint256 fee, bytes calldata params ) external; } // SPDX-License-Identifier: MIT WITH AGPL-3.0-only pragma solidity 0.6.12; import "./SwapV1.sol"; import "./interfaces/IFlashLoanReceiver.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapFlashLoanV1 is SwapV1 { // Total fee that is charged on all flashloans in BPS. Borrowers must repay the amount plus the flash loan fee. // This fee is split between the protocol and the pool. uint256 public flashLoanFeeBPS; // Share of the flash loan fee that goes to the protocol in BPS. A portion of each flash loan fee is allocated // to the protocol rather than the pool. uint256 public protocolFeeShareBPS; // Max BPS for limiting flash loan fee settings. uint256 public constant MAX_BPS = 10000; /*** EVENTS ***/ event FlashLoan( address indexed receiver, uint8 tokenIndex, uint256 amount, uint256 amountFee, uint256 protocolFee ); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param _withdrawFee default withdrawFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, address lpTokenTargetAddress ) public virtual override initializer { SwapV1.initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, _withdrawFee, lpTokenTargetAddress ); flashLoanFeeBPS = 8; // 8 bps protocolFeeShareBPS = 0; // 0 bps } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Borrow the specified token from this pool for this transaction only. This function will call * `IFlashLoanReceiver(receiver).executeOperation` and the `receiver` must return the full amount of the token * and the associated fee by the end of the callback transaction. If the conditions are not met, this call * is reverted. * @param receiver the address of the receiver of the token. This address must implement the IFlashLoanReceiver * interface and the callback function `executeOperation`. * @param token the protocol fee in bps to be applied on the total flash loan fee * @param amount the total amount to borrow in this transaction * @param params optional data to pass along to the callback function */ function flashLoan( address receiver, IERC20 token, uint256 amount, bytes memory params ) external nonReentrant { uint8 tokenIndex = getTokenIndex(address(token)); uint256 availableLiquidityBefore = token.balanceOf(address(this)); uint256 protocolBalanceBefore = availableLiquidityBefore.sub( swapStorage.balances[tokenIndex] ); require( amount > 0 && availableLiquidityBefore >= amount, "invalid amount" ); // Calculate the additional amount of tokens the pool should end up with uint256 amountFee = amount.mul(flashLoanFeeBPS).div(10000); // Calculate the portion of the fee that will go to the protocol uint256 protocolFee = amountFee.mul(protocolFeeShareBPS).div(10000); require(amountFee > 0, "amount is small for a flashLoan"); // Transfer the requested amount of tokens token.safeTransfer(receiver, amount); // Execute callback function on receiver IFlashLoanReceiver(receiver).executeOperation( address(this), address(token), amount, amountFee, params ); uint256 availableLiquidityAfter = token.balanceOf(address(this)); require( availableLiquidityAfter >= availableLiquidityBefore.add(amountFee), "flashLoan fee is not met" ); swapStorage.balances[tokenIndex] = availableLiquidityAfter .sub(protocolBalanceBefore) .sub(protocolFee); emit FlashLoan(receiver, tokenIndex, amount, amountFee, protocolFee); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the flash loan fee parameters. This function can only be called by the owner. * @param newFlashLoanFeeBPS the total fee in bps to be applied on future flash loans * @param newProtocolFeeShareBPS the protocol fee in bps to be applied on the total flash loan fee */ function setFlashLoanFees( uint256 newFlashLoanFeeBPS, uint256 newProtocolFeeShareBPS ) external onlyOwner { require( newFlashLoanFeeBPS > 0 && newFlashLoanFeeBPS <= MAX_BPS && newProtocolFeeShareBPS <= MAX_BPS, "fees are not in valid range" ); flashLoanFeeBPS = newFlashLoanFeeBPS; protocolFeeShareBPS = newProtocolFeeShareBPS; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "./OwnerPausableUpgradeable.sol"; import "./SwapUtilsV1.sol"; import "./AmplificationUtilsV1.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapV1 is OwnerPausableUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; using SwapUtilsV1 for SwapUtilsV1.Swap; using AmplificationUtilsV1 for SwapUtilsV1.Swap; // Struct storing data responsible for automatic market maker functionalities. In order to // access this data, this contract uses SwapUtils library. For more details, see SwapUtilsV1.sol SwapUtilsV1.Swap public swapStorage; // Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool. // getTokenIndex function also relies on this mapping to retrieve token index. mapping(address => uint8) private tokenIndexes; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param _withdrawFee default withdrawFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, address lpTokenTargetAddress ) public virtual initializer { __OwnerPausable_init(); __ReentrancyGuard_init(); // Check _pooledTokens and precisions parameter require(_pooledTokens.length > 1, "_pooledTokens.length <= 1"); require(_pooledTokens.length <= 32, "_pooledTokens.length > 32"); require( _pooledTokens.length == decimals.length, "_pooledTokens decimals mismatch" ); uint256[] memory precisionMultipliers = new uint256[](decimals.length); for (uint8 i = 0; i < _pooledTokens.length; i++) { if (i > 0) { // Check if index is already used. Check if 0th element is a duplicate. require( tokenIndexes[address(_pooledTokens[i])] == 0 && _pooledTokens[0] != _pooledTokens[i], "Duplicate tokens" ); } require( address(_pooledTokens[i]) != address(0), "The 0 address isn't an ERC-20" ); require( decimals[i] <= SwapUtilsV1.POOL_PRECISION_DECIMALS, "Token decimals exceeds max" ); precisionMultipliers[i] = 10 ** uint256(SwapUtilsV1.POOL_PRECISION_DECIMALS).sub( uint256(decimals[i]) ); tokenIndexes[address(_pooledTokens[i])] = i; } // Check _a, _fee, _adminFee, _withdrawFee parameters require(_a < AmplificationUtilsV1.MAX_A, "_a exceeds maximum"); require(_fee < SwapUtilsV1.MAX_SWAP_FEE, "_fee exceeds maximum"); require( _adminFee < SwapUtilsV1.MAX_ADMIN_FEE, "_adminFee exceeds maximum" ); require( _withdrawFee < SwapUtilsV1.MAX_WITHDRAW_FEE, "_withdrawFee exceeds maximum" ); // Clone and initialize a LPToken contract LPToken lpToken = LPToken(Clones.clone(lpTokenTargetAddress)); require( lpToken.initialize(lpTokenName, lpTokenSymbol), "could not init lpToken clone" ); // Initialize swapStorage struct swapStorage.lpToken = lpToken; swapStorage.pooledTokens = _pooledTokens; swapStorage.tokenPrecisionMultipliers = precisionMultipliers; swapStorage.balances = new uint256[](_pooledTokens.length); swapStorage.initialA = _a.mul(AmplificationUtilsV1.A_PRECISION); swapStorage.futureA = _a.mul(AmplificationUtilsV1.A_PRECISION); // swapStorage.initialATime = 0; // swapStorage.futureATime = 0; swapStorage.swapFee = _fee; swapStorage.adminFee = _adminFee; swapStorage.defaultWithdrawFee = _withdrawFee; } /*** MODIFIERS ***/ /** * @notice Modifier to check deadline against current timestamp * @param deadline latest timestamp to accept this transaction */ modifier deadlineCheck(uint256 deadline) { require(block.timestamp <= deadline, "Deadline not met"); _; } /*** VIEW FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @return A parameter */ function getA() external view virtual returns (uint256) { return swapStorage.getA(); } /** * @notice Return A in its raw precision form * @dev See the StableSwap paper for details * @return A parameter in its raw precision form */ function getAPrecise() external view virtual returns (uint256) { return swapStorage.getAPrecise(); } /** * @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) public view virtual returns (IERC20) { require(index < swapStorage.pooledTokens.length, "Out of range"); return swapStorage.pooledTokens[index]; } /** * @notice Return the index of the given token address. Reverts if no matching * token is found. * @param tokenAddress address of the token * @return the index of the given token address */ function getTokenIndex(address tokenAddress) public view virtual returns (uint8) { uint8 index = tokenIndexes[tokenAddress]; require( address(getToken(index)) == tokenAddress, "Token does not exist" ); return index; } /** * @notice Return timestamp of last deposit of given address * @return timestamp of the last deposit made by the given address */ function getDepositTimestamp(address user) external view virtual returns (uint256) { return swapStorage.getDepositTimestamp(user); } /** * @notice Return current balance of the pooled token at given index * @param index the index of the token * @return current balance of the pooled token at given index with token's native precision */ function getTokenBalance(uint8 index) external view virtual returns (uint256) { require(index < swapStorage.pooledTokens.length, "Index out of range"); return swapStorage.balances[index]; } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual returns (uint256) { return swapStorage.getVirtualPrice(); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param account address that is depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view virtual returns (uint256) { return swapStorage.calculateTokenAmount(account, amounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param account the address that is withdrawing tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(address account, uint256 amount) external view virtual returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(account, amount); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param account the address that is withdrawing tokens * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view virtual returns (uint256 availableTokenAmount) { return swapStorage.calculateWithdrawOneToken( account, tokenAmount, tokenIndex ); } /** * @notice Calculate the fee that is applied when the given user withdraws. The withdraw fee * decays linearly over period of 4 weeks. For example, depositing and withdrawing right away * will charge you the full amount of withdraw fee. But withdrawing after 4 weeks will charge you * no additional fees. * @dev returned value should be divided by FEE_DENOMINATOR to convert to correct decimals * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(address user) external view virtual returns (uint256) { return swapStorage.calculateCurrentWithdrawFee(user); } /** * @notice This function reads the accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin's token balance in the token's precision */ function getAdminBalance(uint256 index) external view virtual returns (uint256) { return swapStorage.getAdminBalance(index); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.addLiquidity(amounts, minToMint); } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external virtual nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return swapStorage.removeLiquidity(amount, minAmounts); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the user withdraw fee. This function can only be called by * the pool token. Should be used to update the withdraw fee on transfer of pool tokens. * Transferring your pool token will reset the 4 weeks period. If the recipient is already * holding some pool tokens, the withdraw fee will be discounted in respective amounts. * @param recipient address of the recipient of pool token * @param transferAmount amount of pool token to transfer */ function updateUserWithdrawFee(address recipient, uint256 transferAmount) external { require( msg.sender == address(swapStorage.lpToken), "Only callable by pool token" ); swapStorage.updateUserWithdrawFee(recipient, transferAmount); } /** * @notice Withdraw all admin fees to the contract owner */ function withdrawAdminFees() external onlyOwner { swapStorage.withdrawAdminFees(owner()); } /** * @notice Update the admin fee. Admin fee takes portion of the swap fee. * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(uint256 newAdminFee) external onlyOwner { swapStorage.setAdminFee(newAdminFee); } /** * @notice Update the swap fee to be applied on swaps * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(uint256 newSwapFee) external onlyOwner { swapStorage.setSwapFee(newSwapFee); } /** * @notice Update the withdraw fee. This fee decays linearly over 4 weeks since * user's last deposit. * @param newWithdrawFee new withdraw fee to be applied on future deposits */ function setDefaultWithdrawFee(uint256 newWithdrawFee) external onlyOwner { swapStorage.setDefaultWithdrawFee(newWithdrawFee); } /** * @notice Start ramping up or down A parameter towards given futureA and futureTime * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param futureA the new A to ramp towards * @param futureTime timestamp when the new A should be reached */ function rampA(uint256 futureA, uint256 futureTime) external onlyOwner { swapStorage.rampA(futureA, futureTime); } /** * @notice Stop ramping A immediately. Reverts if ramp A is already stopped. */ function stopRampA() external onlyOwner { swapStorage.stopRampA(); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./AmplificationUtilsV1.sol"; import "./LPToken.sol"; import "./MathUtils.sol"; /** * @title SwapUtils library * @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities. * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library SwapUtilsV1 { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); struct Swap { // variables around the ramp management of A, // the amplification coefficient * n * (n - 1) // see https://www.curve.fi/stableswap-paper.pdf for details uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime; // fee calculation uint256 swapFee; uint256 adminFee; uint256 defaultWithdrawFee; LPToken lpToken; // contract references for all tokens being pooled IERC20[] pooledTokens; // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 uint256[] tokenPrecisionMultipliers; // the pool balance of each token, in the token's precision // the contract's actual token balance might differ uint256[] balances; mapping(address => uint256) depositTimestamp; mapping(address => uint256) withdrawFeeMultiplier; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; } // Struct storing variables used in calculations in the // {add,remove}Liquidity functions to avoid stack too deep errors struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; LPToken lpToken; uint256 totalSupply; uint256[] balances; uint256[] multipliers; } // the precision all pools tokens will be converted to uint8 public constant POOL_PRECISION_DECIMALS = 18; // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Max swap fee is 1% or 100bps of each swap uint256 public constant MAX_SWAP_FEE = 10**8; // Max adminFee is 100% of the swapFee // adminFee does not add additional fee on top of swapFee // Instead it takes a certain % of the swapFee. Therefore it has no impact on the // users but only on the earnings of LPs uint256 public constant MAX_ADMIN_FEE = 10**10; // Max withdrawFee is 1% of the value withdrawn // Fee will be redistributed to the LPs in the pool, rewarding // long term providers. uint256 public constant MAX_WITHDRAW_FEE = 10**8; // Constant value used as max loop limit uint256 private constant MAX_LOOP_LIMIT = 256; // Time that it should take for the withdraw fee to fully decay to 0 uint256 public constant WITHDRAW_FEE_DECAY_TIME = 4 weeks; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Retrieves the timestamp of last deposit made by the given address * @param self Swap struct to read from * @return timestamp of last deposit */ function getDepositTimestamp(Swap storage self, address user) external view returns (uint256) { return self.depositTimestamp[user]; } function _getAPrecise(Swap storage self) internal view returns (uint256) { return AmplificationUtilsV1._getAPrecise(self); } /** * @notice Calculate the dy, the amount of selected token that user receives and * the fee of withdrawing in one token * @param account the address that is withdrawing * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @param self Swap struct to read from * @return the amount of token user will receive */ function calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256) { (uint256 availableTokenAmount, ) = _calculateWithdrawOneToken( self, account, tokenAmount, tokenIndex, self.lpToken.totalSupply() ); return availableTokenAmount; } function _calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex, uint256 totalSupply ) internal view returns (uint256, uint256) { uint256 dy; uint256 newY; uint256 currentY; (dy, newY, currentY) = calculateWithdrawOneTokenDY( self, tokenIndex, tokenAmount, totalSupply ); // dy_0 (without fees) // dy, dy_0 - dy uint256 dySwapFee = currentY .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); dy = dy .mul( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @return the d and the new y after withdrawing one token */ function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 totalSupply ) internal view returns ( uint256, uint256, uint256 ) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self); require(tokenIndex < xp.length, "Token index out of range"); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0); v.preciseA = _getAPrecise(self); v.d0 = getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply)); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = _feePerToken(self.swapFee, xp.length); for (uint256 i = 0; i < xp.length; i++) { uint256 xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = xpi.sub( ( (i == tokenIndex) ? xpi.mul(v.d1).div(v.d0).sub(v.newY) : xpi.sub(xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY, xp[tokenIndex]); } /** * @notice Calculate the price of a token in the pool with given * precision-adjusted balances and a particular D. * * @dev This is accomplished via solving the invariant iteratively. * See the StableSwap paper and Curve.fi implementation for further details. * * x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A) * x_1**2 + b*x_1 = c * x_1 = (x_1**2 + c) / (2*x_1 + b) * * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details. * @param tokenIndex Index of token we are calculating for. * @param xp a precision-adjusted set of pool balances. Array should be * the same cardinality as the pool. * @param d the stableswap invariant * @return the price of the token, in the same precision as in xp */ function getYD( uint256 a, uint8 tokenIndex, uint256[] memory xp, uint256 d ) internal pure returns (uint256) { uint256 numTokens = xp.length; require(tokenIndex < numTokens, "Token not found"); uint256 c = d; uint256 s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < numTokens; i++) { if (i != tokenIndex) { s = s.add(xp[i]); c = c.mul(d).div(xp[i].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } } c = c.mul(d).mul(AmplificationUtilsV1.A_PRECISION).div( nA.mul(numTokens) ); uint256 b = s.add(d.mul(AmplificationUtilsV1.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. * @param xp a precision-adjusted set of pool balances. Array should be the same cardinality * as the pool. * @param a the amplification coefficient * n * (n - 1) in A_PRECISION. * See the StableSwap paper for details * @return the invariant, at the precision of the pool */ function getD(uint256[] memory xp, uint256 a) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s; for (uint256 i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD; uint256 d = s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = d; for (uint256 j = 0; j < numTokens; j++) { dP = dP.mul(d).div(xp[j].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // dP = dP * D * D * D * ... overflow! } prevD = d; d = nA .mul(s) .div(AmplificationUtilsV1.A_PRECISION) .add(dP.mul(numTokens)) .mul(d) .div( nA .sub(AmplificationUtilsV1.A_PRECISION) .mul(d) .div(AmplificationUtilsV1.A_PRECISION) .add(numTokens.add(1).mul(dP)) ); if (d.within1(prevD)) { return d; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("D does not converge"); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers ) internal pure returns (uint256[] memory) { uint256 numTokens = balances.length; require( numTokens == precisionMultipliers.length, "Balances must match multipliers" ); uint256[] memory xp = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { xp[i] = balances[i].mul(precisionMultipliers[i]); } return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenPrecisionMultipliers); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS */ function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); LPToken lpToken = self.lpToken; uint256 supply = lpToken.totalSupply(); if (supply > 0) { return d.mul(10**uint256(POOL_PRECISION_DECIMALS)).div(supply); } return 0; } /** * @notice Calculate the new balances of the tokens given the indexes of the token * that is swapped from (FROM) and the token that is swapped to (TO). * This function is used as a helper function to calculate how much TO token * the user should receive on swap. * * @param preciseA precise form of amplification coefficient * @param tokenIndexFrom index of FROM token * @param tokenIndexTo index of TO token * @param x the new total amount of FROM token * @param xp balances of the tokens in the pool * @return the amount of TO token that should remain in the pool */ function getY( uint256 preciseA, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 x, uint256[] memory xp ) internal pure returns (uint256) { uint256 numTokens = xp.length; require( tokenIndexFrom != tokenIndexTo, "Can't compare token to itself" ); require( tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool" ); uint256 d = getD(xp, preciseA); uint256 c = d; uint256 s; uint256 nA = numTokens.mul(preciseA); uint256 _x; for (uint256 i = 0; i < numTokens; i++) { if (i == tokenIndexFrom) { _x = x; } else if (i != tokenIndexTo) { _x = xp[i]; } else { continue; } s = s.add(_x); c = c.mul(d).div(_x.mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } c = c.mul(d).mul(AmplificationUtilsV1.A_PRECISION).div( nA.mul(numTokens) ); uint256 b = s.add(d.mul(AmplificationUtilsV1.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; // iterative approximation for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Externally calculates a swap between two tokens. * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, self.balances ); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get * @return dyFee the associated fee */ function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256[] memory balances ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256[] memory xp = _xp(balances, multipliers); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 x = dx.mul(multipliers[tokenIndexFrom]).add(xp[tokenIndexFrom]); uint256 y = getY( _getAPrecise(self), tokenIndexFrom, tokenIndexTo, x, xp ); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(multipliers[tokenIndexTo]); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * * @param account the address that is removing liquidity. required for withdraw fee calculation * @param amount the amount of LP tokens that would to be burned on * withdrawal * @return array of amounts of tokens user will receive */ function calculateRemoveLiquidity( Swap storage self, address account, uint256 amount ) external view returns (uint256[] memory) { return _calculateRemoveLiquidity( self, self.balances, account, amount, self.lpToken.totalSupply() ); } function _calculateRemoveLiquidity( Swap storage self, uint256[] memory balances, address account, uint256 amount, uint256 totalSupply ) internal view returns (uint256[] memory) { require(amount <= totalSupply, "Cannot exceed total supply"); uint256 feeAdjustedAmount = amount .mul( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); uint256[] memory amounts = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { amounts[i] = balances[i].mul(feeAdjustedAmount).div(totalSupply); } return amounts; } /** * @notice Calculate the fee that is applied when the given user withdraws. * Withdraw fee decays linearly over WITHDRAW_FEE_DECAY_TIME. * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(Swap storage self, address user) external view returns (uint256) { return _calculateCurrentWithdrawFee(self, user); } function _calculateCurrentWithdrawFee(Swap storage self, address user) internal view returns (uint256) { uint256 endTime = self.depositTimestamp[user].add( WITHDRAW_FEE_DECAY_TIME ); if (endTime > block.timestamp) { uint256 timeLeftover = endTime.sub(block.timestamp); return self .defaultWithdrawFee .mul(self.withdrawFeeMultiplier[user]) .mul(timeLeftover) .div(WITHDRAW_FEE_DECAY_TIME) .div(FEE_DENOMINATOR); } return 0; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param account address of the account depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( Swap storage self, address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 a = _getAPrecise(self); uint256[] memory balances = self.balances; uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256 d0 = getD(_xp(balances, multipliers), a); for (uint256 i = 0; i < balances.length; i++) { if (deposit) { balances[i] = balances[i].add(amounts[i]); } else { balances[i] = balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } } uint256 d1 = getD(_xp(balances, multipliers), a); uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub( _calculateCurrentWithdrawFee(self, account) ) ); } } /** * @notice return accumulated amount of admin fees of the token with given index * @param self Swap struct to read from * @param index Index of the pooled token * @return admin balance in the token's precision */ function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) { require(index < self.pooledTokens.length, "Token index out of range"); return self.pooledTokens[index].balanceOf(address(this)).sub( self.balances[index] ); } /** * @notice internal helper function to calculate fee per token multiplier used in * swap fee calculations * @param swapFee swap fee for the tokens * @param numTokens number of tokens pooled */ function _feePerToken(uint256 swapFee, uint256 numTokens) internal pure returns (uint256) { return swapFee.mul(numTokens).div(numTokens.sub(1).mul(4)); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = tokenFrom.balanceOf(address(this)); tokenFrom.safeTransferFrom(msg.sender, address(this), dx); // Use the actual transferred amount for AMM math dx = tokenFrom.balanceOf(address(this)).sub(beforeBalance); } uint256 dy; uint256 dyFee; uint256[] memory balances = self.balances; (dy, dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, balances ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = balances[tokenIndexFrom].add(dx); self.balances[tokenIndexTo] = balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap(msg.sender, dx, dy, tokenIndexFrom, tokenIndexTo); return dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( Swap storage self, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); } uint256[] memory newBalances = new uint256[](pooledTokens.length); for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = pooledTokens[i].balanceOf( address(this) ); pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } newBalances[i] = v.balances[i].add(amounts[i]); } // invariant after change v.d1 = getD(_xp(newBalances, v.multipliers), v.preciseA); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; uint256[] memory fees = new uint256[](pooledTokens.length); if (v.totalSupply != 0) { uint256 feePerToken = _feePerToken( self.swapFee, pooledTokens.length ); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); newBalances[i] = newBalances[i].sub(fees[i]); } v.d2 = getD(_xp(newBalances, v.multipliers), v.preciseA); } else { // the initial depositor doesn't pay fees self.balances = newBalances; } uint256 toMint; if (v.totalSupply == 0) { toMint = v.d1; } else { toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0); } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens v.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, v.d1, v.totalSupply.add(toMint) ); return toMint; } /** * @notice Update the withdraw fee for `user`. If the user is currently * not providing liquidity in the pool, sets to default value. If not, recalculate * the starting withdraw fee based on the last deposit's time & amount relative * to the new deposit. * * @param self Swap struct to read from and write to * @param user address of the user depositing tokens * @param toMint amount of pool tokens to be minted */ function updateUserWithdrawFee( Swap storage self, address user, uint256 toMint ) public { // If token is transferred to address 0 (or burned), don't update the fee. if (user == address(0)) { return; } if (self.defaultWithdrawFee == 0) { // If current fee is set to 0%, set multiplier to FEE_DENOMINATOR self.withdrawFeeMultiplier[user] = FEE_DENOMINATOR; } else { // Otherwise, calculate appropriate discount based on last deposit amount uint256 currentFee = _calculateCurrentWithdrawFee(self, user); uint256 currentBalance = self.lpToken.balanceOf(user); // ((currentBalance * currentFee) + (toMint * defaultWithdrawFee)) * FEE_DENOMINATOR / // ((toMint + currentBalance) * defaultWithdrawFee) self.withdrawFeeMultiplier[user] = currentBalance .mul(currentFee) .add(toMint.mul(self.defaultWithdrawFee)) .mul(FEE_DENOMINATOR) .div(toMint.add(currentBalance).mul(self.defaultWithdrawFee)); } self.depositTimestamp[user] = block.timestamp; } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param self Swap struct to read from and write to * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @return amounts of tokens the user received */ function removeLiquidity( Swap storage self, uint256 amount, uint256[] calldata minAmounts ) external returns (uint256[] memory) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(amount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require( minAmounts.length == pooledTokens.length, "minAmounts must match poolTokens" ); uint256[] memory balances = self.balances; uint256 totalSupply = lpToken.totalSupply(); uint256[] memory amounts = _calculateRemoveLiquidity( self, balances, msg.sender, amount, totalSupply ); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]"); self.balances[i] = balances[i].sub(amounts[i]); pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } lpToken.burnFrom(msg.sender, amount); emit RemoveLiquidity(msg.sender, amounts, totalSupply.sub(amount)); return amounts; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < pooledTokens.length, "Token not found"); uint256 totalSupply = lpToken.totalSupply(); (uint256 dy, uint256 dyFee) = _calculateWithdrawOneToken( self, msg.sender, tokenAmount, tokenIndex, totalSupply ); require(dy >= minAmount, "dy < minAmount"); self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); lpToken.burnFrom(msg.sender, tokenAmount); pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( Swap storage self, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts should match pool tokens" ); require( maxBurnAmount <= v.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf" ); uint256 feePerToken = _feePerToken(self.swapFee, pooledTokens.length); uint256[] memory fees = new uint256[](pooledTokens.length); { uint256[] memory balances1 = new uint256[](pooledTokens.length); v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { balances1[i] = v.balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = getD(_xp(balances1, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = getD(_xp(balances1, v.multipliers), v.preciseA); } uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); tokenAmount = tokenAmount.add(1).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, msg.sender)) ); require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < pooledTokens.length; i++) { pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, v.totalSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice withdraw all admin fees to a given address * @param self Swap struct to withdraw fees from * @param to Address to send the fees to */ function withdrawAdminFees(Swap storage self, address to) external { IERC20[] memory pooledTokens = self.pooledTokens; for (uint256 i = 0; i < pooledTokens.length; i++) { IERC20 token = pooledTokens[i]; uint256 balance = token.balanceOf(address(this)).sub( self.balances[i] ); if (balance != 0) { token.safeTransfer(to, balance); } } } /** * @notice Sets the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * @param self Swap struct to update * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(Swap storage self, uint256 newAdminFee) external { require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high"); self.adminFee = newAdminFee; emit NewAdminFee(newAdminFee); } /** * @notice update the swap fee * @dev fee cannot be higher than 1% of each swap * @param self Swap struct to update * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(Swap storage self, uint256 newSwapFee) external { require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high"); self.swapFee = newSwapFee; emit NewSwapFee(newSwapFee); } /** * @notice update the default withdraw fee. This also affects deposits made in the past as well. * @param self Swap struct to update * @param newWithdrawFee new withdraw fee to be applied */ function setDefaultWithdrawFee(Swap storage self, uint256 newWithdrawFee) external { require(newWithdrawFee <= MAX_WITHDRAW_FEE, "Fee is too high"); self.defaultWithdrawFee = newWithdrawFee; emit NewWithdrawFee(newWithdrawFee); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./SwapUtilsV1.sol"; /** * @title AmplificationUtils library * @notice A library to calculate and ramp the A parameter of a given `SwapUtils.Swap` struct. * This library assumes the struct is fully validated. */ library AmplificationUtilsV1 { using SafeMath for uint256; event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); // Constant values used in ramping A calculations uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days; /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function getA(SwapUtilsV1.Swap storage self) external view returns (uint256) { return _getAPrecise(self).div(A_PRECISION); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function getAPrecise(SwapUtilsV1.Swap storage self) external view returns (uint256) { return _getAPrecise(self); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function _getAPrecise(SwapUtilsV1.Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } } /** * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_ * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param self Swap struct to update * @param futureA_ the new A to ramp towards * @param futureTime_ timestamp when the new A should be reached */ function rampA( SwapUtilsV1.Swap storage self, uint256 futureA_, uint256 futureTime_ ) external { require( block.timestamp >= self.initialATime.add(1 days), "Wait 1 day before starting ramp" ); require( futureTime_ >= block.timestamp.add(MIN_RAMP_TIME), "Insufficient ramp time" ); require( futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A" ); uint256 initialAPrecise = _getAPrecise(self); uint256 futureAPrecise = futureA_.mul(A_PRECISION); if (futureAPrecise < initialAPrecise) { require( futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise, "futureA_ is too small" ); } else { require( futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE), "futureA_ is too large" ); } self.initialA = initialAPrecise; self.futureA = futureAPrecise; self.initialATime = block.timestamp; self.futureATime = futureTime_; emit RampA( initialAPrecise, futureAPrecise, block.timestamp, futureTime_ ); } /** * @notice Stops ramping A immediately. Once this function is called, rampA() * cannot be called for another 24 hours * @param self Swap struct to update */ function stopRampA(SwapUtilsV1.Swap storage self) external { require(self.futureATime > block.timestamp, "Ramp is already stopped"); uint256 currentA = _getAPrecise(self); self.initialA = currentA; self.futureA = currentA; self.initialATime = block.timestamp; self.futureATime = block.timestamp; emit StopRampA(currentA, block.timestamp); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../LPToken.sol"; import "../interfaces/ISwap.sol"; import "../MathUtils.sol"; import "../SwapUtils.sol"; /** * @title MetaSwapUtils library * @notice A library to be used within MetaSwap.sol. Contains functions responsible for custody and AMM functionalities. * * MetaSwap is a modified version of Swap that allows Swap's LP token to be utilized in pooling with other tokens. * As an example, if there is a Swap pool consisting of [DAI, USDC, USDT]. Then a MetaSwap pool can be created * with [sUSD, BaseSwapLPToken] to allow trades between either the LP token or the underlying tokens and sUSD. * * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library MetaSwapUtils { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; using AmplificationUtils for SwapUtils.Swap; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event TokenSwapUnderlying( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); struct MetaSwap { // Meta-Swap related parameters ISwap baseSwap; uint256 baseVirtualPrice; uint256 baseCacheLastUpdated; IERC20[] baseTokens; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; uint256 xpi; } // Struct storing variables used in calculation in removeLiquidityImbalance function // to avoid stack too deep error struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; LPToken lpToken; uint256 totalSupply; uint256 preciseA; uint256 baseVirtualPrice; uint256[] tokenPrecisionMultipliers; uint256[] newBalances; } struct SwapUnderlyingInfo { uint256 x; uint256 dx; uint256 dy; uint256[] tokenPrecisionMultipliers; uint256[] oldBalances; IERC20[] baseTokens; IERC20 tokenFrom; uint8 metaIndexFrom; IERC20 tokenTo; uint8 metaIndexTo; uint256 baseVirtualPrice; } struct CalculateSwapUnderlyingInfo { uint256 baseVirtualPrice; ISwap baseSwap; uint8 baseLPTokenIndex; uint8 baseTokensLength; uint8 metaIndexTo; uint256 x; uint256 dy; } // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Cache expire time for the stored value of base Swap's virtual price uint256 public constant BASE_CACHE_EXPIRE_TIME = 10 minutes; uint256 public constant BASE_VIRTUAL_PRICE_PRECISION = 10**18; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Return the stored value of base Swap's virtual price. If * value was updated past BASE_CACHE_EXPIRE_TIME, then read it directly * from the base Swap contract. * @param metaSwapStorage MetaSwap struct to read from * @return base Swap's virtual price */ function _getBaseVirtualPrice(MetaSwap storage metaSwapStorage) internal view returns (uint256) { if ( block.timestamp > metaSwapStorage.baseCacheLastUpdated + BASE_CACHE_EXPIRE_TIME ) { return metaSwapStorage.baseSwap.getVirtualPrice(); } return metaSwapStorage.baseVirtualPrice; } function _getBaseSwapFee(ISwap baseSwap) internal view returns (uint256 swapFee) { (, , , , swapFee, , ) = baseSwap.swapStorage(); } /** * @notice Calculate how much the user would receive when withdrawing via single token * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct to read from * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @return dy the amount of token user will receive */ function calculateWithdrawOneToken( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 dy) { (dy, ) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, _getBaseVirtualPrice(metaSwapStorage), self.lpToken.totalSupply() ); } function _calculateWithdrawOneToken( SwapUtils.Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 baseVirtualPrice, uint256 totalSupply ) internal view returns (uint256, uint256) { uint256 dy; uint256 dySwapFee; { uint256 currentY; uint256 newY; // Calculate how much to withdraw (dy, newY, currentY) = _calculateWithdrawOneTokenDY( self, tokenIndex, tokenAmount, baseVirtualPrice, totalSupply ); // Calculate the associated swap fee dySwapFee = currentY .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); } return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @param baseVirtualPrice the virtual price of the base swap's LP token * @return the dy excluding swap fee, the new y after withdrawing one token, and current y */ function _calculateWithdrawOneTokenDY( SwapUtils.Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 baseVirtualPrice, uint256 totalSupply ) internal view returns ( uint256, uint256, uint256 ) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self, baseVirtualPrice); require(tokenIndex < xp.length, "Token index out of range"); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo( 0, 0, 0, 0, self._getAPrecise(), 0 ); v.d0 = SwapUtils.getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply)); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = SwapUtils.getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = SwapUtils._feePerToken(self.swapFee, xp.length); for (uint256 i = 0; i < xp.length; i++) { v.xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = v.xpi.sub( ( (i == tokenIndex) ? v.xpi.mul(v.d1).div(v.d0).sub(v.newY) : v.xpi.sub(v.xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( SwapUtils.getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); if (tokenIndex == xp.length.sub(1)) { dy = dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(baseVirtualPrice); v.newY = v.newY.mul(BASE_VIRTUAL_PRICE_PRECISION).div( baseVirtualPrice ); xp[tokenIndex] = xp[tokenIndex] .mul(BASE_VIRTUAL_PRICE_PRECISION) .div(baseVirtualPrice); } dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY, xp[tokenIndex]); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. The last element will also get scaled up by * the given baseVirtualPrice. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @param baseVirtualPrice the base virtual price to scale the balance of the * base Swap's LP token. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers, uint256 baseVirtualPrice ) internal pure returns (uint256[] memory) { uint256[] memory xp = SwapUtils._xp(balances, precisionMultipliers); uint256 baseLPTokenIndex = balances.length.sub(1); xp[baseLPTokenIndex] = xp[baseLPTokenIndex].mul(baseVirtualPrice).div( BASE_VIRTUAL_PRICE_PRECISION ); return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(SwapUtils.Swap storage self, uint256 baseVirtualPrice) internal view returns (uint256[] memory) { return _xp( self.balances, self.tokenPrecisionMultipliers, baseVirtualPrice ); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct to read from * @return the virtual price, scaled to precision of BASE_VIRTUAL_PRICE_PRECISION */ function getVirtualPrice( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage ) external view returns (uint256) { uint256 d = SwapUtils.getD( _xp( self.balances, self.tokenPrecisionMultipliers, _getBaseVirtualPrice(metaSwapStorage) ), self._getAPrecise() ); uint256 supply = self.lpToken.totalSupply(); if (supply != 0) { return d.mul(BASE_VIRTUAL_PRICE_PRECISION).div(supply); } return 0; } /** * @notice Externally calculates a swap between two tokens. The SwapUtils.Swap storage and * MetaSwap storage should be from the same MetaSwap contract. * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct from the same contract * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, _getBaseVirtualPrice(metaSwapStorage) ); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param baseVirtualPrice the virtual price of the base LP token * @return dy the number of tokens the user will get and dyFee the associated fee */ function _calculateSwap( SwapUtils.Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 baseVirtualPrice ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory xp = _xp(self, baseVirtualPrice); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 baseLPTokenIndex = xp.length.sub(1); uint256 x = dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom]); if (tokenIndexFrom == baseLPTokenIndex) { // When swapping from a base Swap token, scale up dx by its virtual price x = x.mul(baseVirtualPrice).div(BASE_VIRTUAL_PRICE_PRECISION); } x = x.add(xp[tokenIndexFrom]); uint256 y = SwapUtils.getY( self._getAPrecise(), tokenIndexFrom, tokenIndexTo, x, xp ); dy = xp[tokenIndexTo].sub(y).sub(1); if (tokenIndexTo == baseLPTokenIndex) { // When swapping to a base Swap token, scale down dy by its virtual price dy = dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(baseVirtualPrice); } dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee); dy = dy.div(self.tokenPrecisionMultipliers[tokenIndexTo]); } /** * @notice Calculates the expected return amount from swapping between * the pooled tokens and the underlying tokens of the base Swap pool. * * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct from the same contract * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwapUnderlying( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256) { CalculateSwapUnderlyingInfo memory v = CalculateSwapUnderlyingInfo( _getBaseVirtualPrice(metaSwapStorage), metaSwapStorage.baseSwap, 0, uint8(metaSwapStorage.baseTokens.length), 0, 0, 0 ); uint256[] memory xp = _xp(self, v.baseVirtualPrice); v.baseLPTokenIndex = uint8(xp.length.sub(1)); { uint8 maxRange = v.baseLPTokenIndex + v.baseTokensLength; require( tokenIndexFrom < maxRange && tokenIndexTo < maxRange, "Token index out of range" ); } if (tokenIndexFrom < v.baseLPTokenIndex) { // tokenFrom is from this pool v.x = xp[tokenIndexFrom].add( dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom]) ); } else { // tokenFrom is from the base pool tokenIndexFrom = tokenIndexFrom - v.baseLPTokenIndex; if (tokenIndexTo < v.baseLPTokenIndex) { uint256[] memory baseInputs = new uint256[](v.baseTokensLength); baseInputs[tokenIndexFrom] = dx; v.x = v .baseSwap .calculateTokenAmount(baseInputs, true) .mul(v.baseVirtualPrice) .div(BASE_VIRTUAL_PRICE_PRECISION); // when adding to the base pool,you pay approx 50% of the swap fee v.x = v .x .sub( v.x.mul(_getBaseSwapFee(metaSwapStorage.baseSwap)).div( FEE_DENOMINATOR.mul(2) ) ) .add(xp[v.baseLPTokenIndex]); } else { // both from and to are from the base pool return v.baseSwap.calculateSwap( tokenIndexFrom, tokenIndexTo - v.baseLPTokenIndex, dx ); } tokenIndexFrom = v.baseLPTokenIndex; } v.metaIndexTo = v.baseLPTokenIndex; if (tokenIndexTo < v.baseLPTokenIndex) { v.metaIndexTo = tokenIndexTo; } { uint256 y = SwapUtils.getY( self._getAPrecise(), tokenIndexFrom, v.metaIndexTo, v.x, xp ); v.dy = xp[v.metaIndexTo].sub(y).sub(1); uint256 dyFee = v.dy.mul(self.swapFee).div(FEE_DENOMINATOR); v.dy = v.dy.sub(dyFee); } if (tokenIndexTo < v.baseLPTokenIndex) { // tokenTo is from this pool v.dy = v.dy.div(self.tokenPrecisionMultipliers[v.metaIndexTo]); } else { // tokenTo is from the base pool v.dy = v.baseSwap.calculateRemoveLiquidityOneToken( v.dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(v.baseVirtualPrice), tokenIndexTo - v.baseLPTokenIndex ); } return v.dy; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct to read from * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 a = self._getAPrecise(); uint256 d0; uint256 d1; { uint256 baseVirtualPrice = _getBaseVirtualPrice(metaSwapStorage); uint256[] memory balances1 = self.balances; uint256[] memory tokenPrecisionMultipliers = self .tokenPrecisionMultipliers; uint256 numTokens = balances1.length; d0 = SwapUtils.getD( _xp(balances1, tokenPrecisionMultipliers, baseVirtualPrice), a ); for (uint256 i = 0; i < numTokens; i++) { if (deposit) { balances1[i] = balances1[i].add(amounts[i]); } else { balances1[i] = balances1[i].sub( amounts[i], "Cannot withdraw more than available" ); } } d1 = SwapUtils.getD( _xp(balances1, tokenPrecisionMultipliers, baseVirtualPrice), a ); } uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0); } } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { uint256 pooledTokensLength = self.pooledTokens.length; require( tokenIndexFrom < pooledTokensLength && tokenIndexTo < pooledTokensLength, "Token index is out of range" ); } uint256 transferredDx; { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); { // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = tokenFrom.balanceOf(address(this)); tokenFrom.safeTransferFrom(msg.sender, address(this), dx); // Use the actual transferred amount for AMM math transferredDx = tokenFrom.balanceOf(address(this)).sub( beforeBalance ); } } (uint256 dy, uint256 dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, transferredDx, _updateBaseVirtualPrice(metaSwapStorage) ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = self.balances[tokenIndexFrom].add( transferredDx ); self.balances[tokenIndexTo] = self.balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap( msg.sender, transferredDx, dy, tokenIndexFrom, tokenIndexTo ); return dy; } /** * @notice Swaps with the underlying tokens of the base Swap pool. For this function, * the token indices are flattened out so that underlying tokens are represented * in the indices. * @dev Since this calls multiple external functions during the execution, * it is recommended to protect any function that depends on this with reentrancy guards. * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swapUnderlying( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { SwapUnderlyingInfo memory v = SwapUnderlyingInfo( 0, 0, 0, self.tokenPrecisionMultipliers, self.balances, metaSwapStorage.baseTokens, IERC20(address(0)), 0, IERC20(address(0)), 0, _updateBaseVirtualPrice(metaSwapStorage) ); uint8 baseLPTokenIndex = uint8(v.oldBalances.length.sub(1)); { uint8 maxRange = uint8(baseLPTokenIndex + v.baseTokens.length); require( tokenIndexFrom < maxRange && tokenIndexTo < maxRange, "Token index out of range" ); } ISwap baseSwap = metaSwapStorage.baseSwap; // Find the address of the token swapping from and the index in MetaSwap's token list if (tokenIndexFrom < baseLPTokenIndex) { v.tokenFrom = self.pooledTokens[tokenIndexFrom]; v.metaIndexFrom = tokenIndexFrom; } else { v.tokenFrom = v.baseTokens[tokenIndexFrom - baseLPTokenIndex]; v.metaIndexFrom = baseLPTokenIndex; } // Find the address of the token swapping to and the index in MetaSwap's token list if (tokenIndexTo < baseLPTokenIndex) { v.tokenTo = self.pooledTokens[tokenIndexTo]; v.metaIndexTo = tokenIndexTo; } else { v.tokenTo = v.baseTokens[tokenIndexTo - baseLPTokenIndex]; v.metaIndexTo = baseLPTokenIndex; } // Check for possible fee on transfer v.dx = v.tokenFrom.balanceOf(address(this)); v.tokenFrom.safeTransferFrom(msg.sender, address(this), dx); v.dx = v.tokenFrom.balanceOf(address(this)).sub(v.dx); // update dx in case of fee on transfer if ( tokenIndexFrom < baseLPTokenIndex || tokenIndexTo < baseLPTokenIndex ) { // Either one of the tokens belongs to the MetaSwap tokens list uint256[] memory xp = _xp( v.oldBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ); if (tokenIndexFrom < baseLPTokenIndex) { // Swapping from a MetaSwap token v.x = xp[tokenIndexFrom].add( dx.mul(v.tokenPrecisionMultipliers[tokenIndexFrom]) ); } else { // Swapping from one of the tokens hosted in the base Swap // This case requires adding the underlying token to the base Swap, then // using the base LP token to swap to the desired token uint256[] memory baseAmounts = new uint256[]( v.baseTokens.length ); baseAmounts[tokenIndexFrom - baseLPTokenIndex] = v.dx; // Add liquidity to the base Swap contract and receive base LP token v.dx = baseSwap.addLiquidity(baseAmounts, 0, block.timestamp); // Calculate the value of total amount of baseLPToken we end up with v.x = v .dx .mul(v.baseVirtualPrice) .div(BASE_VIRTUAL_PRICE_PRECISION) .add(xp[baseLPTokenIndex]); } // Calculate how much to withdraw in MetaSwap level and the the associated swap fee uint256 dyFee; { uint256 y = SwapUtils.getY( self._getAPrecise(), v.metaIndexFrom, v.metaIndexTo, v.x, xp ); v.dy = xp[v.metaIndexTo].sub(y).sub(1); if (tokenIndexTo >= baseLPTokenIndex) { // When swapping to a base Swap token, scale down dy by its virtual price v.dy = v.dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div( v.baseVirtualPrice ); } dyFee = v.dy.mul(self.swapFee).div(FEE_DENOMINATOR); v.dy = v.dy.sub(dyFee).div( v.tokenPrecisionMultipliers[v.metaIndexTo] ); } // Update the balances array according to the calculated input and output amount { uint256 dyAdminFee = dyFee.mul(self.adminFee).div( FEE_DENOMINATOR ); dyAdminFee = dyAdminFee.div( v.tokenPrecisionMultipliers[v.metaIndexTo] ); self.balances[v.metaIndexFrom] = v .oldBalances[v.metaIndexFrom] .add(v.dx); self.balances[v.metaIndexTo] = v .oldBalances[v.metaIndexTo] .sub(v.dy) .sub(dyAdminFee); } if (tokenIndexTo >= baseLPTokenIndex) { // When swapping to a token that belongs to the base Swap, burn the LP token // and withdraw the desired token from the base pool uint256 oldBalance = v.tokenTo.balanceOf(address(this)); baseSwap.removeLiquidityOneToken( v.dy, tokenIndexTo - baseLPTokenIndex, 0, block.timestamp ); v.dy = v.tokenTo.balanceOf(address(this)) - oldBalance; } // Check the amount of token to send meets minDy require(v.dy >= minDy, "Swap didn't result in min tokens"); } else { // Both tokens are from the base Swap pool // Do a swap through the base Swap v.dy = v.tokenTo.balanceOf(address(this)); baseSwap.swap( tokenIndexFrom - baseLPTokenIndex, tokenIndexTo - baseLPTokenIndex, v.dx, minDy, block.timestamp ); v.dy = v.tokenTo.balanceOf(address(this)).sub(v.dy); } // Send the desired token to the caller v.tokenTo.safeTransfer(msg.sender, v.dy); emit TokenSwapUnderlying( msg.sender, dx, v.dy, tokenIndexFrom, tokenIndexTo ); return v.dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); uint256[] memory fees = new uint256[](pooledTokens.length); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, self.lpToken, 0, self._getAPrecise(), _updateBaseVirtualPrice(metaSwapStorage), self.tokenPrecisionMultipliers, self.balances ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.d0 = SwapUtils.getD( _xp( v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ), v.preciseA ); } for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = pooledTokens[i].balanceOf( address(this) ); pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } v.newBalances[i] = v.newBalances[i].add(amounts[i]); } // invariant after change v.d1 = SwapUtils.getD( _xp(v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; uint256 toMint; if (v.totalSupply != 0) { uint256 feePerToken = SwapUtils._feePerToken( self.swapFee, pooledTokens.length ); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(self.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(v.newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = v.newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); v.newBalances[i] = v.newBalances[i].sub(fees[i]); } v.d2 = SwapUtils.getD( _xp( v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ), v.preciseA ); toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0); } else { // the initial depositor doesn't pay fees self.balances = v.newBalances; toMint = v.d1; } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens self.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, v.d1, v.totalSupply.add(toMint) ); return toMint; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; uint256 totalSupply = lpToken.totalSupply(); uint256 numTokens = self.pooledTokens.length; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < numTokens, "Token not found"); uint256 dyFee; uint256 dy; (dy, dyFee) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, _updateBaseVirtualPrice(metaSwapStorage), totalSupply ); require(dy >= minAmount, "dy < minAmount"); // Update balances array self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); // Burn the associated LP token from the caller and send the desired token lpToken.burnFrom(msg.sender, tokenAmount); self.pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { // Using this struct to avoid stack too deep error ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, self.lpToken, 0, self._getAPrecise(), _updateBaseVirtualPrice(metaSwapStorage), self.tokenPrecisionMultipliers, self.balances ); v.totalSupply = v.lpToken.totalSupply(); require( amounts.length == v.newBalances.length, "Amounts should match pool tokens" ); require(maxBurnAmount != 0, "Must burn more than 0"); uint256 feePerToken = SwapUtils._feePerToken( self.swapFee, v.newBalances.length ); // Calculate how much LPToken should be burned uint256[] memory fees = new uint256[](v.newBalances.length); { uint256[] memory balances1 = new uint256[](v.newBalances.length); v.d0 = SwapUtils.getD( _xp( v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ), v.preciseA ); for (uint256 i = 0; i < v.newBalances.length; i++) { balances1[i] = v.newBalances[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = SwapUtils.getD( _xp(balances1, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); for (uint256 i = 0; i < v.newBalances.length; i++) { uint256 idealBalance = v.d1.mul(v.newBalances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = SwapUtils.getD( _xp(balances1, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); } uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); // Scale up by withdraw fee tokenAmount = tokenAmount.add(1); // Check for max burn amount require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); // Burn the calculated amount of LPToken from the caller and send the desired tokens v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < v.newBalances.length; i++) { self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, v.totalSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice Determines if the stored value of base Swap's virtual price is expired. * If the last update was past the BASE_CACHE_EXPIRE_TIME, then update the stored value. * * @param metaSwapStorage MetaSwap struct to read from and write to * @return base Swap's virtual price */ function _updateBaseVirtualPrice(MetaSwap storage metaSwapStorage) internal returns (uint256) { if ( block.timestamp > metaSwapStorage.baseCacheLastUpdated + BASE_CACHE_EXPIRE_TIME ) { // When the cache is expired, update it uint256 baseVirtualPrice = ISwap(metaSwapStorage.baseSwap) .getVirtualPrice(); metaSwapStorage.baseVirtualPrice = baseVirtualPrice; metaSwapStorage.baseCacheLastUpdated = block.timestamp; return baseVirtualPrice; } else { return metaSwapStorage.baseVirtualPrice; } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "../LPToken.sol"; import "../interfaces/ISwap.sol"; import "../interfaces/IMetaSwap.sol"; /** * @title MetaSwapDeposit * @notice This contract flattens the LP token in a MetaSwap pool for easier user access. MetaSwap must be * deployed before this contract can be initialized successfully. * * For example, suppose there exists a base Swap pool consisting of [DAI, USDC, USDT]. * Then a MetaSwap pool can be created with [sUSD, BaseSwapLPToken] to allow trades between either * the LP token or the underlying tokens and sUSD. * * MetaSwapDeposit flattens the LP token and remaps them to a single array, allowing users * to ignore the dependency on BaseSwapLPToken. Using the above example, MetaSwapDeposit can act * as a Swap containing [sUSD, DAI, USDC, USDT] tokens. */ contract MetaSwapDeposit is Initializable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; ISwap public baseSwap; IMetaSwap public metaSwap; IERC20[] public baseTokens; IERC20[] public metaTokens; IERC20[] public tokens; IERC20 public metaLPToken; uint256 constant MAX_UINT256 = 2**256 - 1; struct RemoveLiquidityImbalanceInfo { ISwap baseSwap; IMetaSwap metaSwap; IERC20 metaLPToken; uint8 baseLPTokenIndex; bool withdrawFromBase; uint256 leftoverMetaLPTokenAmount; } /** * @notice Sets the address for the base Swap contract, MetaSwap contract, and the * MetaSwap LP token contract. * @param _baseSwap the address of the base Swap contract * @param _metaSwap the address of the MetaSwap contract * @param _metaLPToken the address of the MetaSwap LP token contract */ function initialize( ISwap _baseSwap, IMetaSwap _metaSwap, IERC20 _metaLPToken ) external initializer { __ReentrancyGuard_init(); // Check and approve base level tokens to be deposited to the base Swap contract { uint8 i; for (; i < 32; i++) { try _baseSwap.getToken(i) returns (IERC20 token) { baseTokens.push(token); token.safeApprove(address(_baseSwap), MAX_UINT256); token.safeApprove(address(_metaSwap), MAX_UINT256); } catch { break; } } require(i > 1, "baseSwap must have at least 2 tokens"); } // Check and approve meta level tokens to be deposited to the MetaSwap contract IERC20 baseLPToken; { uint8 i; for (; i < 32; i++) { try _metaSwap.getToken(i) returns (IERC20 token) { baseLPToken = token; metaTokens.push(token); tokens.push(token); token.safeApprove(address(_metaSwap), MAX_UINT256); } catch { break; } } require(i > 1, "metaSwap must have at least 2 tokens"); } // Flatten baseTokens and append it to tokens array tokens[tokens.length - 1] = baseTokens[0]; for (uint8 i = 1; i < baseTokens.length; i++) { tokens.push(baseTokens[i]); } // Approve base Swap LP token to be burned by the base Swap contract for withdrawing baseLPToken.safeApprove(address(_baseSwap), MAX_UINT256); // Approve MetaSwap LP token to be burned by the MetaSwap contract for withdrawing _metaLPToken.safeApprove(address(_metaSwap), MAX_UINT256); // Initialize storage variables baseSwap = _baseSwap; metaSwap = _metaSwap; metaLPToken = _metaLPToken; } // Mutative functions /** * @notice Swap two underlying tokens using the meta pool and the base pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external nonReentrant returns (uint256) { tokens[tokenIndexFrom].safeTransferFrom(msg.sender, address(this), dx); uint256 tokenToAmount = metaSwap.swapUnderlying( tokenIndexFrom, tokenIndexTo, dx, minDy, deadline ); tokens[tokenIndexTo].safeTransfer(msg.sender, tokenToAmount); return tokenToAmount; } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external nonReentrant returns (uint256) { // Read to memory to save on gas IERC20[] memory memBaseTokens = baseTokens; IERC20[] memory memMetaTokens = metaTokens; uint256 baseLPTokenIndex = memMetaTokens.length - 1; require(amounts.length == memBaseTokens.length + baseLPTokenIndex); uint256 baseLPTokenAmount; { // Transfer base tokens from the caller and deposit to the base Swap pool uint256[] memory baseAmounts = new uint256[](memBaseTokens.length); bool shouldDepositBaseTokens; for (uint8 i = 0; i < memBaseTokens.length; i++) { IERC20 token = memBaseTokens[i]; uint256 depositAmount = amounts[baseLPTokenIndex + i]; if (depositAmount > 0) { token.safeTransferFrom( msg.sender, address(this), depositAmount ); baseAmounts[i] = token.balanceOf(address(this)); // account for any fees on transfer // if there are any base Swap level tokens, flag it for deposits shouldDepositBaseTokens = true; } } if (shouldDepositBaseTokens) { // Deposit any base Swap level tokens and receive baseLPToken baseLPTokenAmount = baseSwap.addLiquidity( baseAmounts, 0, deadline ); } } uint256 metaLPTokenAmount; { // Transfer remaining meta level tokens from the caller uint256[] memory metaAmounts = new uint256[](metaTokens.length); for (uint8 i = 0; i < baseLPTokenIndex; i++) { IERC20 token = memMetaTokens[i]; uint256 depositAmount = amounts[i]; if (depositAmount > 0) { token.safeTransferFrom( msg.sender, address(this), depositAmount ); metaAmounts[i] = token.balanceOf(address(this)); // account for any fees on transfer } } // Update the baseLPToken amount that will be deposited metaAmounts[baseLPTokenIndex] = baseLPTokenAmount; // Deposit the meta level tokens and the baseLPToken metaLPTokenAmount = metaSwap.addLiquidity( metaAmounts, minToMint, deadline ); } // Transfer the meta lp token to the caller metaLPToken.safeTransfer(msg.sender, metaLPTokenAmount); return metaLPTokenAmount; } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external nonReentrant returns (uint256[] memory) { IERC20[] memory memBaseTokens = baseTokens; IERC20[] memory memMetaTokens = metaTokens; uint256[] memory totalRemovedAmounts; { uint256 numOfAllTokens = memBaseTokens.length + memMetaTokens.length - 1; require(minAmounts.length == numOfAllTokens, "out of range"); totalRemovedAmounts = new uint256[](numOfAllTokens); } // Transfer meta lp token from the caller to this metaLPToken.safeTransferFrom(msg.sender, address(this), amount); uint256 baseLPTokenAmount; { // Remove liquidity from the MetaSwap pool uint256[] memory removedAmounts; uint256 baseLPTokenIndex = memMetaTokens.length - 1; { uint256[] memory metaMinAmounts = new uint256[]( memMetaTokens.length ); for (uint8 i = 0; i < baseLPTokenIndex; i++) { metaMinAmounts[i] = minAmounts[i]; } removedAmounts = metaSwap.removeLiquidity( amount, metaMinAmounts, deadline ); } // Send the meta level tokens to the caller for (uint8 i = 0; i < baseLPTokenIndex; i++) { totalRemovedAmounts[i] = removedAmounts[i]; memMetaTokens[i].safeTransfer(msg.sender, removedAmounts[i]); } baseLPTokenAmount = removedAmounts[baseLPTokenIndex]; // Remove liquidity from the base Swap pool { uint256[] memory baseMinAmounts = new uint256[]( memBaseTokens.length ); for (uint8 i = 0; i < baseLPTokenIndex; i++) { baseMinAmounts[i] = minAmounts[baseLPTokenIndex + i]; } removedAmounts = baseSwap.removeLiquidity( baseLPTokenAmount, baseMinAmounts, deadline ); } // Send the base level tokens to the caller for (uint8 i = 0; i < memBaseTokens.length; i++) { totalRemovedAmounts[baseLPTokenIndex + i] = removedAmounts[i]; memBaseTokens[i].safeTransfer(msg.sender, removedAmounts[i]); } } return totalRemovedAmounts; } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external nonReentrant returns (uint256) { uint8 baseLPTokenIndex = uint8(metaTokens.length - 1); uint8 baseTokensLength = uint8(baseTokens.length); // Transfer metaLPToken from the caller metaLPToken.safeTransferFrom(msg.sender, address(this), tokenAmount); IERC20 token; if (tokenIndex < baseLPTokenIndex) { // When the desired token is meta level token, we can just call `removeLiquidityOneToken` directly metaSwap.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount, deadline ); token = metaTokens[tokenIndex]; } else if (tokenIndex < baseLPTokenIndex + baseTokensLength) { // When the desired token is a base level token, we need to first withdraw via baseLPToken, then withdraw // the desired token from the base Swap contract. uint256 removedBaseLPTokenAmount = metaSwap.removeLiquidityOneToken( tokenAmount, baseLPTokenIndex, 0, deadline ); baseSwap.removeLiquidityOneToken( removedBaseLPTokenAmount, tokenIndex - baseLPTokenIndex, minAmount, deadline ); token = baseTokens[tokenIndex - baseLPTokenIndex]; } else { revert("out of range"); } uint256 amountWithdrawn = token.balanceOf(address(this)); token.safeTransfer(msg.sender, amountWithdrawn); return amountWithdrawn; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external nonReentrant returns (uint256) { IERC20[] memory memBaseTokens = baseTokens; IERC20[] memory memMetaTokens = metaTokens; uint256[] memory metaAmounts = new uint256[](memMetaTokens.length); uint256[] memory baseAmounts = new uint256[](memBaseTokens.length); require( amounts.length == memBaseTokens.length + memMetaTokens.length - 1, "out of range" ); RemoveLiquidityImbalanceInfo memory v = RemoveLiquidityImbalanceInfo( baseSwap, metaSwap, metaLPToken, uint8(metaAmounts.length - 1), false, 0 ); for (uint8 i = 0; i < v.baseLPTokenIndex; i++) { metaAmounts[i] = amounts[i]; } for (uint8 i = 0; i < baseAmounts.length; i++) { baseAmounts[i] = amounts[v.baseLPTokenIndex + i]; if (baseAmounts[i] > 0) { v.withdrawFromBase = true; } } // Calculate how much base LP token we need to get the desired amount of underlying tokens if (v.withdrawFromBase) { metaAmounts[v.baseLPTokenIndex] = v .baseSwap .calculateTokenAmount(baseAmounts, false) .mul(10005) .div(10000); } // Transfer MetaSwap LP token from the caller to this contract v.metaLPToken.safeTransferFrom( msg.sender, address(this), maxBurnAmount ); // Withdraw the paired meta level tokens and the base LP token from the MetaSwap pool uint256 burnedMetaLPTokenAmount = v.metaSwap.removeLiquidityImbalance( metaAmounts, maxBurnAmount, deadline ); v.leftoverMetaLPTokenAmount = maxBurnAmount.sub( burnedMetaLPTokenAmount ); // If underlying tokens are desired, withdraw them from the base Swap pool if (v.withdrawFromBase) { v.baseSwap.removeLiquidityImbalance( baseAmounts, metaAmounts[v.baseLPTokenIndex], deadline ); // Base Swap may require LESS base LP token than the amount we have // In that case, deposit it to the MetaSwap pool. uint256[] memory leftovers = new uint256[](metaAmounts.length); IERC20 baseLPToken = memMetaTokens[v.baseLPTokenIndex]; uint256 leftoverBaseLPTokenAmount = baseLPToken.balanceOf( address(this) ); if (leftoverBaseLPTokenAmount > 0) { leftovers[v.baseLPTokenIndex] = leftoverBaseLPTokenAmount; v.leftoverMetaLPTokenAmount = v.leftoverMetaLPTokenAmount.add( v.metaSwap.addLiquidity(leftovers, 0, deadline) ); } } // Transfer all withdrawn tokens to the caller for (uint8 i = 0; i < amounts.length; i++) { IERC20 token; if (i < v.baseLPTokenIndex) { token = memMetaTokens[i]; } else { token = memBaseTokens[i - v.baseLPTokenIndex]; } if (amounts[i] > 0) { token.safeTransfer(msg.sender, amounts[i]); } } // If there were any extra meta lp token, transfer them back to the caller as well if (v.leftoverMetaLPTokenAmount > 0) { v.metaLPToken.safeTransfer(msg.sender, v.leftoverMetaLPTokenAmount); } return maxBurnAmount - v.leftoverMetaLPTokenAmount; } // VIEW FUNCTIONS /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running. When withdrawing from the base pool in imbalanced * fashion, the recommended slippage setting is 0.2% or higher. * * @dev This shouldn't be used outside frontends for user estimates. * * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256) { uint256[] memory metaAmounts = new uint256[](metaTokens.length); uint256[] memory baseAmounts = new uint256[](baseTokens.length); uint256 baseLPTokenIndex = metaAmounts.length - 1; for (uint8 i = 0; i < baseLPTokenIndex; i++) { metaAmounts[i] = amounts[i]; } for (uint8 i = 0; i < baseAmounts.length; i++) { baseAmounts[i] = amounts[baseLPTokenIndex + i]; } uint256 baseLPTokenAmount = baseSwap.calculateTokenAmount( baseAmounts, deposit ); metaAmounts[baseLPTokenIndex] = baseLPTokenAmount; return metaSwap.calculateTokenAmount(metaAmounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory) { uint256[] memory metaAmounts = metaSwap.calculateRemoveLiquidity( amount ); uint8 baseLPTokenIndex = uint8(metaAmounts.length - 1); uint256[] memory baseAmounts = baseSwap.calculateRemoveLiquidity( metaAmounts[baseLPTokenIndex] ); uint256[] memory totalAmounts = new uint256[]( baseLPTokenIndex + baseAmounts.length ); for (uint8 i = 0; i < baseLPTokenIndex; i++) { totalAmounts[i] = metaAmounts[i]; } for (uint8 i = 0; i < baseAmounts.length; i++) { totalAmounts[baseLPTokenIndex + i] = baseAmounts[i]; } return totalAmounts; } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256) { uint8 baseLPTokenIndex = uint8(metaTokens.length - 1); if (tokenIndex < baseLPTokenIndex) { return metaSwap.calculateRemoveLiquidityOneToken( tokenAmount, tokenIndex ); } else { uint256 baseLPTokenAmount = metaSwap .calculateRemoveLiquidityOneToken( tokenAmount, baseLPTokenIndex ); return baseSwap.calculateRemoveLiquidityOneToken( baseLPTokenAmount, tokenIndex - baseLPTokenIndex ); } } /** * @notice Returns the address of the pooled token at given index. Reverts if tokenIndex is out of range. * This is a flattened representation of the pooled tokens. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) external view returns (IERC20) { require(index < tokens.length, "index out of range"); return tokens[index]; } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256) { return metaSwap.calculateSwapUnderlying(tokenIndexFrom, tokenIndexTo, dx); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./ISwap.sol"; interface IMetaSwap { // pool data view functions function getA() external view returns (uint256); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateSwapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) external; function initializeMetaSwap( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress, ISwap baseSwap ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function swapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "./interfaces/ISwap.sol"; import "./interfaces/IMetaSwap.sol"; contract SwapDeployer is Ownable { event NewSwapPool( address indexed deployer, address swapAddress, IERC20[] pooledTokens ); event NewClone(address indexed target, address cloneAddress); constructor() public Ownable() {} function clone(address target) external returns (address) { address newClone = _clone(target); emit NewClone(target, newClone); return newClone; } function _clone(address target) internal returns (address) { return Clones.clone(target); } function deploy( address swapAddress, IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) external returns (address) { address swapClone = _clone(swapAddress); ISwap(swapClone).initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress ); Ownable(swapClone).transferOwnership(owner()); emit NewSwapPool(msg.sender, swapClone, _pooledTokens); return swapClone; } function deployMetaSwap( address metaSwapAddress, IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress, ISwap baseSwap ) external returns (address) { address metaSwapClone = _clone(metaSwapAddress); IMetaSwap(metaSwapClone).initializeMetaSwap( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress, baseSwap ); Ownable(metaSwapClone).transferOwnership(owner()); emit NewSwapPool(msg.sender, metaSwapClone, _pooledTokens); return metaSwapClone; } } // 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.12; import "synthetix/contracts/interfaces/ISynthetix.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "../interfaces/ISwap.sol"; /** * @title SynthSwapper * @notice Replacement of Virtual Synths in favor of gas savings. Allows swapping synths via the Synthetix protocol * or Saddle's pools. The `Bridge.sol` contract will deploy minimal clones of this contract upon initiating * any cross-asset swaps. */ contract SynthSwapper is Initializable { using SafeERC20 for IERC20; address payable owner; // SYNTHETIX points to `ProxyERC20` (0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F). // This contract is a proxy of `Synthetix` and is used to exchange synths. ISynthetix public constant SYNTHETIX = ISynthetix(0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F); // "SADDLE" in bytes32 form bytes32 public constant TRACKING = 0x534144444c450000000000000000000000000000000000000000000000000000; /** * @notice Initializes the contract when deploying this directly. This prevents * others from calling initialize() on the target contract and setting themself as the owner. */ constructor() public { initialize(); } /** * @notice This modifier checks if the caller is the owner */ modifier onlyOwner() { require(msg.sender == owner, "is not owner"); _; } /** * @notice Sets the `owner` as the caller of this function */ function initialize() public initializer { require(owner == address(0), "owner already set"); owner = msg.sender; } /** * @notice Swaps the synth to another synth via the Synthetix protocol. * @param sourceKey currency key of the source synth * @param synthAmount amount of the synth to swap * @param destKey currency key of the destination synth * @return amount of the destination synth received */ function swapSynth( bytes32 sourceKey, uint256 synthAmount, bytes32 destKey ) external onlyOwner returns (uint256) { return SYNTHETIX.exchangeWithTracking( sourceKey, synthAmount, destKey, msg.sender, TRACKING ); } /** * @notice Approves the given `tokenFrom` and swaps it to another token via the given `swap` pool. * @param swap the address of a pool to swap through * @param tokenFrom the address of the stored synth * @param tokenFromIndex the index of the token to swap from * @param tokenToIndex the token the user wants to swap to * @param tokenFromAmount the amount of the token to swap * @param minAmount the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction * @param recipient the address of the recipient */ function swapSynthToToken( ISwap swap, IERC20 tokenFrom, uint8 tokenFromIndex, uint8 tokenToIndex, uint256 tokenFromAmount, uint256 minAmount, uint256 deadline, address recipient ) external onlyOwner returns (IERC20, uint256) { tokenFrom.approve(address(swap), tokenFromAmount); swap.swap( tokenFromIndex, tokenToIndex, tokenFromAmount, minAmount, deadline ); IERC20 tokenTo = swap.getToken(tokenToIndex); uint256 balance = tokenTo.balanceOf(address(this)); tokenTo.safeTransfer(recipient, balance); return (tokenTo, balance); } /** * @notice Withdraws the given amount of `token` to the `recipient`. * @param token the address of the token to withdraw * @param recipient the address of the account to receive the token * @param withdrawAmount the amount of the token to withdraw * @param shouldDestroy whether this contract should be destroyed after this call */ function withdraw( IERC20 token, address recipient, uint256 withdrawAmount, bool shouldDestroy ) external onlyOwner { token.safeTransfer(recipient, withdrawAmount); if (shouldDestroy) { _destroy(); } } /** * @notice Destroys this contract. Only owner can call this function. */ function destroy() external onlyOwner { _destroy(); } function _destroy() internal { selfdestruct(msg.sender); } } pragma solidity >=0.4.24; import "./ISynth.sol"; import "./IVirtualSynth.sol"; // https://docs.synthetix.io/contracts/source/interfaces/isynthetix interface ISynthetix { // Views function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid); function availableCurrencyKeys() external view returns (bytes32[] memory); function availableSynthCount() external view returns (uint); function availableSynths(uint index) external view returns (ISynth); function collateral(address account) external view returns (uint); function collateralisationRatio(address issuer) external view returns (uint); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint); function isWaitingPeriod(bytes32 currencyKey) external view returns (bool); function maxIssuableSynths(address issuer) external view returns (uint maxIssuable); function remainingIssuableSynths(address issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ); function synths(bytes32 currencyKey) external view returns (ISynth); function synthsByAddress(address synthAddress) external view returns (bytes32); function totalIssuedSynths(bytes32 currencyKey) external view returns (uint); function totalIssuedSynthsExcludeEtherCollateral(bytes32 currencyKey) external view returns (uint); function transferableSynthetix(address account) external view returns (uint transferable); // Mutative Functions function burnSynths(uint amount) external; function burnSynthsOnBehalf(address burnForAddress, uint amount) external; function burnSynthsToTarget() external; function burnSynthsToTargetOnBehalf(address burnForAddress) external; function exchange( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeOnBehalf( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeWithTracking( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeOnBehalfWithTracking( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeWithVirtual( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualSynth vSynth); function issueMaxSynths() external; function issueMaxSynthsOnBehalf(address issueForAddress) external; function issueSynths(uint amount) external; function issueSynthsOnBehalf(address issueForAddress, uint amount) external; function mint() external returns (bool); function settle(bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); // Liquidations function liquidateDelinquentAccount(address account, uint susdAmount) external returns (bool); // Restricted Functions function mintSecondary(address account, uint amount) external; function mintSecondaryRewards(uint amount) external; function burnSecondary(address account, uint amount) external; } pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/isynth interface ISynth { // Views function currencyKey() external view returns (bytes32); function transferableSynths(address account) external view returns (uint); // Mutative functions function transferAndSettle(address to, uint value) external returns (bool); function transferFromAndSettle( address from, address to, uint value ) external returns (bool); // Restricted: used internally to Synthetix function burn(address account, uint amount) external; function issue(address account, uint amount) external; } pragma solidity >=0.4.24; import "./ISynth.sol"; interface IVirtualSynth { // Views function balanceOfUnderlying(address account) external view returns (uint); function rate() external view returns (uint); function readyToSettle() external view returns (bool); function secsLeftInWaitingPeriod() external view returns (uint); function settled() external view returns (bool); function synth() external view returns (ISynth); // Mutative functions function settle(address account) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/ISwapV1.sol"; /** * @title Liquidity Provider Token * @notice This token is an ERC20 detailed token with added capability to be minted by the owner. * It is used to represent user's shares when providing liquidity to swap contracts. * @dev Only Swap contracts should initialize and own LPToken contracts. */ contract LPTokenV1 is ERC20BurnableUpgradeable, OwnableUpgradeable { using SafeMathUpgradeable for uint256; /** * @notice Initializes this LPToken contract with the given name and symbol * @dev The caller of this function will become the owner. A Swap contract should call this * in its initializer function. * @param name name of this token * @param symbol symbol of this token */ function initialize(string memory name, string memory symbol) external initializer returns (bool) { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); __Ownable_init_unchained(); return true; } /** * @notice Mints the given amount of LPToken to the recipient. * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint */ function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "LPToken: cannot mint 0"); _mint(recipient, amount); } /** * @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including * minting and burning. This ensures that Swap.updateUserWithdrawFees are called everytime. * This assumes the owner is set to a Swap contract's address. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable) { super._beforeTokenTransfer(from, to, amount); require(to != address(this), "LPToken: cannot send to itself"); ISwapV1(owner()).updateUserWithdrawFee(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./IAllowlist.sol"; interface ISwapV1 { // pool data view functions function getA() external view returns (uint256); function getAllowlist() external view returns (IAllowlist); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256); function calculateRemoveLiquidity(address account, uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function initialize( IERC20[] memory pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 a, uint256 fee, uint256 adminFee, uint256 withdrawFee, address lpTokenTargetAddress ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); // withdraw fee update function function updateUserWithdrawFee(address recipient, uint256 transferAmount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "./interfaces/ISwapV1.sol"; contract SwapDeployerV1 is Ownable { event NewSwapPool( address indexed deployer, address swapAddress, IERC20[] pooledTokens ); constructor() public Ownable() {} function deploy( address swapAddress, IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, address lpTokenTargetAddress ) external returns (address) { address swapClone = Clones.clone(swapAddress); ISwapV1(swapClone).initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, _withdrawFee, lpTokenTargetAddress ); Ownable(swapClone).transferOwnership(owner()); emit NewSwapPool(msg.sender, swapClone, _pooledTokens); return swapClone; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "synthetix/contracts/interfaces/IAddressResolver.sol"; import "synthetix/contracts/interfaces/IExchanger.sol"; import "synthetix/contracts/interfaces/IExchangeRates.sol"; import "../interfaces/ISwap.sol"; import "./SynthSwapper.sol"; contract Proxy { address public target; } contract Target { address public proxy; } /** * @title Bridge * @notice This contract is responsible for cross-asset swaps using the Synthetix protocol as the bridging exchange. * There are three types of supported cross-asset swaps, tokenToSynth, synthToToken, and tokenToToken. * * 1) tokenToSynth * Swaps a supported token in a saddle pool to any synthetic asset (e.g. tBTC -> sAAVE). * * 2) synthToToken * Swaps any synthetic asset to a suported token in a saddle pool (e.g. sDEFI -> USDC). * * 3) tokenToToken * Swaps a supported token in a saddle pool to one in another pool (e.g. renBTC -> DAI). * * Due to the settlement periods of synthetic assets, the users must wait until the trades can be completed. * Users will receive an ERC721 token that represents pending cross-asset swap. Once the waiting period is over, * the trades can be settled and completed by calling the `completeToSynth` or the `completeToToken` function. * In the cases of pending `synthToToken` or `tokenToToken` swaps, the owners of the pending swaps can also choose * to withdraw the bridging synthetic assets instead of completing the swap. */ contract Bridge is ERC721 { using SafeMath for uint256; using SafeERC20 for IERC20; event SynthIndex( address indexed swap, uint8 synthIndex, bytes32 currencyKey, address synthAddress ); event TokenToSynth( address indexed requester, uint256 indexed itemId, ISwap swapPool, uint8 tokenFromIndex, uint256 tokenFromInAmount, bytes32 synthToKey ); event SynthToToken( address indexed requester, uint256 indexed itemId, ISwap swapPool, bytes32 synthFromKey, uint256 synthFromInAmount, uint8 tokenToIndex ); event TokenToToken( address indexed requester, uint256 indexed itemId, ISwap[2] swapPools, uint8 tokenFromIndex, uint256 tokenFromAmount, uint8 tokenToIndex ); event Settle( address indexed requester, uint256 indexed itemId, IERC20 settleFrom, uint256 settleFromAmount, IERC20 settleTo, uint256 settleToAmount, bool isFinal ); event Withdraw( address indexed requester, uint256 indexed itemId, IERC20 synth, uint256 synthAmount, bool isFinal ); // The addresses for all Synthetix contracts can be found in the below URL. // https://docs.synthetix.io/addresses/#mainnet-contracts // // Since the Synthetix protocol is upgradable, we must use the proxy pairs of each contract such that // the composability is not broken after the protocol upgrade. // // SYNTHETIX_RESOLVER points to `ReadProxyAddressResolver` (0x4E3b31eB0E5CB73641EE1E65E7dCEFe520bA3ef2). // This contract is a read proxy of `AddressResolver` which is responsible for storing the addresses of the contracts // used by the Synthetix protocol. IAddressResolver public constant SYNTHETIX_RESOLVER = IAddressResolver(0x4E3b31eB0E5CB73641EE1E65E7dCEFe520bA3ef2); // EXCHANGER points to `Exchanger`. There is no proxy pair for this contract so we need to update this variable // when the protocol is upgraded. This contract is used to settle synths held by SynthSwapper. IExchanger public exchanger; // CONSTANTS // Available types of cross-asset swaps enum PendingSwapType { Null, TokenToSynth, SynthToToken, TokenToToken } uint256 public constant MAX_UINT256 = 2**256 - 1; uint8 public constant MAX_UINT8 = 2**8 - 1; bytes32 public constant EXCHANGE_RATES_NAME = "ExchangeRates"; bytes32 public constant EXCHANGER_NAME = "Exchanger"; address public immutable SYNTH_SWAPPER_MASTER; // MAPPINGS FOR STORING PENDING SETTLEMENTS // The below two mappings never share the same key. mapping(uint256 => PendingToSynthSwap) public pendingToSynthSwaps; mapping(uint256 => PendingToTokenSwap) public pendingToTokenSwaps; uint256 public pendingSwapsLength; mapping(uint256 => PendingSwapType) private pendingSwapType; // MAPPINGS FOR STORING SYNTH INFO mapping(address => SwapContractInfo) private swapContracts; // Structs holding information about pending settlements struct PendingToSynthSwap { SynthSwapper swapper; bytes32 synthKey; } struct PendingToTokenSwap { SynthSwapper swapper; bytes32 synthKey; ISwap swap; uint8 tokenToIndex; } struct SwapContractInfo { // index of the supported synth + 1 uint8 synthIndexPlusOne; // address of the supported synth address synthAddress; // bytes32 key of the supported synth bytes32 synthKey; // array of tokens supported by the contract IERC20[] tokens; } /** * @notice Deploys this contract and initializes the master version of the SynthSwapper contract. The address to * the Synthetix protocol's Exchanger contract is also set on deployment. */ constructor(address synthSwapperAddress) public ERC721("Saddle Cross-Asset Swap", "SaddleSynthSwap") { SYNTH_SWAPPER_MASTER = synthSwapperAddress; updateExchangerCache(); } /** * @notice Returns the address of the proxy contract targeting the synthetic asset with the given `synthKey`. * @param synthKey the currency key of the synth * @return address of the proxy contract */ function getProxyAddressFromTargetSynthKey(bytes32 synthKey) public view returns (IERC20) { return IERC20(Target(SYNTHETIX_RESOLVER.getSynth(synthKey)).proxy()); } /** * @notice Returns various information of a pending swap represented by the given `itemId`. Information includes * the type of the pending swap, the number of seconds left until it can be settled, the address and the balance * of the synth this swap currently holds, and the address of the destination token. * @param itemId ID of the pending swap * @return swapType the type of the pending virtual swap, * secsLeft number of seconds left until this swap can be settled, * synth address of the synth this swap uses, * synthBalance amount of the synth this swap holds, * tokenTo the address of the destination token */ function getPendingSwapInfo(uint256 itemId) external view returns ( PendingSwapType swapType, uint256 secsLeft, address synth, uint256 synthBalance, address tokenTo ) { swapType = pendingSwapType[itemId]; require(swapType != PendingSwapType.Null, "invalid itemId"); SynthSwapper synthSwapper; bytes32 synthKey; if (swapType == PendingSwapType.TokenToSynth) { synthSwapper = pendingToSynthSwaps[itemId].swapper; synthKey = pendingToSynthSwaps[itemId].synthKey; synth = address(getProxyAddressFromTargetSynthKey(synthKey)); tokenTo = synth; } else { PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; synthSwapper = pendingToTokenSwap.swapper; synthKey = pendingToTokenSwap.synthKey; synth = address(getProxyAddressFromTargetSynthKey(synthKey)); tokenTo = address( swapContracts[address(pendingToTokenSwap.swap)].tokens[ pendingToTokenSwap.tokenToIndex ] ); } secsLeft = exchanger.maxSecsLeftInWaitingPeriod( address(synthSwapper), synthKey ); synthBalance = IERC20(synth).balanceOf(address(synthSwapper)); } // Settles the synth only. function _settle(address synthOwner, bytes32 synthKey) internal { // Settle synth exchanger.settle(synthOwner, synthKey); } /** * @notice Settles and withdraws the synthetic asset without swapping it to a token in a Saddle pool. Only the owner * of the ERC721 token of `itemId` can call this function. Reverts if the given `itemId` does not represent a * `synthToToken` or a `tokenToToken` swap. * @param itemId ID of the pending swap * @param amount the amount of the synth to withdraw */ function withdraw(uint256 itemId, uint256 amount) external { address nftOwner = ownerOf(itemId); require(nftOwner == msg.sender, "not owner"); require( pendingSwapType[itemId] > PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; _settle( address(pendingToTokenSwap.swapper), pendingToTokenSwap.synthKey ); IERC20 synth = getProxyAddressFromTargetSynthKey( pendingToTokenSwap.synthKey ); bool shouldDestroy; if (amount >= synth.balanceOf(address(pendingToTokenSwap.swapper))) { _burn(itemId); delete pendingToTokenSwaps[itemId]; delete pendingSwapType[itemId]; shouldDestroy = true; } pendingToTokenSwap.swapper.withdraw( synth, nftOwner, amount, shouldDestroy ); emit Withdraw(msg.sender, itemId, synth, amount, shouldDestroy); } /** * @notice Completes the pending `tokenToSynth` swap by settling and withdrawing the synthetic asset. * Reverts if the given `itemId` does not represent a `tokenToSynth` swap. * @param itemId ERC721 token ID representing a pending `tokenToSynth` swap */ function completeToSynth(uint256 itemId) external { address nftOwner = ownerOf(itemId); require(nftOwner == msg.sender, "not owner"); require( pendingSwapType[itemId] == PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToSynthSwap memory pendingToSynthSwap = pendingToSynthSwaps[ itemId ]; _settle( address(pendingToSynthSwap.swapper), pendingToSynthSwap.synthKey ); IERC20 synth = getProxyAddressFromTargetSynthKey( pendingToSynthSwap.synthKey ); // Burn the corresponding ERC721 token and delete storage for gas _burn(itemId); delete pendingToTokenSwaps[itemId]; delete pendingSwapType[itemId]; // After settlement, withdraw the synth and send it to the recipient uint256 synthBalance = synth.balanceOf( address(pendingToSynthSwap.swapper) ); pendingToSynthSwap.swapper.withdraw( synth, nftOwner, synthBalance, true ); emit Settle( msg.sender, itemId, synth, synthBalance, synth, synthBalance, true ); } /** * @notice Calculates the expected amount of the token to receive on calling `completeToToken()` with * the given `swapAmount`. * @param itemId ERC721 token ID representing a pending `SynthToToken` or `TokenToToken` swap * @param swapAmount the amount of bridging synth to swap from * @return expected amount of the token the user will receive */ function calcCompleteToToken(uint256 itemId, uint256 swapAmount) external view returns (uint256) { require( pendingSwapType[itemId] > PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; return pendingToTokenSwap.swap.calculateSwap( getSynthIndex(pendingToTokenSwap.swap), pendingToTokenSwap.tokenToIndex, swapAmount ); } /** * @notice Completes the pending `SynthToToken` or `TokenToToken` swap by settling the bridging synth and swapping * it to the desired token. Only the owners of the pending swaps can call this function. * @param itemId ERC721 token ID representing a pending `SynthToToken` or `TokenToToken` swap * @param swapAmount the amount of bridging synth to swap from * @param minAmount the minimum amount of the token to receive - reverts if this amount is not reached * @param deadline the timestamp representing the deadline for this transaction - reverts if deadline is not met */ function completeToToken( uint256 itemId, uint256 swapAmount, uint256 minAmount, uint256 deadline ) external { require(swapAmount != 0, "amount must be greater than 0"); address nftOwner = ownerOf(itemId); require(msg.sender == nftOwner, "must own itemId"); require( pendingSwapType[itemId] > PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; _settle( address(pendingToTokenSwap.swapper), pendingToTokenSwap.synthKey ); IERC20 synth = getProxyAddressFromTargetSynthKey( pendingToTokenSwap.synthKey ); bool shouldDestroyClone; if ( swapAmount >= synth.balanceOf(address(pendingToTokenSwap.swapper)) ) { _burn(itemId); delete pendingToTokenSwaps[itemId]; delete pendingSwapType[itemId]; shouldDestroyClone = true; } // Try swapping the synth to the desired token via the stored swap pool contract // If the external call succeeds, send the token to the owner of token with itemId. (IERC20 tokenTo, uint256 amountOut) = pendingToTokenSwap .swapper .swapSynthToToken( pendingToTokenSwap.swap, synth, getSynthIndex(pendingToTokenSwap.swap), pendingToTokenSwap.tokenToIndex, swapAmount, minAmount, deadline, nftOwner ); if (shouldDestroyClone) { pendingToTokenSwap.swapper.destroy(); } emit Settle( msg.sender, itemId, synth, swapAmount, tokenTo, amountOut, shouldDestroyClone ); } // Add the given pending synth settlement struct to the list function _addToPendingSynthSwapList( PendingToSynthSwap memory pendingToSynthSwap ) internal returns (uint256) { require( pendingSwapsLength < MAX_UINT256, "pendingSwapsLength reached max size" ); pendingToSynthSwaps[pendingSwapsLength] = pendingToSynthSwap; return pendingSwapsLength++; } // Add the given pending synth to token settlement struct to the list function _addToPendingSynthToTokenSwapList( PendingToTokenSwap memory pendingToTokenSwap ) internal returns (uint256) { require( pendingSwapsLength < MAX_UINT256, "pendingSwapsLength reached max size" ); pendingToTokenSwaps[pendingSwapsLength] = pendingToTokenSwap; return pendingSwapsLength++; } /** * @notice Calculates the expected amount of the desired synthetic asset the caller will receive after completing * a `TokenToSynth` swap with the given parameters. This calculation does not consider the settlement periods. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param tokenFromIndex the index of the token to swap from * @param synthOutKey the currency key of the desired synthetic asset * @param tokenInAmount the amount of the token to swap form * @return the expected amount of the desired synth */ function calcTokenToSynth( ISwap swap, uint8 tokenFromIndex, bytes32 synthOutKey, uint256 tokenInAmount ) external view returns (uint256) { uint8 mediumSynthIndex = getSynthIndex(swap); uint256 expectedMediumSynthAmount = swap.calculateSwap( tokenFromIndex, mediumSynthIndex, tokenInAmount ); bytes32 mediumSynthKey = getSynthKey(swap); IExchangeRates exchangeRates = IExchangeRates( SYNTHETIX_RESOLVER.getAddress(EXCHANGE_RATES_NAME) ); return exchangeRates.effectiveValue( mediumSynthKey, expectedMediumSynthAmount, synthOutKey ); } /** * @notice Initiates a cross-asset swap from a token supported in the `swap` pool to any synthetic asset. * The caller will receive an ERC721 token representing their ownership of the pending cross-asset swap. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param tokenFromIndex the index of the token to swap from * @param synthOutKey the currency key of the desired synthetic asset * @param tokenInAmount the amount of the token to swap form * @param minAmount the amount of the token to swap form * @return ID of the ERC721 token sent to the caller */ function tokenToSynth( ISwap swap, uint8 tokenFromIndex, bytes32 synthOutKey, uint256 tokenInAmount, uint256 minAmount ) external returns (uint256) { require(tokenInAmount != 0, "amount must be greater than 0"); // Create a SynthSwapper clone SynthSwapper synthSwapper = SynthSwapper( Clones.clone(SYNTH_SWAPPER_MASTER) ); synthSwapper.initialize(); // Add the synthswapper to the pending settlement list uint256 itemId = _addToPendingSynthSwapList( PendingToSynthSwap(synthSwapper, synthOutKey) ); pendingSwapType[itemId] = PendingSwapType.TokenToSynth; // Mint an ERC721 token that represents ownership of the pending synth settlement to msg.sender _mint(msg.sender, itemId); // Transfer token from msg.sender IERC20 tokenFrom = swapContracts[address(swap)].tokens[tokenFromIndex]; // revert when token not found in swap pool tokenFrom.safeTransferFrom(msg.sender, address(this), tokenInAmount); tokenInAmount = tokenFrom.balanceOf(address(this)); // Swap the synth to the medium synth uint256 mediumSynthAmount = swap.swap( tokenFromIndex, getSynthIndex(swap), tokenInAmount, 0, block.timestamp ); // Swap synths via Synthetix network IERC20(getSynthAddress(swap)).safeTransfer( address(synthSwapper), mediumSynthAmount ); require( synthSwapper.swapSynth( getSynthKey(swap), mediumSynthAmount, synthOutKey ) >= minAmount, "minAmount not reached" ); // Emit TokenToSynth event with relevant data emit TokenToSynth( msg.sender, itemId, swap, tokenFromIndex, tokenInAmount, synthOutKey ); return (itemId); } /** * @notice Calculates the expected amount of the desired token the caller will receive after completing * a `SynthToToken` swap with the given parameters. This calculation does not consider the settlement periods or * any potential changes of the `swap` pool composition. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param synthInKey the currency key of the synth to swap from * @param tokenToIndex the index of the token to swap to * @param synthInAmount the amount of the synth to swap form * @return the expected amount of the bridging synth and the expected amount of the desired token */ function calcSynthToToken( ISwap swap, bytes32 synthInKey, uint8 tokenToIndex, uint256 synthInAmount ) external view returns (uint256, uint256) { IExchangeRates exchangeRates = IExchangeRates( SYNTHETIX_RESOLVER.getAddress(EXCHANGE_RATES_NAME) ); uint8 mediumSynthIndex = getSynthIndex(swap); bytes32 mediumSynthKey = getSynthKey(swap); require(synthInKey != mediumSynthKey, "use normal swap"); uint256 expectedMediumSynthAmount = exchangeRates.effectiveValue( synthInKey, synthInAmount, mediumSynthKey ); return ( expectedMediumSynthAmount, swap.calculateSwap( mediumSynthIndex, tokenToIndex, expectedMediumSynthAmount ) ); } /** * @notice Initiates a cross-asset swap from a synthetic asset to a supported token. The caller will receive * an ERC721 token representing their ownership of the pending cross-asset swap. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param synthInKey the currency key of the synth to swap from * @param tokenToIndex the index of the token to swap to * @param synthInAmount the amount of the synth to swap form * @param minMediumSynthAmount the minimum amount of the bridging synth at pre-settlement stage * @return the ID of the ERC721 token sent to the caller */ function synthToToken( ISwap swap, bytes32 synthInKey, uint8 tokenToIndex, uint256 synthInAmount, uint256 minMediumSynthAmount ) external returns (uint256) { require(synthInAmount != 0, "amount must be greater than 0"); bytes32 mediumSynthKey = getSynthKey(swap); require( synthInKey != mediumSynthKey, "synth is supported via normal swap" ); // Create a SynthSwapper clone SynthSwapper synthSwapper = SynthSwapper( Clones.clone(SYNTH_SWAPPER_MASTER) ); synthSwapper.initialize(); // Add the synthswapper to the pending synth to token settlement list uint256 itemId = _addToPendingSynthToTokenSwapList( PendingToTokenSwap(synthSwapper, mediumSynthKey, swap, tokenToIndex) ); pendingSwapType[itemId] = PendingSwapType.SynthToToken; // Mint an ERC721 token that represents ownership of the pending synth to token settlement to msg.sender _mint(msg.sender, itemId); // Receive synth from the user and swap it to another synth IERC20 synthFrom = getProxyAddressFromTargetSynthKey(synthInKey); synthFrom.safeTransferFrom(msg.sender, address(this), synthInAmount); synthFrom.safeTransfer(address(synthSwapper), synthInAmount); require( synthSwapper.swapSynth(synthInKey, synthInAmount, mediumSynthKey) >= minMediumSynthAmount, "minMediumSynthAmount not reached" ); // Emit SynthToToken event with relevant data emit SynthToToken( msg.sender, itemId, swap, synthInKey, synthInAmount, tokenToIndex ); return (itemId); } /** * @notice Calculates the expected amount of the desired token the caller will receive after completing * a `TokenToToken` swap with the given parameters. This calculation does not consider the settlement periods or * any potential changes of the pool compositions. * @param swaps the addresses of the two Saddle pools used to do the cross-asset swap * @param tokenFromIndex the index of the token in the first `swaps` pool to swap from * @param tokenToIndex the index of the token in the second `swaps` pool to swap to * @param tokenFromAmount the amount of the token to swap from * @return the expected amount of bridging synth at pre-settlement stage and the expected amount of the desired * token */ function calcTokenToToken( ISwap[2] calldata swaps, uint8 tokenFromIndex, uint8 tokenToIndex, uint256 tokenFromAmount ) external view returns (uint256, uint256) { IExchangeRates exchangeRates = IExchangeRates( SYNTHETIX_RESOLVER.getAddress(EXCHANGE_RATES_NAME) ); uint256 firstSynthAmount = swaps[0].calculateSwap( tokenFromIndex, getSynthIndex(swaps[0]), tokenFromAmount ); uint256 mediumSynthAmount = exchangeRates.effectiveValue( getSynthKey(swaps[0]), firstSynthAmount, getSynthKey(swaps[1]) ); return ( mediumSynthAmount, swaps[1].calculateSwap( getSynthIndex(swaps[1]), tokenToIndex, mediumSynthAmount ) ); } /** * @notice Initiates a cross-asset swap from a token in one Saddle pool to one in another. The caller will receive * an ERC721 token representing their ownership of the pending cross-asset swap. * @param swaps the addresses of the two Saddle pools used to do the cross-asset swap * @param tokenFromIndex the index of the token in the first `swaps` pool to swap from * @param tokenToIndex the index of the token in the second `swaps` pool to swap to * @param tokenFromAmount the amount of the token to swap from * @param minMediumSynthAmount the minimum amount of the bridging synth at pre-settlement stage * @return the ID of the ERC721 token sent to the caller */ function tokenToToken( ISwap[2] calldata swaps, uint8 tokenFromIndex, uint8 tokenToIndex, uint256 tokenFromAmount, uint256 minMediumSynthAmount ) external returns (uint256) { // Create a SynthSwapper clone require(tokenFromAmount != 0, "amount must be greater than 0"); SynthSwapper synthSwapper = SynthSwapper( Clones.clone(SYNTH_SWAPPER_MASTER) ); synthSwapper.initialize(); bytes32 mediumSynthKey = getSynthKey(swaps[1]); // Add the synthswapper to the pending synth to token settlement list uint256 itemId = _addToPendingSynthToTokenSwapList( PendingToTokenSwap( synthSwapper, mediumSynthKey, swaps[1], tokenToIndex ) ); pendingSwapType[itemId] = PendingSwapType.TokenToToken; // Mint an ERC721 token that represents ownership of the pending swap to msg.sender _mint(msg.sender, itemId); // Receive token from the user ISwap swap = swaps[0]; { IERC20 tokenFrom = swapContracts[address(swap)].tokens[ tokenFromIndex ]; tokenFrom.safeTransferFrom( msg.sender, address(this), tokenFromAmount ); } uint256 firstSynthAmount = swap.swap( tokenFromIndex, getSynthIndex(swap), tokenFromAmount, 0, block.timestamp ); // Swap the synth to another synth IERC20(getSynthAddress(swap)).safeTransfer( address(synthSwapper), firstSynthAmount ); require( synthSwapper.swapSynth( getSynthKey(swap), firstSynthAmount, mediumSynthKey ) >= minMediumSynthAmount, "minMediumSynthAmount not reached" ); // Emit TokenToToken event with relevant data emit TokenToToken( msg.sender, itemId, swaps, tokenFromIndex, tokenFromAmount, tokenToIndex ); return (itemId); } /** * @notice Registers the index and the address of the supported synth from the given `swap` pool. The matching currency key must * be supplied for a successful registration. * @param swap the address of the pool that contains the synth * @param synthIndex the index of the supported synth in the given `swap` pool * @param currencyKey the currency key of the synth in bytes32 form */ function setSynthIndex( ISwap swap, uint8 synthIndex, bytes32 currencyKey ) external { require(synthIndex < MAX_UINT8, "index is too large"); SwapContractInfo storage swapContractInfo = swapContracts[ address(swap) ]; // Check if the pool has already been added require(swapContractInfo.synthIndexPlusOne == 0, "Pool already added"); // Ensure the synth with the same currency key exists at the given `synthIndex` IERC20 synth = swap.getToken(synthIndex); require( ISynth(Proxy(address(synth)).target()).currencyKey() == currencyKey, "currencyKey does not match" ); swapContractInfo.synthIndexPlusOne = synthIndex + 1; swapContractInfo.synthAddress = address(synth); swapContractInfo.synthKey = currencyKey; swapContractInfo.tokens = new IERC20[](0); for (uint8 i = 0; i < MAX_UINT8; i++) { IERC20 token; if (i == synthIndex) { token = synth; } else { try swap.getToken(i) returns (IERC20 token_) { token = token_; } catch { break; } } swapContractInfo.tokens.push(token); token.safeApprove(address(swap), MAX_UINT256); } emit SynthIndex(address(swap), synthIndex, currencyKey, address(synth)); } /** * @notice Returns the index of the supported synth in the given `swap` pool. Reverts if the `swap` pool * is not registered. * @param swap the address of the pool that contains the synth * @return the index of the supported synth */ function getSynthIndex(ISwap swap) public view returns (uint8) { uint8 synthIndexPlusOne = swapContracts[address(swap)] .synthIndexPlusOne; require(synthIndexPlusOne > 0, "synth index not found for given pool"); return synthIndexPlusOne - 1; } /** * @notice Returns the address of the supported synth in the given `swap` pool. Reverts if the `swap` pool * is not registered. * @param swap the address of the pool that contains the synth * @return the address of the supported synth */ function getSynthAddress(ISwap swap) public view returns (address) { address synthAddress = swapContracts[address(swap)].synthAddress; require( synthAddress != address(0), "synth addr not found for given pool" ); return synthAddress; } /** * @notice Returns the currency key of the supported synth in the given `swap` pool. Reverts if the `swap` pool * is not registered. * @param swap the address of the pool that contains the synth * @return the currency key of the supported synth */ function getSynthKey(ISwap swap) public view returns (bytes32) { bytes32 synthKey = swapContracts[address(swap)].synthKey; require(synthKey != 0x0, "synth key not found for given pool"); return synthKey; } /** * @notice Updates the stored address of the `EXCHANGER` contract. When the Synthetix team upgrades their protocol, * a new Exchanger contract is deployed. This function manually updates the stored address. */ function updateExchangerCache() public { exchanger = IExchanger(SYNTHETIX_RESOLVER.getAddress(EXCHANGER_NAME)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../utils/EnumerableSet.sol"; import "../../utils/EnumerableMap.sol"; import "../../utils/Strings.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/iaddressresolver interface IAddressResolver { function getAddress(bytes32 name) external view returns (address); function getSynth(bytes32 key) external view returns (address); function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address); } pragma solidity >=0.4.24; import "./IVirtualSynth.sol"; // https://docs.synthetix.io/contracts/source/interfaces/iexchanger interface IExchanger { // Views function calculateAmountAfterSettlement( address from, bytes32 currencyKey, uint amount, uint refunded ) external view returns (uint amountAfterSettlement); function isSynthRateInvalid(bytes32 currencyKey) external view returns (bool); function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) external view returns (uint); function settlementOwing(address account, bytes32 currencyKey) external view returns ( uint reclaimAmount, uint rebateAmount, uint numEntries ); function hasWaitingPeriodOrSettlementOwing(address account, bytes32 currencyKey) external view returns (bool); function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view returns (uint exchangeFeeRate); function getAmountsForExchange( uint sourceAmount, bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey ) external view returns ( uint amountReceived, uint fee, uint exchangeFeeRate ); function priceDeviationThresholdFactor() external view returns (uint); function waitingPeriodSecs() external view returns (uint); // Mutative functions function exchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external returns (uint amountReceived); function exchangeOnBehalf( address exchangeForAddress, address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeWithTracking( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeOnBehalfWithTracking( address exchangeForAddress, address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeWithVirtual( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualSynth vSynth); function settle(address from, bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); function setLastExchangeRateForSynth(bytes32 currencyKey, uint rate) external; function suspendSynthWithInvalidRate(bytes32 currencyKey) external; } pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/iexchangerates interface IExchangeRates { // Structs struct RateAndUpdatedTime { uint216 rate; uint40 time; } struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozenAtUpperLimit; bool frozenAtLowerLimit; } // Views function aggregators(bytes32 currencyKey) external view returns (address); function aggregatorWarningFlags() external view returns (address); function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool); function canFreezeRate(bytes32 currencyKey) external view returns (bool); function currentRoundForRate(bytes32 currencyKey) external view returns (uint); function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory); function effectiveValue( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns (uint value); function effectiveValueAndRates( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns ( uint value, uint sourceRate, uint destinationRate ); function effectiveValueAtRound( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, uint roundIdForSrc, uint roundIdForDest ) external view returns (uint value); function getCurrentRoundId(bytes32 currencyKey) external view returns (uint); function getLastRoundIdBeforeElapsedSecs( bytes32 currencyKey, uint startingRoundId, uint startingTimestamp, uint timediff ) external view returns (uint); function inversePricing(bytes32 currencyKey) external view returns ( uint entryPoint, uint upperLimit, uint lowerLimit, bool frozenAtUpperLimit, bool frozenAtLowerLimit ); function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256); function oracle() external view returns (address); function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time); function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time); function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid); function rateForCurrency(bytes32 currencyKey) external view returns (uint); function rateIsFlagged(bytes32 currencyKey) external view returns (bool); function rateIsFrozen(bytes32 currencyKey) external view returns (bool); function rateIsInvalid(bytes32 currencyKey) external view returns (bool); function rateIsStale(bytes32 currencyKey) external view returns (bool); function rateStalePeriod() external view returns (uint); function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds) external view returns (uint[] memory rates, uint[] memory times); function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory rates, bool anyRateInvalid); function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory); // Mutative functions function freezeRate(bytes32 currencyKey) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./interfaces/ISwap.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title SwapMigrator * @notice This contract is responsible for migrating old USD pool liquidity to the new ones. * Users can use this contract to remove their liquidity from the old pools and add them to the new * ones with a single transaction. */ contract SwapMigrator { using SafeERC20 for IERC20; struct MigrationData { address oldPoolAddress; IERC20 oldPoolLPTokenAddress; address newPoolAddress; IERC20 newPoolLPTokenAddress; IERC20[] underlyingTokens; } MigrationData public usdPoolMigrationData; address public owner; uint256 private constant MAX_UINT256 = 2**256 - 1; /** * @notice Sets the storage variables and approves tokens to be used by the old and new swap contracts * @param usdData_ MigrationData struct with information about old and new USD pools * @param owner_ owner that is allowed to call the `rescue()` function */ constructor(MigrationData memory usdData_, address owner_) public { // Approve old USD LP Token to be used by the old USD pool usdData_.oldPoolLPTokenAddress.approve( usdData_.oldPoolAddress, MAX_UINT256 ); // Approve USD tokens to be used by the new USD pool for (uint256 i = 0; i < usdData_.underlyingTokens.length; i++) { usdData_.underlyingTokens[i].safeApprove( usdData_.newPoolAddress, MAX_UINT256 ); } // Set storage variables usdPoolMigrationData = usdData_; owner = owner_; } /** * @notice Migrates old USD pool's LPToken to the new pool * @param amount Amount of old LPToken to migrate * @param minAmount Minimum amount of new LPToken to receive */ function migrateUSDPool(uint256 amount, uint256 minAmount) external returns (uint256) { // Transfer old LP token from the caller usdPoolMigrationData.oldPoolLPTokenAddress.safeTransferFrom( msg.sender, address(this), amount ); // Remove liquidity from the old pool and add them to the new pool uint256[] memory amounts = ISwap(usdPoolMigrationData.oldPoolAddress) .removeLiquidity( amount, new uint256[](usdPoolMigrationData.underlyingTokens.length), MAX_UINT256 ); uint256 mintedAmount = ISwap(usdPoolMigrationData.newPoolAddress) .addLiquidity(amounts, minAmount, MAX_UINT256); // Transfer new LP Token to the caller usdPoolMigrationData.newPoolLPTokenAddress.safeTransfer( msg.sender, mintedAmount ); return mintedAmount; } /** * @notice Rescues any token that may be sent to this contract accidentally. * @param token Amount of old LPToken to migrate * @param to Minimum amount of new LPToken to receive */ function rescue(IERC20 token, address to) external { require(msg.sender == owner, "is not owner"); token.safeTransfer(to, token.balanceOf(address(this))); } } // SPDX-License-Identifier: MIT // Generalized and adapted from https://github.com/k06a/Unipool 🙇 pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title StakeableTokenWrapper * @notice A wrapper for an ERC-20 that can be staked and withdrawn. * @dev In this contract, staked tokens don't do anything- instead other * contracts can inherit from this one to add functionality. */ contract StakeableTokenWrapper { using SafeERC20 for IERC20; using SafeMath for uint256; uint256 public totalSupply; IERC20 public stakedToken; mapping(address => uint256) private _balances; event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); /** * @notice Creates a new StakeableTokenWrapper with given `_stakedToken` address * @param _stakedToken address of a token that will be used to stake */ constructor(IERC20 _stakedToken) public { stakedToken = _stakedToken; } /** * @notice Read how much `account` has staked in this contract * @param account address of an account * @return amount of total staked ERC20(this.stakedToken) by `account` */ function balanceOf(address account) external view returns (uint256) { return _balances[account]; } /** * @notice Stakes given `amount` in this contract * @param amount amount of ERC20(this.stakedToken) to stake */ function stake(uint256 amount) external { require(amount != 0, "amount == 0"); totalSupply = totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakedToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } /** * @notice Withdraws given `amount` from this contract * @param amount amount of ERC20(this.stakedToken) to withdraw */ function withdraw(uint256 amount) external { totalSupply = totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakedToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/IFlashLoanReceiver.sol"; import "../interfaces/ISwapFlashLoan.sol"; import "hardhat/console.sol"; contract FlashLoanBorrowerExample is IFlashLoanReceiver { using SafeMath for uint256; // Typical executeOperation function should do the 3 following actions // 1. Check if the flashLoan was successful // 2. Do actions with the borrowed tokens // 3. Repay the debt to the `pool` function executeOperation( address pool, address token, uint256 amount, uint256 fee, bytes calldata params ) external override { // 1. Check if the flashLoan was valid require( IERC20(token).balanceOf(address(this)) >= amount, "flashloan is broken?" ); // 2. Do actions with the borrowed token bytes32 paramsHash = keccak256(params); if (paramsHash == keccak256(bytes("dontRepayDebt"))) { return; } else if (paramsHash == keccak256(bytes("reentrancy_addLiquidity"))) { ISwapFlashLoan(pool).addLiquidity( new uint256[](0), 0, block.timestamp ); } else if (paramsHash == keccak256(bytes("reentrancy_swap"))) { ISwapFlashLoan(pool).swap(1, 0, 1e6, 0, now); } else if ( paramsHash == keccak256(bytes("reentrancy_removeLiquidity")) ) { ISwapFlashLoan(pool).removeLiquidity(1e18, new uint256[](0), now); } else if ( paramsHash == keccak256(bytes("reentrancy_removeLiquidityOneToken")) ) { ISwapFlashLoan(pool).removeLiquidityOneToken(1e18, 0, 1e18, now); } // 3. Payback debt uint256 totalDebt = amount.add(fee); IERC20(token).transfer(pool, totalDebt); } function flashLoan( ISwapFlashLoan swap, IERC20 token, uint256 amount, bytes memory params ) external { swap.flashLoan(address(this), token, amount, params); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./ISwap.sol"; interface ISwapFlashLoan is ISwap { function flashLoan( address receiver, IERC20 token, uint256 amount, bytes memory params ) external; } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../../interfaces/ISwap.sol"; import "hardhat/console.sol"; contract TestSwapReturnValues { using SafeMath for uint256; ISwap public swap; IERC20 public lpToken; uint8 public n; uint256 public constant MAX_INT = 2**256 - 1; constructor( ISwap swapContract, IERC20 lpTokenContract, uint8 numOfTokens ) public { swap = swapContract; lpToken = lpTokenContract; n = numOfTokens; // Pre-approve tokens for (uint8 i; i < n; i++) { swap.getToken(i).approve(address(swap), MAX_INT); } lpToken.approve(address(swap), MAX_INT); } function test_swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) public { uint256 balanceBefore = swap.getToken(tokenIndexTo).balanceOf( address(this) ); uint256 returnValue = swap.swap( tokenIndexFrom, tokenIndexTo, dx, minDy, block.timestamp ); uint256 balanceAfter = swap.getToken(tokenIndexTo).balanceOf( address(this) ); console.log( "swap: Expected %s, got %s", balanceAfter.sub(balanceBefore), returnValue ); require( returnValue == balanceAfter.sub(balanceBefore), "swap()'s return value does not match received amount" ); } function test_addLiquidity(uint256[] calldata amounts, uint256 minToMint) public { uint256 balanceBefore = lpToken.balanceOf(address(this)); uint256 returnValue = swap.addLiquidity(amounts, minToMint, MAX_INT); uint256 balanceAfter = lpToken.balanceOf(address(this)); console.log( "addLiquidity: Expected %s, got %s", balanceAfter.sub(balanceBefore), returnValue ); require( returnValue == balanceAfter.sub(balanceBefore), "addLiquidity()'s return value does not match minted amount" ); } function test_removeLiquidity(uint256 amount, uint256[] memory minAmounts) public { uint256[] memory balanceBefore = new uint256[](n); uint256[] memory balanceAfter = new uint256[](n); for (uint8 i = 0; i < n; i++) { balanceBefore[i] = swap.getToken(i).balanceOf(address(this)); } uint256[] memory returnValue = swap.removeLiquidity( amount, minAmounts, MAX_INT ); for (uint8 i = 0; i < n; i++) { balanceAfter[i] = swap.getToken(i).balanceOf(address(this)); console.log( "removeLiquidity: Expected %s, got %s", balanceAfter[i].sub(balanceBefore[i]), returnValue[i] ); require( balanceAfter[i].sub(balanceBefore[i]) == returnValue[i], "removeLiquidity()'s return value does not match received amounts of tokens" ); } } function test_removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount ) public { uint256 balanceBefore = lpToken.balanceOf(address(this)); uint256 returnValue = swap.removeLiquidityImbalance( amounts, maxBurnAmount, MAX_INT ); uint256 balanceAfter = lpToken.balanceOf(address(this)); console.log( "removeLiquidityImbalance: Expected %s, got %s", balanceBefore.sub(balanceAfter), returnValue ); require( returnValue == balanceBefore.sub(balanceAfter), "removeLiquidityImbalance()'s return value does not match burned lpToken amount" ); } function test_removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) public { uint256 balanceBefore = swap.getToken(tokenIndex).balanceOf( address(this) ); uint256 returnValue = swap.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount, MAX_INT ); uint256 balanceAfter = swap.getToken(tokenIndex).balanceOf( address(this) ); console.log( "removeLiquidityOneToken: Expected %s, got %s", balanceAfter.sub(balanceBefore), returnValue ); require( returnValue == balanceAfter.sub(balanceBefore), "removeLiquidityOneToken()'s return value does not match received token amount" ); } } // SPDX-License-Identifier: MIT // https://etherscan.io/address/0x2b7a5a5923eca5c00c6572cf3e8e08384f563f93#code pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./LPTokenGuarded.sol"; import "../MathUtils.sol"; /** * @title SwapUtils library * @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities. * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library SwapUtilsGuarded { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); struct Swap { // variables around the ramp management of A, // the amplification coefficient * n * (n - 1) // see https://www.curve.fi/stableswap-paper.pdf for details uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime; // fee calculation uint256 swapFee; uint256 adminFee; uint256 defaultWithdrawFee; LPTokenGuarded lpToken; // contract references for all tokens being pooled IERC20[] pooledTokens; // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 uint256[] tokenPrecisionMultipliers; // the pool balance of each token, in the token's precision // the contract's actual token balance might differ uint256[] balances; mapping(address => uint256) depositTimestamp; mapping(address => uint256) withdrawFeeMultiplier; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; } // Struct storing variables used in calculation in addLiquidity function // to avoid stack too deep error struct AddLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; } // Struct storing variables used in calculation in removeLiquidityImbalance function // to avoid stack too deep error struct RemoveLiquidityImbalanceInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; } // the precision all pools tokens will be converted to uint8 public constant POOL_PRECISION_DECIMALS = 18; // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Max swap fee is 1% or 100bps of each swap uint256 public constant MAX_SWAP_FEE = 10**8; // Max adminFee is 100% of the swapFee // adminFee does not add additional fee on top of swapFee // Instead it takes a certain % of the swapFee. Therefore it has no impact on the // users but only on the earnings of LPs uint256 public constant MAX_ADMIN_FEE = 10**10; // Max withdrawFee is 1% of the value withdrawn // Fee will be redistributed to the LPs in the pool, rewarding // long term providers. uint256 public constant MAX_WITHDRAW_FEE = 10**8; // Constant value used as max loop limit uint256 private constant MAX_LOOP_LIMIT = 256; // Constant values used in ramping A calculations uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function getA(Swap storage self) external view returns (uint256) { return _getA(self); } /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function _getA(Swap storage self) internal view returns (uint256) { return _getAPrecise(self).div(A_PRECISION); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function getAPrecise(Swap storage self) external view returns (uint256) { return _getAPrecise(self); } /** * @notice Calculates and returns A based on the ramp settings * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function _getAPrecise(Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } } /** * @notice Retrieves the timestamp of last deposit made by the given address * @param self Swap struct to read from * @return timestamp of last deposit */ function getDepositTimestamp(Swap storage self, address user) external view returns (uint256) { return self.depositTimestamp[user]; } /** * @notice Calculate the dy, the amount of selected token that user receives and * the fee of withdrawing in one token * @param account the address that is withdrawing * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @param self Swap struct to read from * @return the amount of token user will receive and the associated swap fee */ function calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex ) public view returns (uint256, uint256) { uint256 dy; uint256 newY; (dy, newY) = calculateWithdrawOneTokenDY(self, tokenIndex, tokenAmount); // dy_0 (without fees) // dy, dy_0 - dy uint256 dySwapFee = _xp(self)[tokenIndex] .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); dy = dy .mul( FEE_DENOMINATOR.sub(calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @return the d and the new y after withdrawing one token */ function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount ) internal view returns (uint256, uint256) { require( tokenIndex < self.pooledTokens.length, "Token index out of range" ); // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0); v.preciseA = _getAPrecise(self); v.d0 = getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(self.lpToken.totalSupply())); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = _feePerToken(self); for (uint256 i = 0; i < self.pooledTokens.length; i++) { uint256 xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = xpi.sub( ( (i == tokenIndex) ? xpi.mul(v.d1).div(v.d0).sub(v.newY) : xpi.sub(xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY); } /** * @notice Calculate the price of a token in the pool with given * precision-adjusted balances and a particular D. * * @dev This is accomplished via solving the invariant iteratively. * See the StableSwap paper and Curve.fi implementation for further details. * * x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A) * x_1**2 + b*x_1 = c * x_1 = (x_1**2 + c) / (2*x_1 + b) * * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details. * @param tokenIndex Index of token we are calculating for. * @param xp a precision-adjusted set of pool balances. Array should be * the same cardinality as the pool. * @param d the stableswap invariant * @return the price of the token, in the same precision as in xp */ function getYD( uint256 a, uint8 tokenIndex, uint256[] memory xp, uint256 d ) internal pure returns (uint256) { uint256 numTokens = xp.length; require(tokenIndex < numTokens, "Token not found"); uint256 c = d; uint256 s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < numTokens; i++) { if (i != tokenIndex) { s = s.add(xp[i]); c = c.mul(d).div(xp[i].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } } c = c.mul(d).mul(A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. * @param xp a precision-adjusted set of pool balances. Array should be the same cardinality * as the pool. * @param a the amplification coefficient * n * (n - 1) in A_PRECISION. * See the StableSwap paper for details * @return the invariant, at the precision of the pool */ function getD(uint256[] memory xp, uint256 a) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s; for (uint256 i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD; uint256 d = s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = d; for (uint256 j = 0; j < numTokens; j++) { dP = dP.mul(d).div(xp[j].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // dP = dP * D * D * D * ... overflow! } prevD = d; d = nA.mul(s).div(A_PRECISION).add(dP.mul(numTokens)).mul(d).div( nA.sub(A_PRECISION).mul(d).div(A_PRECISION).add( numTokens.add(1).mul(dP) ) ); if (d.within1(prevD)) { return d; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("D does not converge"); } /** * @notice Get D, the StableSwap invariant, based on self Swap struct * @param self Swap struct to read from * @return The invariant, at the precision of the pool */ function getD(Swap storage self) internal view returns (uint256) { return getD(_xp(self), _getAPrecise(self)); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers ) internal pure returns (uint256[] memory) { uint256 numTokens = balances.length; require( numTokens == precisionMultipliers.length, "Balances must match multipliers" ); uint256[] memory xp = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { xp[i] = balances[i].mul(precisionMultipliers[i]); } return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @param balances array of balances to scale * @return balances array "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self, uint256[] memory balances) internal view returns (uint256[] memory) { return _xp(balances, self.tokenPrecisionMultipliers); } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenPrecisionMultipliers); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS */ function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); uint256 supply = self.lpToken.totalSupply(); if (supply > 0) { return d.mul(10**uint256(ERC20(self.lpToken).decimals())).div(supply); } return 0; } /** * @notice Calculate the new balances of the tokens given the indexes of the token * that is swapped from (FROM) and the token that is swapped to (TO). * This function is used as a helper function to calculate how much TO token * the user should receive on swap. * * @param self Swap struct to read from * @param tokenIndexFrom index of FROM token * @param tokenIndexTo index of TO token * @param x the new total amount of FROM token * @param xp balances of the tokens in the pool * @return the amount of TO token that should remain in the pool */ function getY( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 x, uint256[] memory xp ) internal view returns (uint256) { uint256 numTokens = self.pooledTokens.length; require( tokenIndexFrom != tokenIndexTo, "Can't compare token to itself" ); require( tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool" ); uint256 a = _getAPrecise(self); uint256 d = getD(xp, a); uint256 c = d; uint256 s; uint256 nA = numTokens.mul(a); uint256 _x; for (uint256 i = 0; i < numTokens; i++) { if (i == tokenIndexFrom) { _x = x; } else if (i != tokenIndexTo) { _x = xp[i]; } else { continue; } s = s.add(_x); c = c.mul(d).div(_x.mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } c = c.mul(d).mul(A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; // iterative approximation for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Externally calculates a swap between two tokens. * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap(self, tokenIndexFrom, tokenIndexTo, dx); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get * @return dyFee the associated fee */ function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory xp = _xp(self); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 x = dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom]).add( xp[tokenIndexFrom] ); uint256 y = getY(self, tokenIndexFrom, tokenIndexTo, x, xp); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(self.tokenPrecisionMultipliers[tokenIndexTo]); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * * @param account the address that is removing liquidity. required for withdraw fee calculation * @param amount the amount of LP tokens that would to be burned on * withdrawal * @return array of amounts of tokens user will receive */ function calculateRemoveLiquidity( Swap storage self, address account, uint256 amount ) external view returns (uint256[] memory) { return _calculateRemoveLiquidity(self, account, amount); } function _calculateRemoveLiquidity( Swap storage self, address account, uint256 amount ) internal view returns (uint256[] memory) { uint256 totalSupply = self.lpToken.totalSupply(); require(amount <= totalSupply, "Cannot exceed total supply"); uint256 feeAdjustedAmount = amount .mul( FEE_DENOMINATOR.sub(calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); uint256[] memory amounts = new uint256[](self.pooledTokens.length); for (uint256 i = 0; i < self.pooledTokens.length; i++) { amounts[i] = self.balances[i].mul(feeAdjustedAmount).div( totalSupply ); } return amounts; } /** * @notice Calculate the fee that is applied when the given user withdraws. * Withdraw fee decays linearly over 4 weeks. * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(Swap storage self, address user) public view returns (uint256) { uint256 endTime = self.depositTimestamp[user].add(4 weeks); if (endTime > block.timestamp) { uint256 timeLeftover = endTime.sub(block.timestamp); return self .defaultWithdrawFee .mul(self.withdrawFeeMultiplier[user]) .mul(timeLeftover) .div(4 weeks) .div(FEE_DENOMINATOR); } return 0; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param account address of the account depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( Swap storage self, address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 numTokens = self.pooledTokens.length; uint256 a = _getAPrecise(self); uint256 d0 = getD(_xp(self, self.balances), a); uint256[] memory balances1 = self.balances; for (uint256 i = 0; i < numTokens; i++) { if (deposit) { balances1[i] = balances1[i].add(amounts[i]); } else { balances1[i] = balances1[i].sub( amounts[i], "Cannot withdraw more than available" ); } } uint256 d1 = getD(_xp(self, balances1), a); uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub( calculateCurrentWithdrawFee(self, account) ) ); } } /** * @notice return accumulated amount of admin fees of the token with given index * @param self Swap struct to read from * @param index Index of the pooled token * @return admin balance in the token's precision */ function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) { require(index < self.pooledTokens.length, "Token index out of range"); return self.pooledTokens[index].balanceOf(address(this)).sub( self.balances[index] ); } /** * @notice internal helper function to calculate fee per token multiplier used in * swap fee calculations * @param self Swap struct to read from */ function _feePerToken(Swap storage self) internal view returns (uint256) { return self.swapFee.mul(self.pooledTokens.length).div( self.pooledTokens.length.sub(1).mul(4) ); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { require( dx <= self.pooledTokens[tokenIndexFrom].balanceOf(msg.sender), "Cannot swap more than you own" ); // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = self.pooledTokens[tokenIndexFrom].balanceOf( address(this) ); self.pooledTokens[tokenIndexFrom].safeTransferFrom( msg.sender, address(this), dx ); // Use the actual transferred amount for AMM math uint256 transferredDx = self .pooledTokens[tokenIndexFrom] .balanceOf(address(this)) .sub(beforeBalance); (uint256 dy, uint256 dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, transferredDx ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = self.balances[tokenIndexFrom].add( transferredDx ); self.balances[tokenIndexTo] = self.balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap( msg.sender, transferredDx, dy, tokenIndexFrom, tokenIndexTo ); return dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param merkleProof bytes32 array that will be used to prove the existence of the caller's address in the list of * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( Swap storage self, uint256[] memory amounts, uint256 minToMint, bytes32[] calldata merkleProof ) external returns (uint256) { require( amounts.length == self.pooledTokens.length, "Amounts must match pooled tokens" ); uint256[] memory fees = new uint256[](self.pooledTokens.length); // current state AddLiquidityInfo memory v = AddLiquidityInfo(0, 0, 0, 0); if (self.lpToken.totalSupply() != 0) { v.d0 = getD(self); } uint256[] memory newBalances = self.balances; for (uint256 i = 0; i < self.pooledTokens.length; i++) { require( self.lpToken.totalSupply() != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = self.pooledTokens[i].balanceOf( address(this) ); self.pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = self.pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } newBalances[i] = self.balances[i].add(amounts[i]); } // invariant after change v.preciseA = _getAPrecise(self); v.d1 = getD(_xp(self, newBalances), v.preciseA); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; if (self.lpToken.totalSupply() != 0) { uint256 feePerToken = _feePerToken(self); for (uint256 i = 0; i < self.pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(self.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); newBalances[i] = newBalances[i].sub(fees[i]); } v.d2 = getD(_xp(self, newBalances), v.preciseA); } else { // the initial depositor doesn't pay fees self.balances = newBalances; } uint256 toMint; if (self.lpToken.totalSupply() == 0) { toMint = v.d1; } else { toMint = v.d2.sub(v.d0).mul(self.lpToken.totalSupply()).div(v.d0); } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens self.lpToken.mint(msg.sender, toMint, merkleProof); emit AddLiquidity( msg.sender, amounts, fees, v.d1, self.lpToken.totalSupply() ); return toMint; } /** * @notice Update the withdraw fee for `user`. If the user is currently * not providing liquidity in the pool, sets to default value. If not, recalculate * the starting withdraw fee based on the last deposit's time & amount relative * to the new deposit. * * @param self Swap struct to read from and write to * @param user address of the user depositing tokens * @param toMint amount of pool tokens to be minted */ function updateUserWithdrawFee( Swap storage self, address user, uint256 toMint ) external { _updateUserWithdrawFee(self, user, toMint); } function _updateUserWithdrawFee( Swap storage self, address user, uint256 toMint ) internal { // If token is transferred to address 0 (or burned), don't update the fee. if (user == address(0)) { return; } if (self.defaultWithdrawFee == 0) { // If current fee is set to 0%, set multiplier to FEE_DENOMINATOR self.withdrawFeeMultiplier[user] = FEE_DENOMINATOR; } else { // Otherwise, calculate appropriate discount based on last deposit amount uint256 currentFee = calculateCurrentWithdrawFee(self, user); uint256 currentBalance = self.lpToken.balanceOf(user); // ((currentBalance * currentFee) + (toMint * defaultWithdrawFee)) * FEE_DENOMINATOR / // ((toMint + currentBalance) * defaultWithdrawFee) self.withdrawFeeMultiplier[user] = currentBalance .mul(currentFee) .add(toMint.mul(self.defaultWithdrawFee)) .mul(FEE_DENOMINATOR) .div(toMint.add(currentBalance).mul(self.defaultWithdrawFee)); } self.depositTimestamp[user] = block.timestamp; } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param self Swap struct to read from and write to * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @return amounts of tokens the user received */ function removeLiquidity( Swap storage self, uint256 amount, uint256[] calldata minAmounts ) external returns (uint256[] memory) { require(amount <= self.lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require( minAmounts.length == self.pooledTokens.length, "minAmounts must match poolTokens" ); uint256[] memory amounts = _calculateRemoveLiquidity( self, msg.sender, amount ); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]"); self.balances[i] = self.balances[i].sub(amounts[i]); self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } self.lpToken.burnFrom(msg.sender, amount); emit RemoveLiquidity(msg.sender, amounts, self.lpToken.totalSupply()); return amounts; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { uint256 totalSupply = self.lpToken.totalSupply(); uint256 numTokens = self.pooledTokens.length; require( tokenAmount <= self.lpToken.balanceOf(msg.sender), ">LP.balanceOf" ); require(tokenIndex < numTokens, "Token not found"); uint256 dyFee; uint256 dy; (dy, dyFee) = calculateWithdrawOneToken( self, msg.sender, tokenAmount, tokenIndex ); require(dy >= minAmount, "dy < minAmount"); self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); self.lpToken.burnFrom(msg.sender, tokenAmount); self.pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( Swap storage self, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { require( amounts.length == self.pooledTokens.length, "Amounts should match pool tokens" ); require( maxBurnAmount <= self.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf" ); RemoveLiquidityImbalanceInfo memory v = RemoveLiquidityImbalanceInfo( 0, 0, 0, 0 ); uint256 tokenSupply = self.lpToken.totalSupply(); uint256 feePerToken = _feePerToken(self); uint256[] memory balances1 = self.balances; v.preciseA = _getAPrecise(self); v.d0 = getD(_xp(self), v.preciseA); for (uint256 i = 0; i < self.pooledTokens.length; i++) { balances1[i] = balances1[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = getD(_xp(self, balances1), v.preciseA); uint256[] memory fees = new uint256[](self.pooledTokens.length); for (uint256 i = 0; i < self.pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(self.balances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = getD(_xp(self, balances1), v.preciseA); uint256 tokenAmount = v.d0.sub(v.d2).mul(tokenSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); tokenAmount = tokenAmount.add(1).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub(calculateCurrentWithdrawFee(self, msg.sender)) ); require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); self.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < self.pooledTokens.length; i++) { self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, tokenSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice withdraw all admin fees to a given address * @param self Swap struct to withdraw fees from * @param to Address to send the fees to */ function withdrawAdminFees(Swap storage self, address to) external { for (uint256 i = 0; i < self.pooledTokens.length; i++) { IERC20 token = self.pooledTokens[i]; uint256 balance = token.balanceOf(address(this)).sub( self.balances[i] ); if (balance != 0) { token.safeTransfer(to, balance); } } } /** * @notice Sets the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * @param self Swap struct to update * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(Swap storage self, uint256 newAdminFee) external { require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high"); self.adminFee = newAdminFee; emit NewAdminFee(newAdminFee); } /** * @notice update the swap fee * @dev fee cannot be higher than 1% of each swap * @param self Swap struct to update * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(Swap storage self, uint256 newSwapFee) external { require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high"); self.swapFee = newSwapFee; emit NewSwapFee(newSwapFee); } /** * @notice update the default withdraw fee. This also affects deposits made in the past as well. * @param self Swap struct to update * @param newWithdrawFee new withdraw fee to be applied */ function setDefaultWithdrawFee(Swap storage self, uint256 newWithdrawFee) external { require(newWithdrawFee <= MAX_WITHDRAW_FEE, "Fee is too high"); self.defaultWithdrawFee = newWithdrawFee; emit NewWithdrawFee(newWithdrawFee); } /** * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_ * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param self Swap struct to update * @param futureA_ the new A to ramp towards * @param futureTime_ timestamp when the new A should be reached */ function rampA( Swap storage self, uint256 futureA_, uint256 futureTime_ ) external { require( block.timestamp >= self.initialATime.add(1 days), "Wait 1 day before starting ramp" ); require( futureTime_ >= block.timestamp.add(MIN_RAMP_TIME), "Insufficient ramp time" ); require( futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A" ); uint256 initialAPrecise = _getAPrecise(self); uint256 futureAPrecise = futureA_.mul(A_PRECISION); if (futureAPrecise < initialAPrecise) { require( futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise, "futureA_ is too small" ); } else { require( futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE), "futureA_ is too large" ); } self.initialA = initialAPrecise; self.futureA = futureAPrecise; self.initialATime = block.timestamp; self.futureATime = futureTime_; emit RampA( initialAPrecise, futureAPrecise, block.timestamp, futureTime_ ); } /** * @notice Stops ramping A immediately. Once this function is called, rampA() * cannot be called for another 24 hours * @param self Swap struct to update */ function stopRampA(Swap storage self) external { require(self.futureATime > block.timestamp, "Ramp is already stopped"); uint256 currentA = _getAPrecise(self); self.initialA = currentA; self.futureA = currentA; self.initialATime = block.timestamp; self.futureATime = block.timestamp; emit StopRampA(currentA, block.timestamp); } } // SPDX-License-Identifier: MIT // https://etherscan.io/address/0xC28DF698475dEC994BE00C9C9D8658A548e6304F#code pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/ISwapGuarded.sol"; /** * @title Liquidity Provider Token * @notice This token is an ERC20 detailed token with added capability to be minted by the owner. * It is used to represent user's shares when providing liquidity to swap contracts. */ contract LPTokenGuarded is ERC20Burnable, Ownable { using SafeMath for uint256; // Address of the swap contract that owns this LP token. When a user adds liquidity to the swap contract, // they receive a proportionate amount of this LPToken. ISwapGuarded public swap; // Maps user account to total number of LPToken minted by them. Used to limit minting during guarded release phase mapping(address => uint256) public mintedAmounts; /** * @notice Deploys LPToken contract with given name, symbol, and decimals * @dev the caller of this constructor will become the owner of this contract * @param name_ name of this token * @param symbol_ symbol of this token * @param decimals_ number of decimals this token will be based on */ constructor( string memory name_, string memory symbol_, uint8 decimals_ ) public ERC20(name_, symbol_) { _setupDecimals(decimals_); swap = ISwapGuarded(_msgSender()); } /** * @notice Mints the given amount of LPToken to the recipient. During the guarded release phase, the total supply * and the maximum number of the tokens that a single account can mint are limited. * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint * @param merkleProof the bytes32 array data that is used to prove recipient's address exists in the merkle tree * stored in the allowlist contract. If the pool is not guarded, this parameter is ignored. */ function mint( address recipient, uint256 amount, bytes32[] calldata merkleProof ) external onlyOwner { require(amount != 0, "amount == 0"); // If the pool is in the guarded launch phase, the following checks are done to restrict deposits. // 1. Check if the given merkleProof corresponds to the recipient's address in the merkle tree stored in the // allowlist contract. If the account has been already verified, merkleProof is ignored. // 2. Limit the total number of this LPToken minted to recipient as defined by the allowlist contract. // 3. Limit the total supply of this LPToken as defined by the allowlist contract. if (swap.isGuarded()) { IAllowlist allowlist = swap.getAllowlist(); require( allowlist.verifyAddress(recipient, merkleProof), "Invalid merkle proof" ); uint256 totalMinted = mintedAmounts[recipient].add(amount); require( totalMinted <= allowlist.getPoolAccountLimit(address(swap)), "account deposit limit" ); require( totalSupply().add(amount) <= allowlist.getPoolCap(address(swap)), "pool total supply limit" ); mintedAmounts[recipient] = totalMinted; } _mint(recipient, amount); } /** * @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including * minting and burning. This ensures that swap.updateUserWithdrawFees are called everytime. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override(ERC20) { super._beforeTokenTransfer(from, to, amount); swap.updateUserWithdrawFee(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./IAllowlist.sol"; interface ISwapGuarded { // pool data view functions function getA() external view returns (uint256); function getAllowlist() external view returns (IAllowlist); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline, bytes32[] calldata merkleProof ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); // withdraw fee update function function updateUserWithdrawFee(address recipient, uint256 transferAmount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "../interfaces/IAllowlist.sol"; /** * @title Allowlist * @notice This contract is a registry holding information about how much each swap contract should * contain upto. Swap.sol will rely on this contract to determine whether the pool cap is reached and * also whether a user's deposit limit is reached. */ contract Allowlist is Ownable, IAllowlist { using SafeMath for uint256; // Represents the root node of merkle tree containing a list of eligible addresses bytes32 public merkleRoot; // Maps pool address -> maximum total supply mapping(address => uint256) private poolCaps; // Maps pool address -> maximum amount of pool token mintable per account mapping(address => uint256) private accountLimits; // Maps account address -> boolean value indicating whether it has been checked and verified against the merkle tree mapping(address => bool) private verified; event PoolCap(address indexed poolAddress, uint256 poolCap); event PoolAccountLimit(address indexed poolAddress, uint256 accountLimit); event NewMerkleRoot(bytes32 merkleRoot); /** * @notice Creates this contract and sets the PoolCap of 0x0 with uint256(0x54dd1e) for * crude checking whether an address holds this contract. * @param merkleRoot_ bytes32 that represent a merkle root node. This is generated off chain with the list of * qualifying addresses. */ constructor(bytes32 merkleRoot_) public { merkleRoot = merkleRoot_; // This value will be used as a way of crude checking whether an address holds this Allowlist contract // Value 0x54dd1e has no inherent meaning other than it is arbitrary value that checks for // user error. poolCaps[address(0x0)] = uint256(0x54dd1e); emit PoolCap(address(0x0), uint256(0x54dd1e)); emit NewMerkleRoot(merkleRoot_); } /** * @notice Returns the max mintable amount of the lp token per account in given pool address. * @param poolAddress address of the pool * @return max mintable amount of the lp token per account */ function getPoolAccountLimit(address poolAddress) external view override returns (uint256) { return accountLimits[poolAddress]; } /** * @notice Returns the maximum total supply of the pool token for the given pool address. * @param poolAddress address of the pool */ function getPoolCap(address poolAddress) external view override returns (uint256) { return poolCaps[poolAddress]; } /** * @notice Returns true if the given account's existence has been verified against any of the past or * the present merkle tree. Note that if it has been verified in the past, this function will return true * even if the current merkle tree does not contain the account. * @param account the address to check if it has been verified * @return a boolean value representing whether the account has been verified in the past or the present merkle tree */ function isAccountVerified(address account) external view returns (bool) { return verified[account]; } /** * @notice Checks the existence of keccak256(account) as a node in the merkle tree inferred by the merkle root node * stored in this contract. Pools should use this function to check if the given address qualifies for depositing. * If the given account has already been verified with the correct merkleProof, this function will return true when * merkleProof is empty. The verified status will be overwritten if the previously verified user calls this function * with an incorrect merkleProof. * @param account address to confirm its existence in the merkle tree * @param merkleProof data that is used to prove the existence of given parameters. This is generated * during the creation of the merkle tree. Users should retrieve this data off-chain. * @return a boolean value that corresponds to whether the address with the proof has been verified in the past * or if they exist in the current merkle tree. */ function verifyAddress(address account, bytes32[] calldata merkleProof) external override returns (bool) { if (merkleProof.length != 0) { // Verify the account exists in the merkle tree via the MerkleProof library bytes32 node = keccak256(abi.encodePacked(account)); if (MerkleProof.verify(merkleProof, merkleRoot, node)) { verified[account] = true; return true; } } return verified[account]; } // ADMIN FUNCTIONS /** * @notice Sets the account limit of allowed deposit amounts for the given pool * @param poolAddress address of the pool * @param accountLimit the max number of the pool token a single user can mint */ function setPoolAccountLimit(address poolAddress, uint256 accountLimit) external onlyOwner { require(poolAddress != address(0x0), "0x0 is not a pool address"); accountLimits[poolAddress] = accountLimit; emit PoolAccountLimit(poolAddress, accountLimit); } /** * @notice Sets the max total supply of LPToken for the given pool address * @param poolAddress address of the pool * @param poolCap the max total supply of the pool token */ function setPoolCap(address poolAddress, uint256 poolCap) external onlyOwner { require(poolAddress != address(0x0), "0x0 is not a pool address"); poolCaps[poolAddress] = poolCap; emit PoolCap(poolAddress, poolCap); } /** * @notice Updates the merkle root that is stored in this contract. This can only be called by * the owner. If more addresses are added to the list, a new merkle tree and a merkle root node should be generated, * and merkleRoot should be updated accordingly. * @param merkleRoot_ a new merkle root node that contains a list of deposit allowed addresses */ function updateMerkleRoot(bytes32 merkleRoot_) external onlyOwner { merkleRoot = merkleRoot_; emit NewMerkleRoot(merkleRoot_); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { 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; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./OwnerPausable.sol"; import "./SwapUtilsGuarded.sol"; import "../MathUtils.sol"; import "./Allowlist.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapGuarded is OwnerPausable, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; using SwapUtilsGuarded for SwapUtilsGuarded.Swap; // Struct storing data responsible for automatic market maker functionalities. In order to // access this data, this contract uses SwapUtils library. For more details, see SwapUtilsGuarded.sol SwapUtilsGuarded.Swap public swapStorage; // Address to allowlist contract that holds information about maximum totaly supply of lp tokens // and maximum mintable amount per user address. As this is immutable, this will become a constant // after initialization. IAllowlist private immutable allowlist; // Boolean value that notates whether this pool is guarded or not. When isGuarded is true, // addLiquidity function will be restricted by limits defined in allowlist contract. bool private guarded = true; // Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool. // getTokenIndex function also relies on this mapping to retrieve token index. mapping(address => uint8) private tokenIndexes; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); /** * @notice Deploys this Swap contract with given parameters as default * values. This will also deploy a LPToken that represents users * LP position. The owner of LPToken will be this contract - which means * only this contract is allowed to mint new tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param _withdrawFee default withdrawFee to be initialized with * @param _allowlist address of allowlist contract for guarded launch */ constructor( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, IAllowlist _allowlist ) public OwnerPausable() ReentrancyGuard() { // Check _pooledTokens and precisions parameter require(_pooledTokens.length > 1, "_pooledTokens.length <= 1"); require(_pooledTokens.length <= 32, "_pooledTokens.length > 32"); require( _pooledTokens.length == decimals.length, "_pooledTokens decimals mismatch" ); uint256[] memory precisionMultipliers = new uint256[](decimals.length); for (uint8 i = 0; i < _pooledTokens.length; i++) { if (i > 0) { // Check if index is already used. Check if 0th element is a duplicate. require( tokenIndexes[address(_pooledTokens[i])] == 0 && _pooledTokens[0] != _pooledTokens[i], "Duplicate tokens" ); } require( address(_pooledTokens[i]) != address(0), "The 0 address isn't an ERC-20" ); require( decimals[i] <= SwapUtilsGuarded.POOL_PRECISION_DECIMALS, "Token decimals exceeds max" ); precisionMultipliers[i] = 10 ** uint256(SwapUtilsGuarded.POOL_PRECISION_DECIMALS).sub( uint256(decimals[i]) ); tokenIndexes[address(_pooledTokens[i])] = i; } // Check _a, _fee, _adminFee, _withdrawFee, _allowlist parameters require(_a < SwapUtilsGuarded.MAX_A, "_a exceeds maximum"); require(_fee < SwapUtilsGuarded.MAX_SWAP_FEE, "_fee exceeds maximum"); require( _adminFee < SwapUtilsGuarded.MAX_ADMIN_FEE, "_adminFee exceeds maximum" ); require( _withdrawFee < SwapUtilsGuarded.MAX_WITHDRAW_FEE, "_withdrawFee exceeds maximum" ); require( _allowlist.getPoolCap(address(0x0)) == uint256(0x54dd1e), "Allowlist check failed" ); // Initialize swapStorage struct swapStorage.lpToken = new LPTokenGuarded( lpTokenName, lpTokenSymbol, SwapUtilsGuarded.POOL_PRECISION_DECIMALS ); swapStorage.pooledTokens = _pooledTokens; swapStorage.tokenPrecisionMultipliers = precisionMultipliers; swapStorage.balances = new uint256[](_pooledTokens.length); swapStorage.initialA = _a.mul(SwapUtilsGuarded.A_PRECISION); swapStorage.futureA = _a.mul(SwapUtilsGuarded.A_PRECISION); swapStorage.initialATime = 0; swapStorage.futureATime = 0; swapStorage.swapFee = _fee; swapStorage.adminFee = _adminFee; swapStorage.defaultWithdrawFee = _withdrawFee; // Initialize variables related to guarding the initial deposits allowlist = _allowlist; guarded = true; } /*** MODIFIERS ***/ /** * @notice Modifier to check deadline against current timestamp * @param deadline latest timestamp to accept this transaction */ modifier deadlineCheck(uint256 deadline) { require(block.timestamp <= deadline, "Deadline not met"); _; } /*** VIEW FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @return A parameter */ function getA() external view returns (uint256) { return swapStorage.getA(); } /** * @notice Return A in its raw precision form * @dev See the StableSwap paper for details * @return A parameter in its raw precision form */ function getAPrecise() external view returns (uint256) { return swapStorage.getAPrecise(); } /** * @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) public view returns (IERC20) { require(index < swapStorage.pooledTokens.length, "Out of range"); return swapStorage.pooledTokens[index]; } /** * @notice Return the index of the given token address. Reverts if no matching * token is found. * @param tokenAddress address of the token * @return the index of the given token address */ function getTokenIndex(address tokenAddress) external view returns (uint8) { uint8 index = tokenIndexes[tokenAddress]; require( address(getToken(index)) == tokenAddress, "Token does not exist" ); return index; } /** * @notice Reads and returns the address of the allowlist that is set during deployment of this contract * @return the address of the allowlist contract casted to the IAllowlist interface */ function getAllowlist() external view returns (IAllowlist) { return allowlist; } /** * @notice Return timestamp of last deposit of given address * @return timestamp of the last deposit made by the given address */ function getDepositTimestamp(address user) external view returns (uint256) { return swapStorage.getDepositTimestamp(user); } /** * @notice Return current balance of the pooled token at given index * @param index the index of the token * @return current balance of the pooled token at given index with token's native precision */ function getTokenBalance(uint8 index) external view returns (uint256) { require(index < swapStorage.pooledTokens.length, "Index out of range"); return swapStorage.balances[index]; } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view returns (uint256) { return swapStorage.getVirtualPrice(); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param account address that is depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { return swapStorage.calculateTokenAmount(account, amounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param account the address that is withdrawing tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(address account, uint256 amount) external view returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(account, amount); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param account the address that is withdrawing tokens * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount) { (availableTokenAmount, ) = swapStorage.calculateWithdrawOneToken( account, tokenAmount, tokenIndex ); } /** * @notice Calculate the fee that is applied when the given user withdraws. The withdraw fee * decays linearly over period of 4 weeks. For example, depositing and withdrawing right away * will charge you the full amount of withdraw fee. But withdrawing after 4 weeks will charge you * no additional fees. * @dev returned value should be divided by FEE_DENOMINATOR to convert to correct decimals * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(address user) external view returns (uint256) { return swapStorage.calculateCurrentWithdrawFee(user); } /** * @notice This function reads the accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin's token balance in the token's precision */ function getAdminBalance(uint256 index) external view returns (uint256) { return swapStorage.getAdminBalance(index); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy); } /** * @notice Add liquidity to the pool with given amounts during guarded launch phase. Only users * with valid address and proof can successfully call this function. When this function is called * after the guarded release phase is over, the merkleProof is ignored. * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @param merkleProof data generated when constructing the allowlist merkle tree. Users can * get this data off chain. Even if the address is in the allowlist, users must include * a valid proof for this call to succeed. If the pool is no longer in the guarded release phase, * this parameter is ignored. * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline, bytes32[] calldata merkleProof ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.addLiquidity(amounts, minToMint, merkleProof); } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return swapStorage.removeLiquidity(amount, minAmounts); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the user withdraw fee. This function can only be called by * the pool token. Should be used to update the withdraw fee on transfer of pool tokens. * Transferring your pool token will reset the 4 weeks period. If the recipient is already * holding some pool tokens, the withdraw fee will be discounted in respective amounts. * @param recipient address of the recipient of pool token * @param transferAmount amount of pool token to transfer */ function updateUserWithdrawFee(address recipient, uint256 transferAmount) external { require( msg.sender == address(swapStorage.lpToken), "Only callable by pool token" ); swapStorage.updateUserWithdrawFee(recipient, transferAmount); } /** * @notice Withdraw all admin fees to the contract owner */ function withdrawAdminFees() external onlyOwner { swapStorage.withdrawAdminFees(owner()); } /** * @notice Update the admin fee. Admin fee takes portion of the swap fee. * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(uint256 newAdminFee) external onlyOwner { swapStorage.setAdminFee(newAdminFee); } /** * @notice Update the swap fee to be applied on swaps * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(uint256 newSwapFee) external onlyOwner { swapStorage.setSwapFee(newSwapFee); } /** * @notice Update the withdraw fee. This fee decays linearly over 4 weeks since * user's last deposit. * @param newWithdrawFee new withdraw fee to be applied on future deposits */ function setDefaultWithdrawFee(uint256 newWithdrawFee) external onlyOwner { swapStorage.setDefaultWithdrawFee(newWithdrawFee); } /** * @notice Start ramping up or down A parameter towards given futureA and futureTime * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param futureA the new A to ramp towards * @param futureTime timestamp when the new A should be reached */ function rampA(uint256 futureA, uint256 futureTime) external onlyOwner { swapStorage.rampA(futureA, futureTime); } /** * @notice Stop ramping A immediately. Reverts if ramp A is already stopped. */ function stopRampA() external onlyOwner { swapStorage.stopRampA(); } /** * @notice Disables the guarded launch phase, removing any limits on deposit amounts and addresses */ function disableGuard() external onlyOwner { guarded = false; } /** * @notice Reads and returns current guarded status of the pool * @return guarded_ boolean value indicating whether the deposits should be guarded */ function isGuarded() external view returns (bool) { return guarded; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; /** * @title OwnerPausable * @notice An ownable contract allows the owner to pause and unpause the * contract without a delay. * @dev Only methods using the provided modifiers will be paused. */ contract OwnerPausable is Ownable, Pausable { /** * @notice Pause the contract. Revert if already paused. */ function pause() external onlyOwner { Pausable._pause(); } /** * @notice Unpause the contract. Revert if already unpaused. */ function unpause() external onlyOwner { Pausable._unpause(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Generic ERC20 token * @notice This contract simulates a generic ERC20 token that is mintable and burnable. */ contract GenericERC20 is ERC20, Ownable { /** * @notice Deploy this contract with given name, symbol, and decimals * @dev the caller of this constructor will become the owner of this contract * @param name_ name of this token * @param symbol_ symbol of this token * @param decimals_ number of decimals this token will be based on */ constructor( string memory name_, string memory symbol_, uint8 decimals_ ) public ERC20(name_, symbol_) { _setupDecimals(decimals_); } /** * @notice Mints given amount of tokens to recipient * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint */ function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "amount == 0"); _mint(recipient, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./interfaces/ISwap.sol"; import "./helper/BaseBoringBatchable.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title GeneralizedSwapMigrator * @notice This contract is responsible for migration liquidity between pools * Users can use this contract to remove their liquidity from the old pools and add them to the new * ones with a single transaction. */ contract GeneralizedSwapMigrator is Ownable, BaseBoringBatchable { using SafeERC20 for IERC20; struct MigrationData { address newPoolAddress; IERC20 oldPoolLPTokenAddress; IERC20 newPoolLPTokenAddress; IERC20[] tokens; } uint256 private constant MAX_UINT256 = 2**256 - 1; mapping(address => MigrationData) public migrationMap; event AddMigrationData(address indexed oldPoolAddress, MigrationData mData); event Migrate( address indexed migrator, address indexed oldPoolAddress, uint256 oldLPTokenAmount, uint256 newLPTokenAmount ); constructor() public Ownable() {} /** * @notice Add new migration data to the contract * @param oldPoolAddress pool address to migrate from * @param mData MigrationData struct that contains information of the old and new pools * @param overwrite should overwrite existing migration data */ function addMigrationData( address oldPoolAddress, MigrationData memory mData, bool overwrite ) external onlyOwner { // Check if (!overwrite) { require( address(migrationMap[oldPoolAddress].oldPoolLPTokenAddress) == address(0), "cannot overwrite existing migration data" ); } require( address(mData.oldPoolLPTokenAddress) != address(0), "oldPoolLPTokenAddress == 0" ); require( address(mData.newPoolLPTokenAddress) != address(0), "newPoolLPTokenAddress == 0" ); for (uint8 i = 0; i < 32; i++) { address oldPoolToken; try ISwap(oldPoolAddress).getToken(i) returns (IERC20 token) { oldPoolToken = address(token); } catch { require(i > 0, "Failed to get tokens underlying Saddle pool."); oldPoolToken = address(0); } try ISwap(mData.newPoolAddress).getToken(i) returns (IERC20 token) { require( oldPoolToken == address(token) && oldPoolToken == address(mData.tokens[i]), "Failed to match tokens list" ); } catch { require(i > 0, "Failed to get tokens underlying Saddle pool."); require( oldPoolToken == address(0) && i == mData.tokens.length, "Failed to match tokens list" ); break; } } // Effect migrationMap[oldPoolAddress] = mData; // Interaction // Approve old LP Token to be used for withdraws. mData.oldPoolLPTokenAddress.approve(oldPoolAddress, MAX_UINT256); // Approve underlying tokens to be used for deposits. for (uint256 i = 0; i < mData.tokens.length; i++) { mData.tokens[i].safeApprove(mData.newPoolAddress, 0); mData.tokens[i].safeApprove(mData.newPoolAddress, MAX_UINT256); } emit AddMigrationData(oldPoolAddress, mData); } /** * @notice Migrates saddle LP tokens from a pool to another * @param oldPoolAddress pool address to migrate from * @param amount amount of LP tokens to migrate * @param minAmount of new LP tokens to receive */ function migrate( address oldPoolAddress, uint256 amount, uint256 minAmount ) external returns (uint256) { // Check MigrationData memory mData = migrationMap[oldPoolAddress]; require( address(mData.oldPoolLPTokenAddress) != address(0), "migration is not available" ); // Interactions // Transfer old LP token from the caller mData.oldPoolLPTokenAddress.safeTransferFrom( msg.sender, address(this), amount ); // Remove liquidity from the old pool uint256[] memory amounts = ISwap(oldPoolAddress).removeLiquidity( amount, new uint256[](mData.tokens.length), MAX_UINT256 ); // Add acquired liquidity to the new pool uint256 mintedAmount = ISwap(mData.newPoolAddress).addLiquidity( amounts, minAmount, MAX_UINT256 ); // Transfer new LP Token to the caller mData.newPoolLPTokenAddress.safeTransfer(msg.sender, mintedAmount); emit Migrate(msg.sender, oldPoolAddress, amount, mintedAmount); return mintedAmount; } /** * @notice Rescues any token that may be sent to this contract accidentally. * @param token Amount of old LPToken to migrate * @param to Minimum amount of new LPToken to receive */ function rescue(IERC20 token, address to) external onlyOwner { token.safeTransfer(to, token.balanceOf(address(this))); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // solhint-disable avoid-low-level-calls // solhint-disable no-inline-assembly // Audit on 5-Jan-2021 by Keno and BoringCrypto // WARNING!!! // Combining BoringBatchable with msg.value can cause double spending issues // https://www.paradigm.xyz/2021/08/two-rights-might-make-a-wrong/ contract BaseBoringBatchable { /// @dev Helper function to extract a useful revert message from a failed call. /// If the returned data is malformed or not correctly abi encoded then this call can fail itself. function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } /// @notice Allows batched call to self (this contract). /// @param calls An array of inputs for each call. /// @param revertOnFail If True then reverts after a failed call and stops doing further calls. // F1: External is ok here because this is the batch function, adding it to a batch makes no sense // F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value // C3: The length of the loop is fully under user control, so can't be exploited // C7: Delegatecall is only used on the same contract, so it's safe function batch(bytes[] calldata calls, bool revertOnFail) external payable { for (uint256 i = 0; i < calls.length; i++) { (bool success, bytes memory result) = address(this).delegatecall( calls[i] ); if (!success && revertOnFail) { revert(_getRevertMsg(result)); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../Swap.sol"; import "./MetaSwapUtils.sol"; /** * @title MetaSwap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * MetaSwap is a modified version of Swap that allows Swap's LP token to be utilized in pooling with other tokens. * As an example, if there is a Swap pool consisting of [DAI, USDC, USDT], then a MetaSwap pool can be created * with [sUSD, BaseSwapLPToken] to allow trades between either the LP token or the underlying tokens and sUSD. * Note that when interacting with MetaSwap, users cannot deposit or withdraw via underlying tokens. In that case, * `MetaSwapDeposit.sol` can be additionally deployed to allow interacting with unwrapped representations of the tokens. * * @dev Most of the logic is stored as a library `MetaSwapUtils` for the sake of reducing contract's * deployment size. */ contract MetaSwap is Swap { using MetaSwapUtils for SwapUtils.Swap; MetaSwapUtils.MetaSwap public metaSwapStorage; uint256 constant MAX_UINT256 = 2**256 - 1; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwapUnderlying( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual override returns (uint256) { return MetaSwapUtils.getVirtualPrice(swapStorage, metaSwapStorage); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual override returns (uint256) { return MetaSwapUtils.calculateSwap( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx ); } /** * @notice Calculate amount of tokens you receive on swap. For this function, * the token indices are flattened out so that underlying tokens are represented. * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return MetaSwapUtils.calculateSwapUnderlying( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx ); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view virtual override returns (uint256) { return MetaSwapUtils.calculateTokenAmount( swapStorage, metaSwapStorage, amounts, deposit ); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view virtual override returns (uint256) { return MetaSwapUtils.calculateWithdrawOneToken( swapStorage, metaSwapStorage, tokenAmount, tokenIndex ); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice This overrides Swap's initialize function to prevent initializing * without the address of the base Swap contract. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) public virtual override initializer { revert("use initializeMetaSwap() instead"); } /** * @notice Initializes this MetaSwap contract with the given parameters. * MetaSwap uses an existing Swap pool to expand the available liquidity. * _pooledTokens array should contain the base Swap pool's LP token as * the last element. For example, if there is a Swap pool consisting of * [DAI, USDC, USDT]. Then a MetaSwap pool can be created with [sUSD, BaseSwapLPToken] * as _pooledTokens. * * This will also deploy the LPToken that represents users' * LP position. The owner of LPToken will be this contract - which means * only this contract is allowed to mint new tokens. * * @param _pooledTokens an array of ERC20s this pool will accept. The last * element must be an existing Swap pool's LP token's address. * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with */ function initializeMetaSwap( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress, ISwap baseSwap ) external virtual initializer { Swap.initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress ); // MetaSwap initializer metaSwapStorage.baseSwap = baseSwap; metaSwapStorage.baseVirtualPrice = baseSwap.getVirtualPrice(); metaSwapStorage.baseCacheLastUpdated = block.timestamp; // Read all tokens that belong to baseSwap { uint8 i; for (; i < 32; i++) { try baseSwap.getToken(i) returns (IERC20 token) { metaSwapStorage.baseTokens.push(token); token.safeApprove(address(baseSwap), MAX_UINT256); } catch { break; } } require(i > 1, "baseSwap must pool at least 2 tokens"); } // Check the last element of _pooledTokens is owned by baseSwap IERC20 baseLPToken = _pooledTokens[_pooledTokens.length - 1]; require( LPToken(address(baseLPToken)).owner() == address(baseSwap), "baseLPToken is not owned by baseSwap" ); // Pre-approve the baseLPToken to be used by baseSwap baseLPToken.safeApprove(address(baseSwap), MAX_UINT256); } /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.swap( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx, minDy ); } /** * @notice Swap two tokens using this pool and the base pool. * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.swapUnderlying( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx, minDy ); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.addLiquidity( swapStorage, metaSwapStorage, amounts, minToMint ); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.removeLiquidityOneToken( swapStorage, metaSwapStorage, tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.removeLiquidityImbalance( swapStorage, metaSwapStorage, amounts, maxBurnAmount ); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../../MathUtils.sol"; contract TestMathUtils { using MathUtils for uint256; function difference(uint256 a, uint256 b) public pure returns (uint256) { return a.difference(b); } function within1(uint256 a, uint256 b) public pure returns (bool) { return a.within1(b); } }
Checks the existence of keccak256(account) as a node in the merkle tree inferred by the merkle root node stored in this contract. Pools should use this function to check if the given address qualifies for depositing. If the given account has already been verified with the correct merkleProof, this function will return true when merkleProof is empty. The verified status will be overwritten if the previously verified user calls this function with an incorrect merkleProof. account address to confirm its existence in the merkle tree merkleProof data that is used to prove the existence of given parameters. This is generated during the creation of the merkle tree. Users should retrieve this data off-chain. return a boolean value that corresponds to whether the address with the proof has been verified in the past or if they exist in the current merkle tree./ Verify the account exists in the merkle tree via the MerkleProof library
function verifyAddress(address account, bytes32[] calldata merkleProof) external override returns (bool) { if (merkleProof.length != 0) { bytes32 node = keccak256(abi.encodePacked(account)); if (MerkleProof.verify(merkleProof, merkleRoot, node)) { verified[account] = true; return true; } } return verified[account]; }
970,628
./full_match/4/0x38528Bd6119D645B5c004c8edAb4C86b752e9bA0/sources/contracts/SupermanDns.sol
publicif (msg.sender != owner()) {require(msg.value >= cost _mintAmount);
function mint(address _to, uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(!paused); require(_mintAmount > 0); require(_mintAmount <= maxMintAmount); require(supply + _mintAmount <= maxSupply); require(msg.sender == owner(), "Only owner allowed to mint"); if(whitelisted[msg.sender] != true) { require(msg.sender == owner(), "Only owner allowed to mint"); } }*/
13,355,888
pragma solidity 0.5.12; import "./library/ReentrancyGuard.sol"; import "./library/Pausable.sol"; import "./library/ERC20SafeTransfer.sol"; import "./library/SafeMath.sol"; import "./interface/IDispatcher.sol"; import "./interface/IHandler.sol"; contract DToken is ReentrancyGuard, Pausable, ERC20SafeTransfer { using SafeMath for uint256; // --- Data --- bool private initialized; // Flag of initialize data struct DTokenData { uint256 exchangeRate; uint256 totalInterest; } DTokenData public data; address public feeRecipient; mapping(bytes4 => uint256) public originationFee; // Trade fee address public dispatcher; address public token; address public swapModel; uint256 constant BASE = 10**18; // --- ERC20 Data --- string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; struct Balance { uint256 value; uint256 exchangeRate; uint256 interest; } mapping(address => Balance) public balances; mapping(address => mapping(address => uint256)) public allowance; // --- User Triggered Event --- event Approval(address indexed src, address indexed guy, uint256 wad); event Transfer(address indexed src, address indexed dst, uint256 wad); event Interest( address indexed src, uint256 interest, uint256 increase, uint256 totalInterest ); event Mint( address indexed account, uint256 indexed pie, uint256 wad, uint256 totalSupply, uint256 exchangeRate ); event Redeem( address indexed account, uint256 indexed pie, uint256 wad, uint256 totalSupply, uint256 exchangeRate ); // --- Admin Triggered Event --- event Rebalance( address[] withdraw, uint256[] withdrawAmount, address[] supply, uint256[] supplyAmount ); event TransferFee(address token, address feeRecipient, uint256 amount); event FeeRecipientSet(address oldFeeRecipient, address newFeeRecipient); event NewDispatcher(address oldDispatcher, address Dispatcher); event NewSwapModel(address _oldSwapModel, address _newSwapModel); event NewOriginationFee( bytes4 sig, uint256 oldOriginationFeeMantissa, uint256 newOriginationFeeMantissa ); /** * The constructor is used here to ensure that the implementation * contract is initialized. An uncontrolled implementation * contract might lead to misleading state * for users who accidentally interact with it. */ constructor( string memory _name, string memory _symbol, address _token, address _dispatcher ) public { initialize(_name, _symbol, _token, _dispatcher); } /************************/ /*** Admin Operations ***/ /************************/ // --- Init --- function initialize( string memory _name, string memory _symbol, address _token, address _dispatcher ) public { require(!initialized, "initialize: Already initialized!"); owner = msg.sender; initReentrancyStatus(); feeRecipient = address(this); name = _name; symbol = _symbol; token = _token; dispatcher = _dispatcher; decimals = IERC20(_token).decimals(); data.exchangeRate = BASE; initialized = true; emit NewDispatcher(address(0), _dispatcher); } /** * @dev Authorized function to set a new dispatcher. * @param _newDispatcher New dispatcher contract address. */ function updateDispatcher(address _newDispatcher) external auth { address _oldDispatcher = dispatcher; require( _newDispatcher != address(0) && _newDispatcher != _oldDispatcher, "updateDispatcher: dispatcher can be not set to 0 or the current one." ); dispatcher = _newDispatcher; emit NewDispatcher(_oldDispatcher, _newDispatcher); } /** * @dev Authorized function to set a new model contract to swap. * @param _newSwapModel New model contract address. */ function setSwapModel(address _newSwapModel) external auth { address _oldSwapModel = swapModel; require( _newSwapModel != address(0) && _newSwapModel != _oldSwapModel, "setSwapModel: swap model can be not set to 0 or the current one." ); swapModel = _newSwapModel; emit NewSwapModel(_oldSwapModel, _newSwapModel); } /** * @dev Authorized function to set a new fee recipient. * @param _newFeeRecipient The address allowed to collect fees. */ function setFeeRecipient(address _newFeeRecipient) external auth { address _oldFeeRecipient = feeRecipient; require( _newFeeRecipient != address(0) && _newFeeRecipient != _oldFeeRecipient, "setFeeRecipient: feeRecipient can be not set to 0 or the current one." ); feeRecipient = _newFeeRecipient; emit FeeRecipientSet(_oldFeeRecipient, feeRecipient); } /** * @dev Authorized function to set a new origination fee. * @param _sig function signature. * @param _newOriginationFee New trading fee ratio, scaled by 1e18. */ function updateOriginationFee(bytes4 _sig, uint256 _newOriginationFee) external auth { require( _newOriginationFee < BASE, "updateOriginationFee: incorrect fee." ); uint256 _oldOriginationFee = originationFee[_sig]; require( _oldOriginationFee != _newOriginationFee, "updateOriginationFee: fee has already set to this value." ); originationFee[_sig] = _newOriginationFee; emit NewOriginationFee(_sig, _oldOriginationFee, _newOriginationFee); } /** * @dev Authorized function to swap airdrop tokens to increase yield. * @param _token Airdrop token to swap from. * @param _amount Amount to swap. */ function swap(address _token, uint256 _amount) external auth { require(swapModel != address(0), "swap: no swap model available!"); (bool success, ) = swapModel.delegatecall( abi.encodeWithSignature("swap(address,uint256)", _token, _amount) ); require(success, "swap: swap to another token failed!"); } /** * @dev Authorized function to transfer token out. * @param _token The underlying token. * @param _amount Amount to transfer. */ function transferFee(address _token, uint256 _amount) external auth { require( feeRecipient != address(this), "transferFee: Can not transfer fee back to this contract." ); require( doTransferOut(_token, feeRecipient, _amount), "transferFee: Token transfer out of contract failed." ); emit TransferFee(_token, feeRecipient, _amount); } /** * @dev Authorized function to rebalance underlying token between handlers. * @param _withdraw From which handlers to withdraw. * @param _withdrawAmount Amounts to withdraw. * @param _deposit To which handlers to deposit. * @param _depositAmount Amounts to deposit. */ function rebalance( address[] calldata _withdraw, uint256[] calldata _withdrawAmount, address[] calldata _deposit, uint256[] calldata _depositAmount ) external auth { require( _withdraw.length == _withdrawAmount.length && _deposit.length == _depositAmount.length, "rebalance: the length of addresses and amounts must match." ); address _token = token; address _defaultHandler = IDispatcher(dispatcher).defaultHandler(); // Start withdrawing uint256[] memory _realWithdrawAmount = new uint256[]( _withdrawAmount.length ); for (uint256 i = 0; i < _withdraw.length; i++) { // No need to withdraw from default handler, all withdrown tokens go to it if (_withdrawAmount[i] == 0 || _defaultHandler == _withdraw[i]) continue; // Check whether we want to withdraw all _realWithdrawAmount[i] = _withdrawAmount[i] == uint256(-1) ? IHandler(_withdraw[i]).getRealBalance(_token) : _withdrawAmount[i]; // Ensure we get the exact amount we wanted // Will fail if there is fee for withdraw // For withdraw all (-1) we check agaist the real amount require( IHandler(_withdraw[i]).withdraw(_token, _withdrawAmount[i]) == _realWithdrawAmount[i], "rebalance: actual withdrown amount does not match the wanted" ); // Transfer to the default handler require( doTransferFrom( _token, _withdraw[i], _defaultHandler, _realWithdrawAmount[i] ), "rebalance: transfer to default handler failed" ); } // Start depositing for (uint256 i = 0; i < _deposit.length; i++) { require( IDispatcher(dispatcher).isHandlerActive(_deposit[i]) && IHandler(_deposit[i]).tokenIsEnabled(_token), "rebalance: both handler and token must be enabled" ); // No need to deposit into default handler, it has been there already. if (_depositAmount[i] == 0 || _defaultHandler == _deposit[i]) continue; // Transfer from default handler to the target one. require( doTransferFrom( _token, _defaultHandler, _deposit[i], _depositAmount[i] ), "rebalance: transfer to target handler failed" ); // Deposit into the target lending market require( IHandler(_deposit[i]).deposit(_token, _depositAmount[i]) == _depositAmount[i], "rebalance: deposit to the target protocal failed" ); } emit Rebalance(_withdraw, _withdrawAmount, _deposit, _depositAmount); } /*************************************/ /*** Helpers only for internal use ***/ /*************************************/ function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(y) / BASE; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(BASE).div(y); } function rdivup(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(BASE).add(y.sub(1)).div(y); } /** * @dev Current newest exchange rate, scaled by 1e18. */ function getCurrentExchangeRate() internal returns (uint256) { address[] memory _handlers = getHandlers(); return getCurrentExchangeRateByHandler(_handlers, token); } /** * @dev Calculate the exchange rate according to handlers and their token balance. * @param _handlers The list of handlers. * @param _token The underlying token. * @return Current exchange rate between token and dToken. */ function getCurrentExchangeRateByHandler( address[] memory _handlers, address _token ) internal returns (uint256) { uint256 _totalToken = 0; // Get the total underlying token amount from handlers for (uint256 i = 0; i < _handlers.length; i++) _totalToken = _totalToken.add( IHandler(_handlers[i]).getRealBalance(_token) ); // Reset exchange rate to 1 when there is no dToken left uint256 _exchangeRate = (totalSupply == 0) ? BASE : rdiv(_totalToken, totalSupply); require(_exchangeRate > 0, "Exchange rate should not be 0!"); return _exchangeRate; } /** * @dev Update global and user's accrued interest. * @param _account User account. * @param _exchangeRate Current exchange rate. */ function updateInterest(address _account, uint256 _exchangeRate) internal { Balance storage _balance = balances[_account]; // There have been some interest since last time if ( _balance.exchangeRate > 0 && _exchangeRate > _balance.exchangeRate ) { uint256 _interestIncrease = rmul( _exchangeRate.sub(_balance.exchangeRate), _balance.value ); // Update user's accrued interst _balance.interest = _balance.interest.add(_interestIncrease); // Update global accrued interst data.totalInterest = data.totalInterest.add(_interestIncrease); emit Interest( _account, _balance.interest, _interestIncrease, data.totalInterest ); } // Update the exchange rate accordingly _balance.exchangeRate = _exchangeRate; data.exchangeRate = _exchangeRate; } /** * @dev Internal function to withdraw specific amount underlying token from handlers, * all tokens withdrown will be put into default handler. * @param _defaultHandler default handler acting as temporary pool. * @param _handlers list of handlers to withdraw. * @param _amounts list of amounts to withdraw. * @return The actual withdrown amount. */ function withdrawFromHandlers( address _defaultHandler, address[] memory _handlers, uint256[] memory _amounts ) internal returns (uint256 _totalWithdrown) { address _token = token; uint256 _withdrown; for (uint256 i = 0; i < _handlers.length; i++) { if (_amounts[i] == 0) continue; // The handler withdraw underlying token from the market. _withdrown = IHandler(_handlers[i]).withdraw(_token, _amounts[i]); require( _withdrown > 0, "withdrawFromHandlers: handler withdraw failed" ); // Transfer token from other handlers to default handler // Default handler acts as a temporary pool here if (_defaultHandler != _handlers[i]) { require( doTransferFrom( _token, _handlers[i], _defaultHandler, _withdrown ), "withdrawFromHandlers: transfer to default handler failed" ); } _totalWithdrown = _totalWithdrown.add(_withdrown); } } /***********************/ /*** User Operations ***/ /***********************/ struct MintLocalVars { address token; address[] handlers; uint256[] amounts; uint256 exchangeRate; uint256 originationFee; uint256 fee; uint256 netDepositAmount; uint256 mintAmount; uint256 wad; } /** * @dev Deposit token to earn savings, but only when the contract is not paused. * @param _dst Account who will get dToken. * @param _pie Amount to deposit, scaled by 1e18. */ function mint(address _dst, uint256 _pie) external nonReentrant whenNotPaused { MintLocalVars memory _mintLocal; _mintLocal.token = token; // Charge the fee first _mintLocal.originationFee = originationFee[msg.sig]; _mintLocal.fee = rmul(_pie, _mintLocal.originationFee); if (_mintLocal.fee > 0) require( doTransferFrom( _mintLocal.token, msg.sender, feeRecipient, _mintLocal.fee ), "mint: transferFrom fee failed" ); _mintLocal.netDepositAmount = _pie.sub(_mintLocal.fee); // Get deposit strategy base on the deposit amount. (_mintLocal.handlers, _mintLocal.amounts) = IDispatcher(dispatcher) .getDepositStrategy(_mintLocal.netDepositAmount); require( _mintLocal.handlers.length > 0, "mint: no deposit strategy available, possibly due to a paused handler" ); // Get current exchange rate. _mintLocal.exchangeRate = getCurrentExchangeRateByHandler( _mintLocal.handlers, _mintLocal.token ); for (uint256 i = 0; i < _mintLocal.handlers.length; i++) { // If deposit amount is 0 for this handler, then pass. if (_mintLocal.amounts[i] == 0) continue; // Transfer the calculated token amount from `msg.sender` to the `handler`. require( doTransferFrom( _mintLocal.token, msg.sender, _mintLocal.handlers[i], _mintLocal.amounts[i] ), "mint: transfer token to handler failed." ); // The `handler` deposit obtained token to corresponding market to earn savings. // Add the returned amount to the acutal mint amount, there could be fee when deposit _mintLocal.mintAmount = _mintLocal.mintAmount.add( IHandler(_mintLocal.handlers[i]).deposit( _mintLocal.token, _mintLocal.amounts[i] ) ); } require( _mintLocal.mintAmount <= _mintLocal.netDepositAmount, "mint: deposited more than intended" ); // Calculate amount of the dToken based on current exchange rate. _mintLocal.wad = rdiv(_mintLocal.mintAmount, _mintLocal.exchangeRate); require( _mintLocal.wad > 0, "mint: can not mint the smallest unit with the given amount" ); updateInterest(_dst, _mintLocal.exchangeRate); Balance storage _balance = balances[_dst]; _balance.value = _balance.value.add(_mintLocal.wad); totalSupply = totalSupply.add(_mintLocal.wad); emit Transfer(address(0), _dst, _mintLocal.wad); emit Mint( _dst, _pie, _mintLocal.wad, totalSupply, _mintLocal.exchangeRate ); } struct RedeemLocalVars { address token; address defaultHandler; address[] handlers; uint256[] amounts; uint256 exchangeRate; uint256 originationFee; uint256 fee; uint256 grossAmount; uint256 redeemTotalAmount; uint256 userAmount; } /** * @dev Redeem token according to input dToken amount, * but only when the contract is not paused. * @param _src Account who will spend dToken. * @param _wad Amount to burn dToken, scaled by 1e18. */ function redeem(address _src, uint256 _wad) external nonReentrant whenNotPaused { // Check the balance and allowance Balance storage _balance = balances[_src]; require(_balance.value >= _wad, "redeem: insufficient balance"); if (_src != msg.sender && allowance[_src][msg.sender] != uint256(-1)) { require( allowance[_src][msg.sender] >= _wad, "redeem: insufficient allowance" ); allowance[_src][msg.sender] = allowance[_src][msg.sender].sub(_wad); } RedeemLocalVars memory _redeemLocal; _redeemLocal.token = token; // Get current exchange rate. _redeemLocal.exchangeRate = getCurrentExchangeRate(); _redeemLocal.grossAmount = rmul(_wad, _redeemLocal.exchangeRate); _redeemLocal.defaultHandler = IDispatcher(dispatcher).defaultHandler(); require( _redeemLocal.defaultHandler != address(0) && IDispatcher(dispatcher).isHandlerActive( _redeemLocal.defaultHandler ), "redeem: default handler is inactive" ); // Get `_token` best withdraw strategy base on the withdraw amount `_pie`. (_redeemLocal.handlers, _redeemLocal.amounts) = IDispatcher(dispatcher) .getWithdrawStrategy(_redeemLocal.token, _redeemLocal.grossAmount); require( _redeemLocal.handlers.length > 0, "redeem: no withdraw strategy available, possibly due to a paused handler" ); _redeemLocal.redeemTotalAmount = withdrawFromHandlers( _redeemLocal.defaultHandler, _redeemLocal.handlers, _redeemLocal.amounts ); // Market may charge some fee in withdraw, so the actual withdrown total amount // could be less than what was intended // Use the redeemTotalAmount as the baseline for further calculation require( _redeemLocal.redeemTotalAmount <= _redeemLocal.grossAmount, "redeem: redeemed more than intended" ); updateInterest(_src, _redeemLocal.exchangeRate); // Update the balance and totalSupply _balance.value = _balance.value.sub(_wad); totalSupply = totalSupply.sub(_wad); // Calculate fee _redeemLocal.originationFee = originationFee[msg.sig]; _redeemLocal.fee = rmul( _redeemLocal.redeemTotalAmount, _redeemLocal.originationFee ); // Transfer fee from the default handler(the temporary pool) to dToken. if (_redeemLocal.fee > 0) require( doTransferFrom( _redeemLocal.token, _redeemLocal.defaultHandler, feeRecipient, _redeemLocal.fee ), "redeem: transfer fee from default handler failed" ); // Subtracting the fee _redeemLocal.userAmount = _redeemLocal.redeemTotalAmount.sub( _redeemLocal.fee ); // Transfer the remaining amount from the default handler to msg.sender. if (_redeemLocal.userAmount > 0) require( doTransferFrom( _redeemLocal.token, _redeemLocal.defaultHandler, msg.sender, _redeemLocal.userAmount ), "redeem: transfer from default handler to user failed" ); emit Transfer(_src, address(0), _wad); emit Redeem( _src, _redeemLocal.redeemTotalAmount, _wad, totalSupply, _redeemLocal.exchangeRate ); } struct RedeemUnderlyingLocalVars { address token; address defaultHandler; address[] handlers; uint256[] amounts; uint256 exchangeRate; uint256 originationFee; uint256 fee; uint256 consumeAmountWithFee; uint256 redeemTotalAmount; uint256 wad; } /** * @dev Redeem specific amount of underlying token, but only when the contract is not paused. * @param _src Account who will spend dToken. * @param _pie Amount to redeem, scaled by 1e18. */ function redeemUnderlying(address _src, uint256 _pie) external nonReentrant whenNotPaused { RedeemUnderlyingLocalVars memory _redeemLocal; _redeemLocal.token = token; // Here use the signature of redeem(), both functions should use the same fee rate _redeemLocal.originationFee = originationFee[DToken(this) .redeem .selector]; _redeemLocal.consumeAmountWithFee = rdivup( _pie, BASE.sub(_redeemLocal.originationFee) ); _redeemLocal.defaultHandler = IDispatcher(dispatcher).defaultHandler(); require( _redeemLocal.defaultHandler != address(0) && IDispatcher(dispatcher).isHandlerActive( _redeemLocal.defaultHandler ), "redeemUnderlying: default handler is inactive" ); // Get `_token` best withdraw strategy base on the redeem amount including fee. (_redeemLocal.handlers, _redeemLocal.amounts) = IDispatcher(dispatcher) .getWithdrawStrategy( _redeemLocal.token, _redeemLocal.consumeAmountWithFee ); require( _redeemLocal.handlers.length > 0, "redeemUnderlying: no withdraw strategy available, possibly due to a paused handler" ); // !!!DO NOT move up, we need the handlers to current exchange rate. _redeemLocal.exchangeRate = getCurrentExchangeRateByHandler( _redeemLocal.handlers, _redeemLocal.token ); _redeemLocal.redeemTotalAmount = withdrawFromHandlers( _redeemLocal.defaultHandler, _redeemLocal.handlers, _redeemLocal.amounts ); // Make sure enough token has been withdrown // If the market charge fee in withdraw, there are 2 cases: // 1) redeemed < intended, unlike redeem(), it should fail as user has demanded the specific amount; // 2) redeemed == intended, it is okay, as fee was covered by consuming more underlying token require( _redeemLocal.redeemTotalAmount == _redeemLocal.consumeAmountWithFee, "redeemUnderlying: withdrown more than intended" ); // Calculate amount of the dToken based on current exchange rate. _redeemLocal.wad = rdivup( _redeemLocal.redeemTotalAmount, _redeemLocal.exchangeRate ); updateInterest(_src, _redeemLocal.exchangeRate); // Check the balance and allowance Balance storage _balance = balances[_src]; require( _balance.value >= _redeemLocal.wad, "redeemUnderlying: insufficient balance" ); if (_src != msg.sender && allowance[_src][msg.sender] != uint256(-1)) { require( allowance[_src][msg.sender] >= _redeemLocal.wad, "redeemUnderlying: insufficient allowance" ); allowance[_src][msg.sender] = allowance[_src][msg.sender].sub( _redeemLocal.wad ); } // Update the balance and totalSupply _balance.value = _balance.value.sub(_redeemLocal.wad); totalSupply = totalSupply.sub(_redeemLocal.wad); // The calculated amount contains exchange token fee, if it exists. _redeemLocal.fee = _redeemLocal.redeemTotalAmount.sub(_pie); // Transfer fee from the default handler(the temporary pool) to dToken. if (_redeemLocal.fee > 0) require( doTransferFrom( _redeemLocal.token, _redeemLocal.defaultHandler, feeRecipient, _redeemLocal.fee ), "redeemUnderlying: transfer fee from default handler failed" ); // Transfer original amount _pie from the default handler to msg.sender. require( doTransferFrom( _redeemLocal.token, _redeemLocal.defaultHandler, msg.sender, _pie ), "redeemUnderlying: transfer to user failed" ); emit Transfer(_src, address(0), _redeemLocal.wad); emit Redeem( _src, _redeemLocal.redeemTotalAmount, _redeemLocal.wad, totalSupply, _redeemLocal.exchangeRate ); } // --- ERC20 Standard Interfaces --- function transfer(address _dst, uint256 _wad) external returns (bool) { return transferFrom(msg.sender, _dst, _wad); } function transferFrom( address _src, address _dst, uint256 _wad ) public nonReentrant whenNotPaused returns (bool) { Balance storage _srcBalance = balances[_src]; // Check balance and allowance require( _srcBalance.value >= _wad, "transferFrom: insufficient balance" ); if (_src != msg.sender && allowance[_src][msg.sender] != uint256(-1)) { require( allowance[_src][msg.sender] >= _wad, "transferFrom: insufficient allowance" ); allowance[_src][msg.sender] = allowance[_src][msg.sender].sub(_wad); } // Update the accured interest for both uint256 _exchangeRate = getCurrentExchangeRate(); updateInterest(_src, _exchangeRate); updateInterest(_dst, _exchangeRate); // Finally update the balance Balance storage _dstBalance = balances[_dst]; _srcBalance.value = _srcBalance.value.sub(_wad); _dstBalance.value = _dstBalance.value.add(_wad); emit Transfer(_src, _dst, _wad); return true; } function approve(address _spender, uint256 _wad) public whenNotPaused returns (bool) { allowance[msg.sender][_spender] = _wad; emit Approval(msg.sender, _spender, _wad); return true; } function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { return approve(spender, allowance[msg.sender][spender].add(addedValue)); } function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { return approve( spender, allowance[msg.sender][spender].sub(subtractedValue) ); } function balanceOf(address account) external view returns (uint256) { return balances[account].value; } /** * @dev According to the current exchange rate, get user's corresponding token balance * based on the dToken amount, which has substracted dToken fee. * @param _account Account to query token balance. * @return Actual token balance based on dToken amount. */ function getTokenBalance(address _account) external view returns (uint256) { return rmul(balances[_account].value, getExchangeRate()); } /** * @dev According to the current exchange rate, get user's accrued interest until now, it is an estimation, since it use the exchange rate in view instead of the realtime one. * @param _account Account to query token balance. * @return Estimation of accrued interest till now. */ function getCurrentInterest(address _account) external view returns (uint256) { return balances[_account].interest.add( rmul( getExchangeRate().sub(balances[_account].exchangeRate), balances[_account].value ) ); } /** * @dev Get the current list of the handlers. */ function getHandlers() public view returns (address[] memory) { (address[] memory _handlers, ) = IDispatcher(dispatcher).getHandlers(); return _handlers; } /** * @dev Get all deposit token amount including interest. */ function getTotalBalance() external view returns (uint256) { address[] memory _handlers = getHandlers(); uint256 _tokenTotalBalance = 0; for (uint256 i = 0; i < _handlers.length; i++) _tokenTotalBalance = _tokenTotalBalance.add( IHandler(_handlers[i]).getBalance(token) ); return _tokenTotalBalance; } /** * @dev Get maximum valid token amount in the whole market. */ function getLiquidity() external view returns (uint256) { address[] memory _handlers = getHandlers(); uint256 _liquidity = 0; for (uint256 i = 0; i < _handlers.length; i++) _liquidity = _liquidity.add( IHandler(_handlers[i]).getLiquidity(token) ); return _liquidity; } /** * @dev Current exchange rate, scaled by 1e18. */ function getExchangeRate() public view returns (uint256) { address[] memory _handlers = getHandlers(); address _token = token; uint256 _totalToken = 0; for (uint256 i = 0; i < _handlers.length; i++) _totalToken = _totalToken.add( IHandler(_handlers[i]).getBalance(_token) ); return totalSupply == 0 ? BASE : rdiv(_totalToken, totalSupply); } function currentExchangeRate() external returns (uint256) { return getCurrentExchangeRate(); } function totalUnderlying() external returns (uint256) { address[] memory _handlers = getHandlers(); uint256 _tokenTotalBalance = 0; for (uint256 i = 0; i < _handlers.length; i++) _tokenTotalBalance = _tokenTotalBalance.add( IHandler(_handlers[i]).getRealBalance(token) ); return _tokenTotalBalance; } function getRealLiquidity() external returns (uint256) { address[] memory _handlers = getHandlers(); uint256 _liquidity = 0; for (uint256 i = 0; i < _handlers.length; i++) _liquidity = _liquidity.add( IHandler(_handlers[i]).getRealLiquidity(token) ); return _liquidity; } function balanceOfUnderlying(address _account) external returns (uint256) { uint256 _underlying = rmul( balances[_account].value, getCurrentExchangeRate() ); return _underlying.sub( rmul(_underlying, originationFee[this.redeem.selector]) ); } function getBaseData() external returns ( uint256, uint256, uint256, uint256, uint256 ) { address[] memory _handlers = getHandlers(); uint256 _tokenTotalBalance = 0; for (uint256 i = 0; i < _handlers.length; i++) _tokenTotalBalance = _tokenTotalBalance.add( IHandler(_handlers[i]).getRealBalance(token) ); return ( decimals, getCurrentExchangeRate(), originationFee[DToken(this).mint.selector], originationFee[DToken(this).redeem.selector], _tokenTotalBalance ); } function getHandlerInfo() external returns ( address[] memory, uint256[] memory, uint256[] memory ) { address[] memory _handlers = getHandlers(); uint256[] memory _balances = new uint256[](_handlers.length); uint256[] memory _liquidities = new uint256[](_handlers.length); for (uint256 i = 0; i < _handlers.length; i++) { _balances[i] = IHandler(_handlers[i]).getRealBalance(token); _liquidities[i] = IHandler(_handlers[i]).getRealLiquidity(token); } return (_handlers, _balances, _liquidities); } }
Authorized function to swap airdrop tokens to increase yield. _token Airdrop token to swap from. _amount Amount to swap./
function swap(address _token, uint256 _amount) external auth { require(swapModel != address(0), "swap: no swap model available!"); (bool success, ) = swapModel.delegatecall( abi.encodeWithSignature("swap(address,uint256)", _token, _amount) ); require(success, "swap: swap to another token failed!"); }
12,948,836
pragma solidity ^0.4.19; // solhint-disable-line /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Srini Vasan contract ERC721 { // Required methods function approve(address _to, uint256 _tokenId) public; function balanceOf(address _owner) public view returns (uint256 balance); function implementsERC721() public pure returns (bool); function ownerOf(uint256 _tokenId) public view returns (address addr); function takeOwnership(uint256 _tokenId) public; function totalSupply() public view returns (uint256 total); function transferFrom(address _from, address _to, uint256 _tokenId) public; function transfer(address _to, uint256 _tokenId) public; event Transfer(address indexed from, address indexed to, uint256 tokenId); event Approval(address indexed owner, address indexed approved, uint256 tokenId); } contract CryptonToken is ERC721 { /*** EVENTS ***/ /// @dev The Birth event is fired whenever a new crypton comes into existence. event Birth(uint256 tokenId, string name, address owner, bool isProtected, uint8 category); /// @dev The TokenSold event is fired whenever a token is sold. event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name); /// @dev Transfer event as defined in current draft of ERC721. /// ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); /// @dev the PaymentTransferredToPreviousOwner event is fired when the previous owner of the Crypton is paid after a purchase. event PaymentTransferredToPreviousOwner(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name); // @dev CryptonIsProtected is fired when the Crypton is protected from snatching - i.e. owner is allowed to set the selling price for the crypton event CryptonIsProtected(uint256 tokenId); // @dev The markup was changed event MarkupChanged(string name, uint256 newMarkup); //@dev Selling price of protected Crypton changed event ProtectedCryptonSellingPriceChanged(uint256 tokenId, uint256 newSellingPrice); // Owner protected their Crypton event OwnerProtectedCrypton(uint256 _tokenId, uint256 newSellingPrice); //Contract paused event event ContractIsPaused(bool paused); /*** CONSTANTS ***/ /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant NAME = "Cryptons"; // solhint-disable-line string public constant SYMBOL = "CRYPTON"; // solhint-disable-line uint256 private startingPrice = 0.1 ether; uint256 private defaultMarkup = 2 ether; uint256 private FIRST_STEP_LIMIT = 1.0 ether; uint16 private FIRST_STEP_MULTIPLIER = 200; // double the value uint16 private SECOND_STEP_MULTIPLIER = 120; // increment value by 20% uint16 private XPROMO_MULTIPLIER = 500; // 5 times the value uint16 private CRYPTON_CUT = 6; // our cut uint16 private NET_PRICE_PERCENT = 100 - CRYPTON_CUT; // Net price paid out after cut // I could have used enums - but preferered the more specific uint8 uint8 private constant PROMO = 1; uint8 private constant STANDARD = 2; uint8 private constant RESERVED = 7; uint8 private constant XPROMO = 10; // First transaction, contract sets sell price to 5x /*** STORAGE ***/ /// @dev A mapping from crypton IDs to the address that owns them. All cryptons have /// some valid owner address. mapping (uint256 => address) public cryptonIndexToOwner; mapping (uint256 => bool) public cryptonIndexToProtected; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) private ownershipTokenCount; /// @dev A mapping from CryptonIDs to an address that has been approved to call /// transferFrom(). Each Crypton can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public cryptonIndexToApproved; // @dev A mapping from CryptonIDs to the price of the token. mapping (uint256 => uint256) private cryptonIndexToPrice; // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cooAddress; /*** DATATYPES ***/ struct Crypton { string name; uint8 category; uint256 markup; } Crypton[] private cryptons; /// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked. bool public paused = false; /*** ACCESS MODIFIERS ***/ /// @dev Access modifier for COO-only functionality /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } modifier onlyCOO() { require(msg.sender == cooAddress); _; } /// Access modifier for contract owner only functionality modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == cooAddress ); _; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; emit ContractIsPaused(paused); } /// @dev Unpauses the smart contract. Can only be called by the CEO /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyCEO whenPaused { // can't unpause if contract was forked paused = false; emit ContractIsPaused(paused); } /*** CONSTRUCTOR ***/ constructor() public { ceoAddress = msg.sender; cooAddress = msg.sender; } /*** PUBLIC FUNCTIONS ***/ /// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom(). /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) public whenNotPaused { // Caller must own token. require(_owns(msg.sender, _tokenId)); cryptonIndexToApproved[_tokenId] = _to; emit Approval(msg.sender, _to, _tokenId); } /// For querying balance of a particular account /// @param _owner The address for balance query /// @dev Required for ERC-721 compliance. function balanceOf(address _owner) public view returns (uint256 balance) { return ownershipTokenCount[_owner]; } /// @dev Creates a new Crypton with the given name, startingPrice, category and an (optional) owner wallet address function createCrypton( string _name, //Required uint8 _category, //Required uint256 _startingPrice, // Optional - defaults to startingPrice uint256 _markup, // Optional - defaults to defaultMarkup address _owner // Optional - deafults to contract ) public onlyCLevel { address cryptonOwner = _owner; if (cryptonOwner == address(0)) { cryptonOwner = address(this); } if (_category == XPROMO) { // XPROMO Cryptons - force ownership to contract cryptonOwner = address(this); } if (_markup <= 0) { _markup = defaultMarkup; } if (_category == PROMO) { // PROMO Cryptons - force markup to zero _markup = 0; } if (_startingPrice <= 0) { _startingPrice = startingPrice; } bool isProtected = (_category == PROMO)?true:false; // PROMO cryptons are protected, others are not - at creation _createCrypton(_name, cryptonOwner, _startingPrice, _markup, isProtected, _category); } /// @notice Returns all the relevant information about a specific crypton. /// @param _tokenId The tokenId of the crypton of interest. function getCrypton(uint256 _tokenId) public view returns ( string cryptonName, uint8 category, uint256 markup, uint256 sellingPrice, address owner, bool isProtected ) { Crypton storage crypton = cryptons[_tokenId]; cryptonName = crypton.name; sellingPrice = cryptonIndexToPrice[_tokenId]; owner = cryptonIndexToOwner[_tokenId]; isProtected = cryptonIndexToProtected[_tokenId]; category = crypton.category; markup = crypton.markup; } function implementsERC721() public pure returns (bool) { return true; } /// @dev Required for ERC-721 compliance. function name() public pure returns (string) { return NAME; } /// For querying owner of token /// @param _tokenId The tokenID for owner inquiry /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = cryptonIndexToOwner[_tokenId]; require(owner != address(0)); } /// @dev This function withdraws the contract owner's cut. /// Any amount may be withdrawn as there is no user funds. /// User funds are immediately sent to the old owner in `purchase` function payout(address _to) public onlyCLevel { _payout(_to); } /// @dev This function allows the contract owner to adjust the selling price of a protected Crypton function setPriceForProtectedCrypton(uint256 _tokenId, uint256 newSellingPrice) public whenNotPaused { address oldOwner = cryptonIndexToOwner[_tokenId]; // owner in blockchain address newOwner = msg.sender; // person requesting change require(oldOwner == newOwner); // Only current owner can update the price require(cryptonIndexToProtected[_tokenId]); // Make sure Crypton is protected require(newSellingPrice > 0); // Make sure the price is not zero cryptonIndexToPrice[_tokenId] = newSellingPrice; emit ProtectedCryptonSellingPriceChanged(_tokenId, newSellingPrice); } /// @dev This function allows the contract owner to buy protection for an unprotected that they already own function setProtectionForMyUnprotectedCrypton(uint256 _tokenId, uint256 newSellingPrice) public payable whenNotPaused { address oldOwner = cryptonIndexToOwner[_tokenId]; // owner in blockchain address newOwner = msg.sender; // person requesting change uint256 markup = cryptons[_tokenId].markup; if (cryptons[_tokenId].category != PROMO) { require(markup > 0); // if this is NOT a promotional crypton, the markup should be > zero } require(oldOwner == newOwner); // Only current owner can buy protection for existing crypton require(! cryptonIndexToProtected[_tokenId]); // Make sure Crypton is NOT already protected require(newSellingPrice > 0); // Make sure the sellingPrice is more than zero require(msg.value >= markup); // Make sure to collect the markup cryptonIndexToPrice[_tokenId] = newSellingPrice; cryptonIndexToProtected[_tokenId] = true; emit OwnerProtectedCrypton(_tokenId, newSellingPrice); } function getMarkup(uint256 _tokenId) public view returns (uint256 markup) { return cryptons[_tokenId].markup; } /// @dev This function allows the contract owner to adjust the markup value function setMarkup(uint256 _tokenId, uint256 newMarkup) public onlyCLevel { require(newMarkup >= 0); cryptons[_tokenId].markup = newMarkup; emit MarkupChanged(cryptons[_tokenId].name, newMarkup); } // Allows someone to send ether and obtain the token function purchase(uint256 _tokenId, uint256 newSellingPrice) public payable whenNotPaused { address oldOwner = cryptonIndexToOwner[_tokenId]; address newOwner = msg.sender; bool isAlreadyProtected = cryptonIndexToProtected[_tokenId]; uint256 sellingPrice = cryptonIndexToPrice[_tokenId]; uint256 markup = cryptons[_tokenId].markup; if (cryptons[_tokenId].category != PROMO) { require(markup > 0); // if this is NOT a promotional crypton, the markup should be > zero } // Make sure token owner is not sending to self require(oldOwner != newOwner); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Make sure sent amount is greater than or equal to the sellingPrice require(msg.value >= sellingPrice); // this is redundant - as we are checking this below if (newSellingPrice > 0) { // if we are called with a new selling price, then the buyer is paying the markup or purchasing a protected crypton uint256 purchasePrice = sellingPrice; //assume it is protected if (! cryptonIndexToProtected[_tokenId] ) { // Crypton is not protected, purchasePrice = sellingPrice + markup; // apply markup } // If the Crypton is not already protected, make sure that the buyer is paying markup more than the current selling price // If the buyer is not paying the markup - then he cannot set the new selling price- bailout require(msg.value >= purchasePrice); // Ok - the buyer paid the markup or the crypton was already protected. cryptonIndexToPrice[_tokenId] = newSellingPrice; // Set the selling price that the buyer wants cryptonIndexToProtected[_tokenId] = true; // Set the Crypton to protected emit CryptonIsProtected(_tokenId); // Let the world know } else { // Compute next listing price. // Handle XPROMO case first... if ( (oldOwner == address(this)) && // first transaction only` (cryptons[_tokenId].category == XPROMO) // Only for XPROMO category ) { cryptonIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, XPROMO_MULTIPLIER), NET_PRICE_PERCENT); } else { if (sellingPrice < FIRST_STEP_LIMIT) { // first stage cryptonIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, FIRST_STEP_MULTIPLIER), NET_PRICE_PERCENT); } else { // second stage cryptonIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, SECOND_STEP_MULTIPLIER), NET_PRICE_PERCENT); } } } _transfer(oldOwner, newOwner, _tokenId); uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, NET_PRICE_PERCENT), 100)); string storage cname = cryptons[_tokenId].name; bool isReservedToken = (cryptons[_tokenId].category == RESERVED); if (isReservedToken && isAlreadyProtected) { oldOwner.transfer(payment); //(1-CRYPTON_CUT/100) emit PaymentTransferredToPreviousOwner(_tokenId, sellingPrice, cryptonIndexToPrice[_tokenId], oldOwner, newOwner, cname); emit TokenSold(_tokenId, sellingPrice, cryptonIndexToPrice[_tokenId], oldOwner, newOwner, cname); return; } // Pay seller of the Crypton if they are not this contract or if this is a Reserved token if ((oldOwner != address(this)) && !isReservedToken ) // Not a Reserved token and not owned by the contract { oldOwner.transfer(payment); //(1-CRYPTON_CUT/100) emit PaymentTransferredToPreviousOwner(_tokenId, sellingPrice, cryptonIndexToPrice[_tokenId], oldOwner, newOwner, cname); } emit TokenSold(_tokenId, sellingPrice, cryptonIndexToPrice[_tokenId], oldOwner, newOwner, cname); } function priceOf(uint256 _tokenId) public view returns (uint256 price) { return cryptonIndexToPrice[_tokenId]; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the COO. Only available to the current COO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /// @dev Required for ERC-721 compliance. function symbol() public pure returns (string) { return SYMBOL; } /// @notice Allow pre-approved user to take ownership of a token /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function takeOwnership(uint256 _tokenId) public whenNotPaused { address newOwner = msg.sender; address oldOwner = cryptonIndexToOwner[_tokenId]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure transfer is approved require(_approved(newOwner, _tokenId)); _transfer(oldOwner, newOwner, _tokenId); } /// @param _owner The owner whose Cryptons we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire Cryptons array looking for cryptons belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalCryptons = totalSupply(); uint256 resultIndex = 0; uint256 cryptonId; for (cryptonId = 0; cryptonId <= totalCryptons; cryptonId++) { if (cryptonIndexToOwner[cryptonId] == _owner) { result[resultIndex] = cryptonId; resultIndex++; } } return result; } } /// For querying totalSupply of token /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256 total) { return cryptons.length; } /// Owner initates the transfer of the token to another account /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) public whenNotPaused { require(_owns(msg.sender, _tokenId)); require(_addressNotNull(_to)); _transfer(msg.sender, _to, _tokenId); } /// Third-party initiates transfer of token from address _from to address _to /// @param _from The address for the token to be transferred from. /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) public whenNotPaused { require(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } /*** PRIVATE FUNCTIONS ***/ /// Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } /// For checking approval of transfer for address _to function _approved(address _to, uint256 _tokenId) private view returns (bool) { return cryptonIndexToApproved[_tokenId] == _to; } /// For creating Crypton function _createCrypton(string _name, address _owner, uint256 _price, uint256 _markup, bool _isProtected, uint8 _category) private { Crypton memory _crypton = Crypton({ name: _name, category: _category, markup: _markup }); uint256 newCryptonId = cryptons.push(_crypton) - 1; // It's probably never going to happen, 4 billion tokens are A LOT, but // let's just be 100% sure we never let this happen. require(newCryptonId == uint256(uint32(newCryptonId))); emit Birth(newCryptonId, _name, _owner, _isProtected, _category); cryptonIndexToPrice[newCryptonId] = _price; cryptonIndexToProtected[newCryptonId] = _isProtected; // _isProtected is true for promo cryptons - false for others. // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(address(0), _owner, newCryptonId); } /// Check for token ownership function _owns(address claimant, uint256 _tokenId) private view returns (bool) { return claimant == cryptonIndexToOwner[_tokenId]; } /// For paying out balance on contract function _payout(address _to) private { address myAddress = this; if (_to == address(0)) { ceoAddress.transfer(myAddress.balance); } else { _to.transfer(myAddress.balance); } } /// @dev Assigns ownership of a specific Crypton to an address. function _transfer(address _from, address _to, uint256 _tokenId) private { // Since the number of cryptons is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; //transfer ownership cryptonIndexToOwner[_tokenId] = _to; // When creating new cryptons _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete cryptonIndexToApproved[_tokenId]; } // Emit the transfer event. emit Transfer(_from, _to, _tokenId); } //various getter/setter methods function setFIRST_STEP_LIMIT(uint256 newLimit) public onlyCLevel { require(newLimit > 0 && newLimit < 100 ether); FIRST_STEP_LIMIT = newLimit; } function getFIRST_STEP_LIMIT() public view returns (uint256 value) { return FIRST_STEP_LIMIT; } function setFIRST_STEP_MULTIPLIER(uint16 newValue) public onlyCLevel { require(newValue >= 110 && newValue <= 200); FIRST_STEP_MULTIPLIER = newValue; } function getFIRST_STEP_MULTIPLIER() public view returns (uint16 value) { return FIRST_STEP_MULTIPLIER; } function setSECOND_STEP_MULTIPLIER(uint16 newValue) public onlyCLevel { require(newValue >= 110 && newValue <= 200); SECOND_STEP_MULTIPLIER = newValue; } function getSECOND_STEP_MULTIPLIER() public view returns (uint16 value) { return SECOND_STEP_MULTIPLIER; } function setXPROMO_MULTIPLIER(uint16 newValue) public onlyCLevel { require(newValue >= 100 && newValue <= 10000); // between 0 and 100x XPROMO_MULTIPLIER = newValue; } function getXPROMO_MULTIPLIER() public view returns (uint16 value) { return XPROMO_MULTIPLIER; } function setCRYPTON_CUT(uint16 newValue) public onlyCLevel { require(newValue > 0 && newValue < 10); CRYPTON_CUT = newValue; } function getCRYPTON_CUT() public view returns (uint16 value) { return CRYPTON_CUT; } } 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; } }
For checking approval of transfer for address _to
function _approved(address _to, uint256 _tokenId) private view returns (bool) { return cryptonIndexToApproved[_tokenId] == _to; }
11,953,286
pragma solidity ^0.5.11; import "./ERC721.sol"; import "./Growdrop.sol"; /** * @dev Implementation of ERC721 token which is used as donation deed, * and includes storing IPFS hash to identify Growdrop's donation. */ contract DonateToken is ERC721 { /** * @notice Check whether address is admin. */ mapping(address => bool) public CheckOwner; /** * @notice Current deployed Growdrop. */ Growdrop growdrop; /** * @notice Container for IPFS hash. * @member hash digest of IPFS hash format * @member hash_function hash function code of IPFS hash format * @member size digest size of IPFS hash format */ struct Multihash { bytes32 hash; uint8 hash_function; uint8 size; } /** * @notice Container for ERC721 token's donation information. * @member supporter address of Growdrop investor * @member beneficiary address of Growdrop investee or beneficiary * @member tokenAddress address of Growdrop's funding token * @member tokenAmount accrued interest amount of Growdrop investor * @member donateId Growdrop's donation identifier */ struct DonateInfo { address supporter; address beneficiary; address tokenAddress; uint256 tokenAmount; uint256 donateId; } /** * @notice Accrued interest amount from supporter to beneficiary with token address and Growdrop's donation identifier. */ mapping( address => mapping( address => mapping( address => mapping( uint256 => uint256)))) public DonateInfoToTokenAmount; /** * @notice Donation information of ERC721 token identifier. */ mapping(uint256 => DonateInfo) private TokenIdToDonateInfo; /** * @notice IPFS hash of Growdrop's donation identifier. */ mapping(uint256 => Multihash) private DonateIdToMultihash; /** * @notice Owner of Growdrop's donation identifier. */ mapping(uint256 => address) public DonateIdOwner; /** * @notice Growdrop's donation identifier of IPFS hash. */ mapping( bytes32 => mapping( uint8 => mapping ( uint8 => uint256))) public MultihashToDonateId; /** * @notice Event emitted when IPFS hash is stored. */ event DonateEvent( uint256 indexed event_idx, address indexed from_address, uint256 indexed donate_id, bytes32 hash, uint8 hash_function, uint8 size ); /** * @dev Constructor, storing deployer as admin, * and storing deployed Growdrop address. * @param _Growdrop Growdrop's deployed address */ constructor (address payable _Growdrop) public { CheckOwner[msg.sender] = true; growdrop = Growdrop(_Growdrop); } /** * @dev Adds new admin address * @param _Owner new admin address */ function addOwner(address _Owner) public { require(CheckOwner[msg.sender], "not owner"); CheckOwner[_Owner] = !CheckOwner[_Owner]; } /** * @dev Set new Growdrop's deployed address. * @param _Growdrop new Growdrop's deployed address */ function setGrowdrop(address payable _Growdrop) public { require(CheckOwner[msg.sender], "not owner"); growdrop = Growdrop(_Growdrop); } /** * @dev Stores new IPFS hash as a donation identifier * and owner as caller. * * Emits {Growdrop-DonateAction} event indicating owner and donation identifier as 'donateId'. * * @param _hash digest of IPFS hash format * @param hash_function hash function code of IPFS hash format * @param size digest size of IPFS hash format */ function setMultihash(bytes32 _hash, uint8 hash_function, uint8 size) public { uint256 donateId = uint256(keccak256(abi.encode(_hash, hash_function, size))); MultihashToDonateId[_hash][hash_function][size] = donateId; DonateIdToMultihash[donateId] = Multihash(_hash,hash_function,size); DonateIdOwner[donateId] = msg.sender; uint256 eventIdx = growdrop.emitDonateActionEvent( msg.sender, address(0x0), address(0x0), address(0x0), address(0x0), donateId, 0, 0, 2 ); emit DonateEvent(eventIdx, msg.sender, donateId, _hash, hash_function, size); } /** * @dev Mint a ERC721 token to 'supporter'. * * Emits {Growdrop-DonateAction} event indicating new ERC721 token information. * * @param supporter address of Growdrop's investor * @param beneficiary address of Growdrop's investee or 'beneficiary' * @param token address of Growdrop's funding token * @param amount accrued interest amount of investor * @param donateId Growdrop's donation identifier * @return tokenId new ERC721 token's identifier */ function mint(address supporter, address beneficiary, address token, uint256 amount, uint256 donateId) public returns (uint256) { require(msg.sender==address(growdrop), "not growdrop contract"); if(amount==0) return 0; uint256 tokenId = uint256(keccak256(abi.encode(supporter, beneficiary, token, amount, donateId))); TokenIdToDonateInfo[tokenId] = DonateInfo(supporter,beneficiary,token,amount,donateId); _mint(supporter, tokenId); DonateInfoToTokenAmount[supporter][beneficiary][token][donateId] = DonateInfoToTokenAmount[supporter][beneficiary][token][donateId].add(amount); growdrop.emitDonateActionEvent(address(0x0), supporter, supporter, beneficiary, token, donateId, tokenId, amount, 0); return tokenId; } /** * @dev Transfer 'tokenId' ERC721 token from '_from' to 'to'. * After transferring token, 'DonateInfoToTokenAmount' changes. * This does not change 'DonateInfo' of ERC721 token. * * Emits {Growdrop-DonateAction} event indicating transfer of ERC721 token. * * @param _from address of token owner * @param to address of token receiver * @param tokenId identifier of token */ function transferFrom(address _from, address to, uint256 tokenId) public { super.transferFrom(_from,to,tokenId); setInfoToTokenId(_from,to,tokenId); } /** * @dev Safe Transfer 'tokenId' ERC721 token from '_from' to 'to'. * After transferring token, 'DonateInfoToTokenAmount' changes. * This does not change 'DonateInfo' of ERC721 token. * * Emits {Growdrop-DonateAction} event indicating transfer of ERC721 token. * * @param _from address of token owner * @param to address of token receiver * @param tokenId identifier of token */ function safeTransferFrom(address _from, address to, uint256 tokenId, bytes memory _data) public { super.safeTransferFrom(_from,to,tokenId,_data); setInfoToTokenId(_from,to,tokenId); } /** * @dev Changes donation amount recalculated with '_from' and 'to'. * * Emits {Growdrop-DonateAction} event. * * @param _from address of token owner * @param to address of token receiver * @param tokenId identifier of token */ function setInfoToTokenId(address _from, address to, uint256 tokenId) private { DonateInfo memory donateInfo = TokenIdToDonateInfo[tokenId]; DonateInfoToTokenAmount[_from][donateInfo.beneficiary][donateInfo.tokenAddress][donateInfo.donateId] = DonateInfoToTokenAmount[_from][donateInfo.beneficiary][donateInfo.tokenAddress][donateInfo.donateId].sub(donateInfo.tokenAmount); DonateInfoToTokenAmount[to][donateInfo.beneficiary][donateInfo.tokenAddress][donateInfo.donateId] = DonateInfoToTokenAmount[to][donateInfo.beneficiary][donateInfo.tokenAddress][donateInfo.donateId].add(donateInfo.tokenAmount); growdrop.emitDonateActionEvent(_from, to, donateInfo.supporter, donateInfo.beneficiary, donateInfo.tokenAddress, donateInfo.donateId, tokenId, donateInfo.tokenAmount, 1); } /** * @dev Get donation information of ERC721 token identifier. * @param tokenId identifier of token * @return donateInfo.supporter stored investor address of 'tokenId' * @return donateInfo.beneficiary stored investee or beneficiary address of 'tokenId' * @return donateInfo.tokenAddress stored funding token's address of 'tokenId' * @return donateInfo.tokenAmount stored accrued interest amount of 'tokenId' * @return donateInfo.donateId Growdrop's donation identifier of 'tokenId' */ function getDonateInfo(uint256 tokenId) public view returns (address, address, address, uint256, uint256) { DonateInfo memory donateInfo = TokenIdToDonateInfo[tokenId]; return (donateInfo.supporter, donateInfo.beneficiary, donateInfo.tokenAddress, donateInfo.tokenAmount, donateInfo.donateId); } /** * @dev Get stored IPFS hash of Growdrop's donation identifier. * @param donateId Growdrop's donation identifier * @return multihash.hash stored digest of IPFS hash format * @return multihash.hash_function stored hash function code of IPFS hash format * @return multihash.size stored digest size of IPFS hash format */ function getMultihash(uint256 donateId) public view returns (bytes32, uint8, uint8) { Multihash memory multihash = DonateIdToMultihash[donateId]; return (multihash.hash, multihash.hash_function, multihash.size); } }
Safe Transfer 'tokenId' ERC721 token from '_from' to 'to'. After transferring token, 'DonateInfoToTokenAmount' changes. This does not change 'DonateInfo' of ERC721 token. Emits {Growdrop-DonateAction} event indicating transfer of ERC721 token. _from address of token owner to address of token receiver tokenId identifier of token/
function safeTransferFrom(address _from, address to, uint256 tokenId, bytes memory _data) public { super.safeTransferFrom(_from,to,tokenId,_data); setInfoToTokenId(_from,to,tokenId); }
5,461,821
./full_match/80001/0xA8D6F9B6DE7311976905D8986Fcb2dCb6dA8a3D0/sources/contracts/caicaNFT.sol
NFT購入 販売利益利益を出品者に振込(※小数点以下切り捨て)
function buyNFT(uint256 _tokenId) external payable { uint256 price = tokenIdToPrice[_tokenId]; bool isAllowedBuy = tokenIdToAllowedBuy[_tokenId]; require(isAllowedBuy == true, "Contract error: Not for sale"); require(msg.value == price, "Contract error: Incorrect value"); address seller = ownerOf(_tokenId); _transfer(seller, msg.sender, _tokenId); tokenIdToAllowedBuy[_tokenId] = false; uint256 paymentAmount = price * tokenPaymentPercent[_tokenId] / 100; payable(seller).transfer(paymentAmount); emit SuccessBuyNFT(msg.sender, seller, paymentAmount); }
5,567,949
./partial_match/1/0x5fE4e37c9FC121A602bAcCeaA9CEDeDb6153d3E6/sources/contracts/soma/SecurityTokens/ISecurityToken.sol
SOMA Security Token Contract. SOMA.finance A guarded, mintable and seizable security token./
interface ISecurityToken { function initialize(string memory domain, string memory name, string memory symbol) external; }
9,426,645
./partial_match/42/0x34eB80898149f2B77a4990822836803105F2FfC1/sources/contracts/DecentralizedAutonomousTrust.sol
Called once after deploy to set the initial configuration. None of the values provided here may change once initially set. using the init pattern in order to support zos upgrades Set initGoal, which in turn defines the initial state Math: If this value got too large, the DAT would overflow on sell
function initialize( uint _initReserve, address _currencyAddress, uint _initGoal, uint _bcGoal, uint _buySlopeNum, uint _buySlopeDen, uint _investmentReserveBasisPoints ) public { require(control == address(0), "ALREADY_INITIALIZED"); if(_initGoal == 0) { emit StateChange(state, STATE_RUN); state = STATE_RUN; } else { require(_initGoal < MAX_SUPPLY, "EXCESSIVE_GOAL"); initGoal = _initGoal; } require(_bcGoal > 0, "INVALID_BC_GOAL"); bcGoal = _bcGoal; bcTakeReleased = 0; require(_buySlopeNum > 0, "INVALID_SLOPE_NUM"); require(_buySlopeDen > 0, "INVALID_SLOPE_DEN"); require(_buySlopeNum < MAX_BEFORE_SQUARE, "EXCESSIVE_SLOPE_NUM"); require(_buySlopeDen < MAX_BEFORE_SQUARE, "EXCESSIVE_SLOPE_DEN"); buySlopeNum = _buySlopeNum; buySlopeDen = _buySlopeDen; investmentReserveBasisPoints = _investmentReserveBasisPoints; beneficiary = msg.sender; control = msg.sender; feeCollector = msg.sender; { initReserve = _initReserve; _mint(beneficiary, initReserve); } abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes(version)), _getChainId(), address(this) ) ); uniswapFactory = IUniswapV2Factory(UNISWAP_FACTORY_ADDRESS); }
9,006,644
//SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "../interfaces/IEternalFactory.sol"; import "../interfaces/ILoyaltyGage.sol"; import "../gages/LoyaltyGage.sol"; import "../inheritances/OwnableEnhanced.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Contract for the Eternal gaging platform * @author Nobody (me) * @notice The Eternal Factory contract creates all gages and maintains sustainability of the system by enforcing limits. */ contract EternalFactory is IEternalFactory, OwnableEnhanced { /////–––««« Variables: Interfaces, Addresses and Hashes »»»––––\\\\\ // The Eternal shared storage interface IEternalStorage public immutable eternalStorage; // The Eternal token interface IERC20 private eternal; // The Eternal treasury interface IEternalTreasury private eternalTreasury; // The keccak256 hash of this address bytes32 public immutable entity; /////–––««« Variables: Hidden Mappings »»»––––\\\\\ /** // Keeps track of the respective gage tied to any given ID mapping (uint256 => address) gages // Keeps track of the risk percentage for any given asset's liquidity gage (x 10 ** 4) mapping (address => uint256) risk; // Keeps track of whether a user is in a liquid gage for a given asset mapping (address => mapping (address => bool)) inLiquidGage */ /////–––««« Variables: Gage Bookkeeping »»»––––\\\\\ // Keeps track of the latest Gage ID bytes32 public immutable lastId; /////–––««« Variables: Constants, Factors and Limits »»»––––\\\\\ // The holding time constant used in the percent change condition calculation (decided by the Eternal Fund) (x 10 ** 6) bytes32 public immutable timeFactor; // The average amount of time that users provide liquidity for (in days) bytes32 public immutable timeConstant; // The risk constant used in the calculation of the treasury's risk (x 10 ** 4) bytes32 public immutable riskConstant; // The general limiting variable deciding the total amount of ETRNL which can be used from the treasury's reserves bytes32 public immutable psi; /////–––««« Variables: Counters and Estimates »»»––––\\\\\ // The total number of ETRNL transacted with fees in the last full 24h period bytes32 public immutable alpha; // The total number of ETRNL transacted with fees in the current 24h period (ongoing) bytes32 public immutable transactionCount; // Keeps track of the UNIX time to recalculate the average transaction estimate bytes32 public immutable oneDayFromNow; // The minimum token value estimate of transactions in 24h, used in case the alpha value is not determined yet bytes32 public immutable baseline; /////–––««« Constructors & Initializers »»»––––\\\\\ constructor (address _eternalStorage, address _eternal) { // Set the initial Eternal storage and token interfaces eternalStorage = IEternalStorage(_eternalStorage); eternal = IERC20(_eternal); // Initialize keccak256 hashes entity = keccak256(abi.encodePacked(address(this))); lastId = keccak256(abi.encodePacked("lastId")); timeFactor = keccak256(abi.encodePacked("timeFactor")); timeConstant = keccak256(abi.encodePacked("timeConstant")); riskConstant = keccak256(abi.encodePacked("riskConstant")); baseline = keccak256(abi.encodePacked("baseline")); psi = keccak256(abi.encodePacked("psi")); alpha = keccak256(abi.encodePacked("alpha")); transactionCount = keccak256(abi.encodePacked("transactionCount")); oneDayFromNow = keccak256(abi.encodePacked("oneDayFromNow")); } function initialize(address _treasury, address _fund) external onlyAdmin { // Set the initial treasury interface eternalTreasury = IEternalTreasury(_treasury); // Set initial constants, factors and limiting variables eternalStorage.setUint(entity, timeFactor, 6 * (10 ** 6)); eternalStorage.setUint(entity, timeConstant, 15); eternalStorage.setUint(entity, riskConstant, 100); eternalStorage.setUint(entity, psi, 4164 * (10 ** 6) * (10 ** 18)); // Set initial baseline eternalStorage.setUint(entity, baseline, (10 ** 7) * (10 ** 18)); // Initialize the transaction count time tracker eternalStorage.setUint(entity, oneDayFromNow, block.timestamp + 1 days); // Set initial risk eternalStorage.setUint(entity, keccak256(abi.encodePacked("risk", 0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7)), 1100); eternalStorage.setUint(entity, keccak256(abi.encodePacked("risk", 0xA7D7079b0FEaD91F3e65f86E8915Cb59c1a4C664)), 1100); attributeFundRights(_fund); } /////–––««« Gage-logic functions »»»––––\\\\\ /** * @notice Creates an ETRNL liquid gage contract for using a given asset and amount. * @param asset The address of the asset being deposited in the liquid gage by the receiver * @param amount The amount of the asset being deposited in the liquid gage by the receiver * * Requirements: * * - The asset must be supported by Eternal * - Receivers (users) cannot deposit ETRNL into liquid gages * - There must be less active gages than the liquid gage limit dictates * - Users are only able to join 1 liquid gage per Asset-ETRNL pair offered (the maximum being the number of existing liquid gage pairs) * - The Eternal Treasury cannot have a liquidity swap in progress */ function initiateEternalLiquidGage(address asset, uint256 amount) external payable override { // Checks uint256 userRisk = eternalStorage.getUint(entity, keccak256(abi.encodePacked("risk", asset))); require(userRisk > 0, "This asset is not supported"); require(asset != address(eternal), "Receiver can't deposit ETRNL"); uint256 treasuryRisk = userRisk - eternalStorage.getUint(entity, riskConstant); require(!gageLimitReached(asset, amount, treasuryRisk), "ETRNL treasury reserves are dry"); bytes32 inGage = keccak256(abi.encodePacked("inLiquidGage", _msgSender(), asset)); bool inLiquidGage = eternalStorage.getBool(entity, inGage); require(!inLiquidGage, "Per-asset gaging limit reached"); eternalStorage.setBool(entity, inGage, true); require(!eternalTreasury.viewUndergoingSwap(), "A liquidity swap is in progress"); //Transfer the deposit to the treasury and join the gage for the user and the treasury if (msg.value == 0) { require(IERC20(asset).transferFrom(_msgSender(), address(eternalTreasury), amount), "Failed to deposit asset"); } else { require(msg.value == amount, "Msg.value must equate amount"); } // Incremement the lastId tracker uint256 idLast = eternalStorage.getUint(entity, lastId) + 1; eternalStorage.setUint(entity, lastId, idLast); // Deploy a new Gage LoyaltyGage newGage = new LoyaltyGage(idLast, percentCondition(), 2, false, address(eternalTreasury), _msgSender(), address(eternalStorage)); emit NewGage(idLast, address(newGage)); eternalStorage.setAddress(entity, keccak256(abi.encodePacked("gages", idLast)), address(newGage)); eternalTreasury.fundEternalLiquidGage{value: msg.value}(address(newGage), _msgSender(), asset, amount, userRisk, treasuryRisk); } /////–––««« Counter functions »»»––––\\\\\ /** * @notice Updates any 24h counter related to ETRNL in/outflow. * @param amount The value used to update the counters * * Requirements: * * - Only callable by the Eternal Token */ function updateCounters(uint256 amount) external override { require(_msgSender() == address(eternal), "Caller must be the token"); // If the 24h period is ongoing, then update the counter if (block.timestamp < eternalStorage.getUint(entity, oneDayFromNow)) { eternalStorage.setUint(entity, transactionCount, eternalStorage.getUint(entity, transactionCount) + amount); } else { // Update the baseline, alpha and the transaction count eternalStorage.setUint(entity, baseline, eternalStorage.getUint(entity, alpha)); eternalStorage.setUint(entity, alpha, eternalStorage.getUint(entity, transactionCount)); eternalStorage.setUint(entity, transactionCount, amount); // Reset the 24h period tracker eternalStorage.setUint(entity, oneDayFromNow, block.timestamp + 1 days); } } /////–––««« Utility functions »»»––––\\\\\ /** * @notice Computes whether there is enough ETRNL left in the treasury to allow for a given liquid gage (whilst remaining sustainable). * @param asset The address of the asset to be deposited to the specified liquid gage * @param amountAsset The amount of the asset being deposited to the specified liquid gage * @param risk The current risk percentage for an Eternal liquid gage with this asset as deposit * @return limitReached Whether the gaging limit is reached or not */ function gageLimitReached(address asset, uint256 amountAsset, uint256 risk) public view returns (bool limitReached) { bytes32 treasury = keccak256(abi.encodePacked(address(eternalTreasury))); // Convert the asset to ETRNL if it isn't already if (asset != address(eternal)) { (, , amountAsset) = eternalTreasury.computeMinAmounts(asset, address(eternal), amountAsset, 0); } // Calculate the treasury's currently available ETRNL uint256 treasuryReserve = eternalStorage.getUint(treasury, keccak256(abi.encodePacked("reserveBalances", address(eternalTreasury)))); // Available ETRNL is all the ETRNL which can be spent by the treasury on gages whilst still remaining sustainable uint256 availableETRNL = eternalTreasury.convertToStaked(treasuryReserve) - eternalStorage.getUint(entity, psi); limitReached = availableETRNL < amountAsset + (2 * amountAsset * risk / (10 ** 4)); } /** * @notice Computes the percent condition for a given Eternal gage. * @return uint256 The percent by which the ETRNL supply must decrease in order for a gage to close in favor of the receiver */ function percentCondition() public view returns (uint256) { uint256 _timeConstant = eternalStorage.getUint(entity, timeConstant); uint256 _timeFactor = eternalStorage.getUint(entity, timeFactor); uint256 burnRate = eternalStorage.getUint(keccak256(abi.encodePacked(address(eternal))), keccak256(abi.encodePacked("burnRate"))); uint256 _baseline = eternalStorage.getUint(entity, baseline); uint256 _alpha = eternalStorage.getUint(entity, alpha) < _baseline ? _baseline : eternalStorage.getUint(entity, alpha); return burnRate * _alpha * _timeConstant * _timeFactor / eternal.totalSupply(); } /////–––««« Fund-only functions »»»––––\\\\\ /** * @notice Updates the address of the Eternal Treasury contract. * @param newContract The new address for the Eternal Treasury contract */ function setEternalTreasury(address newContract) external onlyFund { eternalTreasury = IEternalTreasury(newContract); } /** * @notice Updates the address of the Eternal Token contract. * @param newContract The new address for the Eternal Token contract */ function setEternalToken(address newContract) external onlyFund { eternal = IERC20(newContract); } }
Computes the percent condition for a given Eternal gage. return uint256 The percent by which the ETRNL supply must decrease in order for a gage to close in favor of the receiver/
function percentCondition() public view returns (uint256) { uint256 _timeConstant = eternalStorage.getUint(entity, timeConstant); uint256 _timeFactor = eternalStorage.getUint(entity, timeFactor); uint256 burnRate = eternalStorage.getUint(keccak256(abi.encodePacked(address(eternal))), keccak256(abi.encodePacked("burnRate"))); uint256 _baseline = eternalStorage.getUint(entity, baseline); uint256 _alpha = eternalStorage.getUint(entity, alpha) < _baseline ? _baseline : eternalStorage.getUint(entity, alpha); return burnRate * _alpha * _timeConstant * _timeFactor / eternal.totalSupply(); }
7,244,086
./full_match/1/0x44b622a7CD27653DBEF271e30e9359DADC02C768/sources/browser/McdCreateFlashLoan.sol
Internal method that preforms a sell on 0x/on-chain Usefull for other DFS contract to integrate for exchanging exData Exchange data struct return (address, uint) Address of the wrapper used and destAmount if selling eth, convert to weth Try 0x first and then fallback on specific wrapper fallback to desired wrapper if 0x failed if anything is left in weth, pull it to user as eth
function _sell(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; uint tokensLeft = exData.srcAmount; if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); uint ethAmount = exData.srcAddr == WETH_ADDRESS ? msg.value - exData.srcAmount : msg.value; (success, swapedTokens, tokensLeft) = takeOrder(exData, ethAmount, ActionType.SELL); if (success) { wrapper = exData.exchangeAddr; } } if (!success) { swapedTokens = saverSwap(exData, ActionType.SELL); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), "Final amount isn't correct"); if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, swapedTokens); }
8,394,081
./partial_match/1/0x363B4B1ADa52E50353f746999bd9E94395190d2C/sources/contracts/libraries/rlp/RLPReader.sol
Copies the bytes from a memory location. _src Pointer to the location to read from. _offset Offset to start reading from. _length Number of bytes to read. return Copied bytes./
function _copy( MemoryPointer _src, uint256 _offset, uint256 _length ) private pure returns (bytes memory) { bytes memory out = new bytes(_length); if (_length == 0) { return out; } assembly { let dest := add(out, 32) let i := 0 for { i := add(i, 32) mstore(add(dest, i), mload(add(src, i))) } if gt(i, _length) { mstore(add(dest, _length), 0) } } return out; }
15,919,091
./partial_match/1/0x068326574be11546DEC87C3a2DA0eB2Ae8867368/sources/UNICARD.sol
get balance of liquidity pair calculate amount to burn pull tokens from pancakePair liquidity and move to dead address permanently
function autoBurnLiquidityPairTokens() internal returns (bool) { lastLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div( 10000 ); if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit AutoNukeLP(); return true; }
4,496,771
./partial_match/4/0x0316A65Ba45CFA7375E6e0153BF209Ec29B90832/sources/stake.sol
GlobalsCache memory g;GlobalsCache memory gSnapshot;_globalsLoad(g, gSnapshot);_dailyDataUpdateAuto(g);_globalsSync(g, gSnapshot);
function _waasLobby(uint256 enterDay) private returns (uint256 waasLobby) { if (enterDay > 0 && enterDay <= CLAIM_PHASE_END_DAY) { waasLobby = CLAIM_STARTING_AMOUNT - ((enterDay - 1) * CLAIM_DAILY_AMOUNT); } else{ waasLobby=CLAIM_DAILY_AMOUNT; } return waasLobby; }
8,563,969
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; interface IOracle { function value() external view returns (int256, bool); function update() external returns (bool); } /// @notice Emitted when paused error Pausable__whenNotPaused_paused(); /// @notice Emitted when not paused error Pausable__whenPaused_notPaused(); /// @title Guarded /// @notice Mixin implementing an authentication scheme on a method level abstract contract Guarded { /// ======== Custom Errors ======== /// error Guarded__notRoot(); error Guarded__notGranted(); /// ======== Storage ======== /// /// @notice Wildcard for granting a caller to call every guarded method bytes32 public constant ANY_SIG = keccak256("ANY_SIG"); /// @notice Wildcard for granting a caller to call every guarded method address public constant ANY_CALLER = address(uint160(uint256(bytes32(keccak256("ANY_CALLER"))))); /// @notice Mapping storing who is granted to which method /// @dev Method Signature => Caller => Bool mapping(bytes32 => mapping(address => bool)) private _canCall; /// ======== Events ======== /// event AllowCaller(bytes32 sig, address who); event BlockCaller(bytes32 sig, address who); constructor() { // set root _setRoot(msg.sender); } /// ======== Auth ======== /// modifier callerIsRoot() { if (_canCall[ANY_SIG][msg.sender]) { _; } else revert Guarded__notRoot(); } modifier checkCaller() { if (canCall(msg.sig, msg.sender)) { _; } else revert Guarded__notGranted(); } /// @notice Grant the right to call method `sig` to `who` /// @dev Only the root user (granted `ANY_SIG`) is able to call this method /// @param sig_ Method signature (4Byte) /// @param who_ Address of who should be able to call `sig` function allowCaller(bytes32 sig_, address who_) public callerIsRoot { _canCall[sig_][who_] = true; emit AllowCaller(sig_, who_); } /// @notice Revoke the right to call method `sig` from `who` /// @dev Only the root user (granted `ANY_SIG`) is able to call this method /// @param sig_ Method signature (4Byte) /// @param who_ Address of who should not be able to call `sig` anymore function blockCaller(bytes32 sig_, address who_) public callerIsRoot { _canCall[sig_][who_] = false; emit BlockCaller(sig_, who_); } /// @notice Returns if `who` can call `sig` /// @param sig_ Method signature (4Byte) /// @param who_ Address of who should be able to call `sig` function canCall(bytes32 sig_, address who_) public view returns (bool) { return (_canCall[sig_][who_] || _canCall[ANY_SIG][who_] || _canCall[sig_][ANY_CALLER]); } /// @notice Sets the root user (granted `ANY_SIG`) /// @param root_ Address of who should be set as root function _setRoot(address root_) internal { _canCall[ANY_SIG][root_] = true; emit AllowCaller(ANY_SIG, root_); } } contract Pausable is Guarded { event Paused(address who); event Unpaused(address who); bool private _paused; function paused() public view virtual returns (bool) { return _paused; } modifier whenNotPaused() { // If the contract is paused, throw an error if (_paused) { revert Pausable__whenNotPaused_paused(); } _; } modifier whenPaused() { // If the contract is not paused, throw an error if (_paused == false) { revert Pausable__whenPaused_notPaused(); } _; } function _pause() internal whenNotPaused { _paused = true; emit Paused(msg.sender); } function _unpause() internal whenPaused { _paused = false; emit Unpaused(msg.sender); } } abstract contract Oracle is Pausable, IOracle { /// @notice Emitted when a method is reentered error Oracle__nonReentrant(); /// ======== Events ======== /// event ValueInvalid(); event ValueUpdated(int256 currentValue, int256 nextValue); event OracleReset(); /// ======== Storage ======== /// // Time interval between the value updates uint256 public immutable timeUpdateWindow; // Timestamp of the current value uint256 public lastTimestamp; // The next value that will replace the current value once the timeUpdateWindow has passed int256 public nextValue; // Current value that will be returned by the Oracle int256 private _currentValue; // Flag that tells if the value provider returned successfully bool private _validReturnedValue; // Reentrancy constants uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; // Reentrancy guard flag uint256 private _reentrantGuard = _NOT_ENTERED; /// ======== Modifiers ======== /// modifier nonReentrant() { // Check if the guard is set if (_reentrantGuard != _NOT_ENTERED) { revert Oracle__nonReentrant(); } // Set the guard _reentrantGuard = _ENTERED; // Allow execution _; // Reset the guard _reentrantGuard = _NOT_ENTERED; } constructor(uint256 timeUpdateWindow_) { timeUpdateWindow = timeUpdateWindow_; _validReturnedValue = false; } /// @notice Get the current value of the oracle /// @return The current value of the oracle /// @return Whether the value is valid function value() public view override(IOracle) whenNotPaused returns (int256, bool) { // Value is considered valid if the value provider successfully returned a value return (_currentValue, _validReturnedValue); } function getValue() external virtual returns (int256); function update() public override(IOracle) checkCaller nonReentrant returns (bool) { // Not enough time has passed since the last update if (lastTimestamp + timeUpdateWindow > block.timestamp) { // Exit early if no update is needed return false; } // Oracle update should not fail even if the value provider fails to return a value try this.getValue() returns (int256 returnedValue) { // Update the value using an exponential moving average if (_currentValue == 0) { // First update takes the current value nextValue = returnedValue; _currentValue = nextValue; } else { // Update the current value with the next value _currentValue = nextValue; // Set the returnedValue as the next value nextValue = returnedValue; } // Save when the value was last updated lastTimestamp = block.timestamp; _validReturnedValue = true; emit ValueUpdated(_currentValue, nextValue); return true; } catch { // When a value provider fails, we update the valid flag which will // invalidate the value instantly _validReturnedValue = false; emit ValueInvalid(); } return false; } function pause() public checkCaller { _pause(); } function unpause() public checkCaller { _unpause(); } function reset() public whenPaused checkCaller { _currentValue = 0; nextValue = 0; lastTimestamp = 0; _validReturnedValue = false; emit OracleReset(); } } contract Convert { function convert( int256 x_, uint256 currentPrecision_, uint256 targetPrecision_ ) internal pure returns (int256) { if (targetPrecision_ > currentPrecision_) return x_ * int256(10**(targetPrecision_ - currentPrecision_)); return x_ / int256(10**(currentPrecision_ - targetPrecision_)); } function uconvert( uint256 x_, uint256 currentPrecision_, uint256 targetPrecision_ ) internal pure returns (uint256) { if (targetPrecision_ > currentPrecision_) return x_ * 10**(targetPrecision_ - currentPrecision_); return x_ / 10**(currentPrecision_ - targetPrecision_); } } // Chainlink Aggregator v3 interface // https://github.com/smartcontractkit/chainlink/blob/6fea3ccd275466e082a22be690dbaf1609f19dce/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol interface IChainlinkAggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } contract ChainlinkValueProvider is Oracle, Convert { uint8 public immutable underlierDecimals; address public chainlinkAggregatorAddress; /// @notice Constructs the Value provider contracts with the needed Chainlink. /// @param timeUpdateWindow_ Minimum time between updates of the value /// @param chainlinkAggregatorAddress_ Address of the deployed chainlink aggregator contract. constructor( // Oracle parameters uint256 timeUpdateWindow_, // Chainlink specific parameter address chainlinkAggregatorAddress_ ) Oracle(timeUpdateWindow_) { chainlinkAggregatorAddress = chainlinkAggregatorAddress_; underlierDecimals = IChainlinkAggregatorV3Interface( chainlinkAggregatorAddress_ ).decimals(); } /// @notice Retrieves the price from the chainlink aggregator /// @return result The result as an signed 59.18-decimal fixed-point number. function getValue() external view override(Oracle) returns (int256) { // Convert the annual rate to 1e18 precision. (, int256 answer, , , ) = IChainlinkAggregatorV3Interface( chainlinkAggregatorAddress ).latestRoundData(); return convert(answer, underlierDecimals, 18); } /// @notice returns the description of the chainlink aggregator the proxy points to. function description() external view returns (string memory) { return IChainlinkAggregatorV3Interface(chainlinkAggregatorAddress) .description(); } }
Chainlink Aggregator v3 interface https:github.com/smartcontractkit/chainlink/blob/6fea3ccd275466e082a22be690dbaf1609f19dce/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol getRoundData and latestRoundData should both raise "No data present" if they do not have data to report, instead of returning unset values which could be misinterpreted as actual reported values.
interface IChainlinkAggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); }
13,735,925
./full_match/10200/0x4bF8A3F713538270f2b5d8Fc1Da5d380C4dA3d13/sources/newHashi/contracts/Yaho.sol
Relays hashes of the given messageIds to the given adapters. messageIds Array of IDs of the message hashes to relay to the given adapters. adapters Array of relay adapter addresses to which hashes should be relayed. destinationAdapters Array of oracle adapter addresses to receive hashes. return adapterReciepts Reciepts from each of the relay adapters.
function relayMessagesToAdapters( uint256[] memory messageIds, address[] memory adapters, address[] memory destinationAdapters ) external payable returns (bytes32[] memory) { if (messageIds.length == 0) revert NoMessageIdsGiven(address(this)); if (adapters.length == 0) revert NoAdaptersGiven(address(this)); if (adapters.length != destinationAdapters.length) revert UnequalArrayLengths(address(this)); bytes32[] memory adapterReciepts = new bytes32[](adapters.length); for (uint256 i = 0; i < adapters.length; i++) { adapterReciepts[i] = IMessageRelay(adapters[i]).relayMessages(messageIds, destinationAdapters[i]); } return adapterReciepts; }
3,785,132
./full_match/43113/0xdB07a5f2B46bedA613f05fc1feb5fb97892E9890/sources/contracts/TheMetaWitch.sol
uint currentSupply = totalSupply();
function calculatePrice() public view returns (uint256) { require(isActive == true, "Sale hasn't started"); require(totalSupply() < MAX_NFTS, "Sale has already ended"); return 15000000000000000; }
7,169,839
./full_match/1/0xf79F58075a5Eb5a319DA62699aDFE58C65100bd8/sources/contracts/AuctionContract.sol
由平台发起的提现,需要收取提现手续费以支付gas费 send the funds
function withdrawTo(uint _tokenid, address _to) onlyEndedOrCanceled(_tokenid) public returns (bool success) { require(_to == msg.sender || msg.sender == owner(), "AuctionContract_withdrawTo_invalid_caller"); address withdrawalAccount; uint withdrawalAmount; BidRecord storage record = auctionRecord[_tokenid]; require(record.fundsByBidder[_to] > 0, "AuctionContract_withdrawTo_no_fund"); if (!record.canceled) { require(msg.sender != record.highestBidder, "AuctionContract_withdrawTo_no_winner"); } withdrawalAccount = _to; withdrawalAmount = record.fundsByBidder[withdrawalAccount]; require(withdrawalAmount > withdrawFee, "AuctionContract_withdrawTo_too_less_value"); record.fundsByBidder[withdrawalAccount] = SafeMath.sub(record.fundsByBidder[withdrawalAccount], withdrawalAmount); uint userWithdrawalAmount = withdrawalAmount; record.totalFunds = SafeMath.sub(record.totalFunds, withdrawalAmount); require(record.fundsByBidder[withdrawalAccount] == 0, "AuctionContract_withdrawTo_should_no_remaining"); if (msg.sender == owner()) { userWithdrawalAmount = SafeMath.sub(userWithdrawalAmount, withdrawFee); } if (record.bidQuote == address(0)) { if (!sendEth(_to, userWithdrawalAmount)) revert(); if (!sendErc20(_to, userWithdrawalAmount, record.bidQuote)) revert(); } emit LogWithdrawal(_tokenid, msg.sender, _to, userWithdrawalAmount); return true; }
2,958,325
pragma solidity ^0.4.15; /* ERC20 Standard Token interface */ contract IERC20Token { // these functions aren't abstract since the compiler emits automatically generated getter functions as external function name() public constant returns (string) {} function symbol() public constant returns (string) {} function decimals() public constant returns (uint8) {} function totalSupply() public constant returns (uint) {} function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); function balanceOf(address _owner) public constant returns (uint balance); function allowance(address _owner, address _spender) public constant returns (uint remaining); event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, 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) { 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; } } /** * @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 IERC20Token { using SafeMath for uint; mapping (address => mapping (address => uint256)) internal allowed; mapping (address => uint) balances; uint256 totalSupply_; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @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); 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); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Burnable * * @dev Standard ERC20 token */ contract Burnable is StandardToken { using SafeMath for uint; /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint value); function burn(uint _value) public returns (bool success) { require(_value > 0 && balances[msg.sender] >= _value); balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply_ = totalSupply_.sub(_value); Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint _value) public returns (bool success) { require(_from != 0x0 && _value > 0 && balances[_from] >= _value); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); totalSupply_ = totalSupply_.sub(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Burn(_from, _value); return true; } function transfer(address _to, uint _value) public returns (bool success) { require(_to != 0x0); //use burn return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) public returns (bool success) { require(_to != 0x0); //use burn return super.transferFrom(_from, _to, _value); } } /* Utilities & Common Modifiers */ contract Utils { /** constructor */ function Utils() public { } // verifies that an amount is greater than zero modifier greaterThanZero(uint _amount) { require(_amount > 0); _; } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { require(_address != 0x0); _; } // verifies that the address is different than this contract address modifier notThis(address _address) { require(_address != address(this)); _; } function _validAddress(address _address) internal pure returns (bool) { return _address != 0x0; } // Overflow protected math functions /** @dev returns the sum of _x and _y, asserts if the calculation overflows @param _x value 1 @param _y value 2 @return sum */ function safeAdd(uint _x, uint _y) internal pure returns (uint) { uint z = _x + _y; assert(z >= _x); return z; } /** @dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number @param _x minuend @param _y subtrahend @return difference */ function safeSub(uint _x, uint _y) internal pure returns (uint) { assert(_x >= _y); return _x - _y; } /** @dev returns the product of multiplying _x by _y, asserts if the calculation overflows @param _x factor 1 @param _y factor 2 @return product */ function safeMul(uint _x, uint _y) internal pure returns (uint) { uint z = _x * _y; assert(_x == 0 || z / _x == _y); return z; } } /* Owned contract interface */ contract IOwned { // this function isn't abstract since the compiler emits automatically generated getter functions as external function owner() public constant returns (address) {} function transferOwnership(address _newOwner) public; } /* Token Holder interface */ contract ITokenHolder is IOwned { function withdrawTokens(IERC20Token _token, address _to, uint _amount) 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)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /* We consider every contract to be a 'token holder' since it's currently not possible for a contract to deny receiving tokens. The TokenHolder's contract sole purpose is to provide a safety mechanism that allows the owner to send tokens that were sent to the contract by mistake back to their sender. */ contract TokenHolder is ITokenHolder, Ownable, Utils { // @dev constructor function TokenHolder() public { } // @dev withdraws tokens held by the contract and sends them to an account // can only be called by the owner // @param _token ERC20 token contract address // @param _to account to receive the new amount // @param _amount amount to withdraw function withdrawTokens(IERC20Token _token, address _to, uint _amount) public onlyOwner validAddress(_to) { require(_to != address(this)); assert(_token.transfer(_to, _amount)); } } /* Smart Token interface */ contract ISmartToken is IOwned, IERC20Token { function disableTransfers(bool _disable) public; function issue(address _to, uint _amount) public; function destroy(address _from, uint _amount) public; } contract SmartToken is ISmartToken, Burnable, TokenHolder { string public version = '0.3'; bool public transfersEnabled = true; // true if transfer/transferFrom are enabled, false if not // triggered when a smart token is deployed - the _token address is defined for forward compatibility, in case we want to trigger the event from a factory event NewSmartToken(address _token); // triggered when the total supply is increased event Issuance(uint _amount); // triggered when the total supply is decreased event Destruction(uint _amount); // allows execution only when transfers aren't disabled modifier transfersAllowed { assert(transfersEnabled); _; } /** @dev disables/enables transfers can only be called by the contract owner @param _disable true to disable transfers, false to enable them */ function disableTransfers(bool _disable) public onlyOwner { transfersEnabled = !_disable; } /** @dev increases the token supply and sends the new tokens to an account can only be called by the contract owner @param _to account to receive the new amount @param _amount amount to increase the supply by */ function issue(address _to, uint _amount) public onlyOwner validAddress(_to) notThis(_to) { totalSupply_ = safeAdd(totalSupply_, _amount); balances[_to] = safeAdd(balances[_to], _amount); Issuance(_amount); Transfer(this, _to, _amount); } /** @dev removes tokens from an account and decreases the token supply can be called by the contract owner to destroy tokens from any account or by any holder to destroy tokens from his/her own account @param _from account to remove the amount from @param _amount amount to decrease the supply by */ function destroy(address _from, uint _amount) public { require(msg.sender == _from || msg.sender == owner); // validate input balances[_from] = safeSub(balances[_from], _amount); totalSupply_ = safeSub(totalSupply_, _amount); Transfer(_from, this, _amount); Destruction(_amount); } // ERC20 standard method overrides with some extra functionality /** @dev send coins throws on any error rather then return a false flag to minimize user errors in addition to the standard checks, the function throws if transfers are disabled @param _to target address @param _value transfer amount @return true if the transfer was successful, false if it wasn't */ function transfer(address _to, uint _value) public transfersAllowed returns (bool success) { assert(super.transfer(_to, _value)); return true; } /** @dev an account/contract attempts to get the coins throws on any error rather then return a false flag to minimize user errors in addition to the standard checks, the function throws if transfers are disabled @param _from source address @param _to target address @param _value transfer amount @return true if the transfer was successful, false if it wasn't */ function transferFrom(address _from, address _to, uint _value) public transfersAllowed returns (bool success) { assert(super.transferFrom(_from, _to, _value)); return true; } } contract ContractReceiver { function tokenFallback(address _from, uint _value, bytes _data) external; } /** * @title FinTabToken * * @dev Burnable Ownable ERC223(and ERC20-compilant) token with support of * Bancor SmartToken protocol */ contract FinTabToken is SmartToken { uint public constant INITIAL_SUPPLY = 3079387 * (10 ** 8); uint public releaseTokensBlock; //Approximatly will be at 01.07.2018 mapping (address => bool) public teamAddresses; mapping (address => bool) public tokenBurners; event Transfer(address indexed _from, address indexed _to, uint _value, bytes _data); // Limit token transfer for the team modifier canTransfer(address _sender) { require(block.number >= releaseTokensBlock || !teamAddresses[_sender]); _; } modifier canBurnTokens(address _sender) { require(tokenBurners[_sender] == true || owner == _sender); _; } // Token construcor function FinTabToken(uint _releaseBlock) public { releaseTokensBlock = _releaseBlock; totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; NewSmartToken(this); } function name() public constant returns (string) { return "FinTab"; } function symbol() public constant returns (string) { return "FNTB" ;} function decimals() public constant returns (uint8) { return 8; } function totalSupply() public constant returns (uint) { return totalSupply_; } function balanceOf(address _owner) public constant returns (uint balance) { require(_owner != 0x0); return balances[_owner]; } // Owner can allow a particular address (a crowdsale contract) to transfer tokens despite the lock up period. function setTeamAddress(address addr, bool state) onlyOwner public { require(addr != 0x0); teamAddresses[addr] = state; } function setBurner(address addr, bool state) onlyOwner public { require(addr != 0x0); tokenBurners[addr] = state; } // Function that is called when a user or another contract wants to transfer funds . function transfer(address _to, uint _value, bytes _data) transfersAllowed canTransfer(msg.sender) public returns (bool success) { if(isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . function transfer(address _to, uint _value) transfersAllowed canTransfer(msg.sender) public returns (bool success) { //standard function transfer similar to ERC20 transfer with no _data //added due to backwards compatibility reasons bytes memory empty; if(isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } // Transfer on _from behalf function transferFrom(address _from, address _to, uint _value) transfersAllowed canTransfer(_from) public returns (bool success) { // Call Burnable.transferForm() return super.transferFrom(_from, _to, _value); } // Burn tokens function burn(uint _value) canBurnTokens(msg.sender) public returns (bool success) { return super.burn(_value); } // Burn tokens on _from behalf function burnFrom(address _from, uint _value) onlyOwner canBurnTokens(msg.sender) public returns (bool success) { return super.burnFrom(_from, _value); } //assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length>0); } //function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes _data) private canTransfer(msg.sender) returns (bool success) { require(balanceOf(msg.sender) >= _value); balances[msg.sender] = safeSub(balanceOf(msg.sender), _value); balances[_to] = safeAdd(balanceOf(_to), _value); Transfer(msg.sender, _to, _value); return true; } //function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data) private canTransfer(msg.sender) returns (bool success) { require(balanceOf(msg.sender) >= _value); balances[msg.sender] = safeSub(balanceOf(msg.sender), _value); balances[_to] = safeAdd(balanceOf(_to), _value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value); return true; } }
This notifies clients about the amount burnt /
function burn(uint _value) public returns (bool success) { require(_value > 0 && balances[msg.sender] >= _value); balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply_ = totalSupply_.sub(_value); Burn(msg.sender, _value); return true; }
1,059,885
./full_match/3/0x5Cdb4992f4c81a54eBd19b1a1aC8Cec679E9620f/sources/contracts/Auction.sol
TODO: this is only for testnet
function changeAuctionEnd(uint auctionId, uint deadline) external onlyOwner { require(auctionId <= lastAuctionId, "HardStakingNFTAuction: No such auction Id"); auctions[auctionId].auctionEnd = deadline; }
14,226,918
//https://t.me/+Gt9qqBTkLKo3ZWFk // SPDX-License-Identifier: MIT pragma solidity 0.8.9; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } 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 EightyEightPlus is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public 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 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("88+", "88+") { 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 = 4; uint256 _buyLiquidityFee = 10; uint256 _buyDevFee = 1; uint256 _sellMarketingFee = 5; uint256 _sellLiquidityFee = 14; uint256 _sellDevFee = 1; uint256 totalSupply = 1 * 1e9 * 1e18; maxTransactionAmount = totalSupply * 10 / 1000; // 1% maxTransactionAmountTxn maxWallet = totalSupply * 25 / 1000; // 2.5% 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; 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; lastLpBurnTime = 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)/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) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; 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 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"); 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"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // 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 deadAddress, 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 setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner { require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes"); require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%"); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool){ lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
exclude from paying fees or having max transaction amount
constructor() ERC20("88+", "88+") { 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 = 4; uint256 _buyLiquidityFee = 10; uint256 _buyDevFee = 1; uint256 _sellMarketingFee = 5; uint256 _sellLiquidityFee = 14; uint256 _sellDevFee = 1; uint256 totalSupply = 1 * 1e9 * 1e18; 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,196,255
pragma solidity ^0.4.18; // File: zeppelin-solidity/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)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: zeppelin-solidity/contracts/lifecycle/Destructible.sol /** * @title Destructible * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. */ contract Destructible is Ownable { function Destructible() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } // File: zeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } // File: zeppelin-solidity/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) { 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; } } // File: zeppelin-solidity/contracts/payment/PullPayment.sol /** * @title PullPayment * @dev Base contract supporting async send for pull payments. Inherit from this * contract and use asyncSend instead of send. */ contract PullPayment { using SafeMath for uint256; mapping(address => uint256) public payments; uint256 public totalPayments; /** * @dev withdraw accumulated balance, called by payee. */ function withdrawPayments() public { address payee = msg.sender; uint256 payment = payments[payee]; require(payment != 0); require(this.balance >= payment); totalPayments = totalPayments.sub(payment); payments[payee] = 0; assert(payee.send(payment)); } /** * @dev Called by the payer to store the sent amount as credit to be pulled. * @param dest The destination address of the funds. * @param amount The amount to transfer. */ function asyncSend(address dest, uint256 amount) internal { payments[dest] = payments[dest].add(amount); totalPayments = totalPayments.add(amount); } } // File: contracts/GoGlobals.sol /// @title The base contract for EthernalGo, contains the admin functions and the globals used throught the game /// @author https://www.EthernalGo.com /// @dev See the GoGameLogic and GoBoardMetaDetails contract documentation to understand the actual game mechanics. contract GoGlobals is Ownable, PullPayment, Destructible, Pausable { // Used for simplifying capture calculations uint8 constant MAX_UINT8 = 255; // Used to dermine player color and who is up next enum PlayerColor {None, Black, White} /// @dev Board status is a critical concept that determines which actions can be taken within each phase /// WaitForOpponent - When the first player has registered and waiting for a second player /// InProgress - The match is on! The acting player can choose between placing a stone or passing (or resigning) /// WaitingToResolve - Both players chose to pass their turn and we are waiting for the winner to ask the contract for score count /// BlackWin, WhiteWin, Draw - Pretty self explanatory /// Canceled - The first player who joined the board is allowed to cancel a match if no opponent has joined yet enum BoardStatus {WaitForOpponent, InProgress, WaitingToResolve, BlackWin, WhiteWin, Draw, Canceled} // We staretd with a 9x9 rows uint8 constant BOARD_ROW_SIZE = 9; uint8 constant BOARD_SIZE = BOARD_ROW_SIZE ** 2; // We use a shrinked board size to optimize gas costs uint8 constant SHRINKED_BOARD_SIZE = 21; // These are the shares each player and EthernalGo are getting for each game uint public WINNER_SHARE; uint public HOST_SHARE; uint public HONORABLE_LOSS_BONUS; // Each player gets PLAYER_TURN_SINGLE_PERIOD x PLAYER_START_PERIODS to act. These may change according to player feedback and network conjunction to optimize the playing experience uint public PLAYER_TURN_SINGLE_PERIOD = 4 minutes; uint8 public PLAYER_START_PERIODS = 5; // We decided to restrict the table stakes to several options to allow for easier match-making uint[] public tableStakesOptions; // This is the main data field that contains access to all of the GoBoards that were created GoBoard[] internal allBoards; // The CFO is the only account that is allowed to withdraw funds address public CFO; // This is the main board structure and is instantiated for every new game struct GoBoard { // We use the last update to determine how long has it been since the player could act uint lastUpdate; // The table stakes marks how much ETH each participant needs to pay to register for the board uint tableStakes; // The board balance keeps track of how much ETH this board has in order to see if we already distributed the payments for this match uint boardBalance; // Black and white player addresses address blackAddress; address whiteAddress; // Black and white time periods remaining (initially they will be PLAYER_START_PERIODS) uint8 blackPeriodsRemaining; uint8 whitePeriodsRemaining; // Keep track of double pass to finish the game bool didPassPrevTurn; // Keep track of double pass to finish the game bool isHonorableLoss; // Who's next PlayerColor nextTurnColor; // Use a mapping to figure out which stone is set in which position. (Positions can be 0-BOARD_SIZE) // @dev We decided not use an array to minimize the storage cost mapping(uint8=>uint8) positionToColor; // The board's current status BoardStatus status; } /// @notice The constructor is called with our inital values, they will probably change but this is what had in mind when developing the game. function GoGlobals() public Ownable() PullPayment() Destructible() { // Add initial price tiers so from variouos ranges addPriceTier(0.5 ether); addPriceTier(1 ether); addPriceTier(5 ether); // These are the inital shares we've had in mind when developing the game updateShares(950, 50, 5); // The CFO will be the owner, but it will change soon after the contract is deployed CFO = owner; } /// @notice In case we need extra price tiers (table stakes where people can play) we can add additional ones /// @param price the price for the new price tier in WEI function addPriceTier(uint price) public onlyOwner { tableStakesOptions.push(price); } /// If we need to update price tiers /// @param priceTier the tier index from the array /// @param price the new price to set function updatePriceTier(uint8 priceTier, uint price) public onlyOwner { tableStakesOptions[priceTier] = price; } /// @notice If we need to adjust the amounts players or EthernalGo gets for each game /// @param newWinnerShare the winner's share (out of 1000) /// @param newHostShare EthernalGo's share (out of 1000) /// @param newBonusShare Bonus that comes our of EthernalGo and goes to the loser in case of an honorable loss (out of 1000) function updateShares(uint newWinnerShare, uint newHostShare, uint newBonusShare) public onlyOwner { require(newWinnerShare + newHostShare == 1000); WINNER_SHARE = newWinnerShare; HOST_SHARE = newHostShare; HONORABLE_LOSS_BONUS = newBonusShare; } /// @notice Separating the CFO and the CEO responsibilities requires the ability to set the CFO account /// @param newCFO the new CFO function setNewCFO(address newCFO) public onlyOwner { require(newCFO != 0); CFO = newCFO; } /// @notice Separating the CFO and the CEO responsibilities requires the ability to set the CFO account /// @param secondsPerPeriod The number of seconds we would like each period to last /// @param numberOfPeriods The number of of periods each player initially has function updateGameTimes(uint secondsPerPeriod, uint8 numberOfPeriods) public onlyOwner { PLAYER_TURN_SINGLE_PERIOD = secondsPerPeriod; PLAYER_START_PERIODS = numberOfPeriods; } /// @dev Convinience function to access the shares function getShares() public view returns(uint, uint, uint) { return (WINNER_SHARE, HOST_SHARE, HONORABLE_LOSS_BONUS); } } // File: contracts/GoBoardMetaDetails.sol /// @title This contract manages the meta details of EthernalGo. /// Registering to a board, splitting the revenues and other day-to-day actions that are unrelated to the actual game /// @author https://www.EthernalGo.com /// @dev See the GoGameLogic to understand the actual game mechanics and rules contract GoBoardMetaDetails is GoGlobals { /// @dev The player added to board event can be used to check upon registration success event PlayerAddedToBoard(uint boardId, address playerAddress); /// @dev The board updated status can be used to get the new board status event BoardStatusUpdated(uint boardId, BoardStatus newStatus); /// @dev The player withdrawn his accumulated balance event PlayerWithdrawnBalance(address playerAddress); /// @dev Simple wrapper to return the number of boards in total function getTotalNumberOfBoards() public view returns(uint) { return allBoards.length; } /// @notice We would like to easily and transparantly share the game's statistics with anyone and present on the web-app function getCompletedGamesStatistics() public view returns(uint, uint) { uint completed = 0; uint ethPaid = 0; // @dev Go through all the boards, we start with 1 as it's an unsigned int for (uint i = 1; i <= allBoards.length; i++) { // Get the current board GoBoard storage board = allBoards[i - 1]; // Check if it was a victory, otherwise it's not interesting as the players just got their deposit back if ((board.status == BoardStatus.BlackWin) || (board.status == BoardStatus.WhiteWin)) { ++completed; // We need to query the table stakes as the board's balance will be zero once a game is finished ethPaid += board.tableStakes.mul(2); } } return (completed, ethPaid); } /// @dev At this point there is no support for returning dynamic arrays (it's supported for web3 calls but not for internal testing) so we will "only" present the recent 50 games per player. uint8 constant PAGE_SIZE = 50; /// @dev Make sure this board is in waiting for result status modifier boardWaitingToResolve(uint boardId){ require(allBoards[boardId].status == BoardStatus.WaitingToResolve); _; } /// @dev Make sure this board is in one of the end of game states modifier boardGameEnded(GoBoard storage board){ require(isEndGameStatus(board.status)); _; } /// @dev Make sure this board still has balance modifier boardNotPaid(GoBoard storage board){ require(board.boardBalance > 0); _; } /// @dev Make sure this board still has a spot for at least one player to join modifier boardWaitingForPlayers(uint boardId){ require(allBoards[boardId].status == BoardStatus.WaitForOpponent && (allBoards[boardId].blackAddress == 0 || allBoards[boardId].whiteAddress == 0)); _; } /// @dev Restricts games for the allowed table stakes /// @param value the value we are looking for to register modifier allowedValuesOnly(uint value){ bool didFindValue = false; // The number of tableStakesOptions can change hence it has to be dynamic for (uint8 i = 0; i < tableStakesOptions.length; ++ i) { if (value == tableStakesOptions[i]) didFindValue = true; } require (didFindValue); _; } /// @dev Checks a status if and returns if it's an end game /// @param status the value we are checking /// @return true if it's an end-game status function isEndGameStatus(BoardStatus status) public pure returns(bool) { return (status == BoardStatus.BlackWin) || (status == BoardStatus.WhiteWin) || (status == BoardStatus.Draw) || (status == BoardStatus.Canceled); } /// @dev Gets the update time for a board /// @param boardId The id of the board to check /// @return the update timestamp in seconds function getBoardUpdateTime(uint boardId) public view returns(uint) { GoBoard storage board = allBoards[boardId]; return (board.lastUpdate); } /// @dev Gets the current board status /// @param boardId The id of the board to check /// @return the current board status function getBoardStatus(uint boardId) public view returns(BoardStatus) { GoBoard storage board = allBoards[boardId]; return (board.status); } /// @dev Gets the current balance of the board /// @param boardId The id of the board to check /// @return the current board balance in WEI function getBoardBalance(uint boardId) public view returns(uint) { GoBoard storage board = allBoards[boardId]; return (board.boardBalance); } /// @dev Sets the current balance of the board, this is internal and is triggerred by functions run by external player actions /// @param board The board to update /// @param boardId The board's Id /// @param newStatus The new status to set function updateBoardStatus(GoBoard storage board, uint boardId, BoardStatus newStatus) internal { // Save gas if we accidentally are trying to update to an existing update if (newStatus != board.status) { // Set the new board status board.status = newStatus; // Update the time (important for start and finish states) board.lastUpdate = now; // If this is an end game status if (isEndGameStatus(newStatus)) { // Credit the players accoriding to the board score creditBoardGameRevenues(board); } // Notify status update BoardStatusUpdated(boardId, newStatus); } } /// @dev Overload to set the board status when we only have a boardId /// @param boardId The boardId to update /// @param newStatus The new status to set function updateBoardStatus(uint boardId, BoardStatus newStatus) internal { updateBoardStatus(allBoards[boardId], boardId, newStatus); } /// @dev Gets the player color given an address and board (overload for when we only have boardId) /// @param boardId The boardId to check /// @param searchAddress The player's address we are searching for /// @return the player's color function getPlayerColor(uint boardId, address searchAddress) internal view returns (PlayerColor) { return (getPlayerColor(allBoards[boardId], searchAddress)); } /// @dev Gets the player color given an address and board /// @param board The board to check /// @param searchAddress The player's address we are searching for /// @return the player's color function getPlayerColor(GoBoard storage board, address searchAddress) internal view returns (PlayerColor) { // Check if this is the black player if (board.blackAddress == searchAddress) { return (PlayerColor.Black); } // Check if this is the white player if (board.whiteAddress == searchAddress) { return (PlayerColor.White); } // We aren't suppose to try and get the color of a player if they aren't on the board revert(); } /// @dev Gets the player address given a color on the board /// @param boardId The board to check /// @param color The color of the player we want /// @return the player's address function getPlayerAddress(uint boardId, PlayerColor color) public view returns(address) { // If it's the black player if (color == PlayerColor.Black) { return allBoards[boardId].blackAddress; } // If it's the white player if (color == PlayerColor.White) { return allBoards[boardId].whiteAddress; } // We aren't suppose to try and get the color of a player if they aren't on the board revert(); } /// @dev Check if a player is on board (overload for boardId) /// @param boardId The board to check /// @param searchAddress the player's address we want to check /// @return true if the player is playing in the board function isPlayerOnBoard(uint boardId, address searchAddress) public view returns(bool) { return (isPlayerOnBoard(allBoards[boardId], searchAddress)); } /// @dev Check if a player is on board /// @param board The board to check /// @param searchAddress the player's address we want to check /// @return true if the player is playing in the board function isPlayerOnBoard(GoBoard storage board, address searchAddress) private view returns(bool) { return (board.blackAddress == searchAddress || board.whiteAddress == searchAddress); } /// @dev Check which player acts next /// @param boardId The board to check /// @return The color of the current player to act function getNextTurnColor(uint boardId) public view returns(PlayerColor) { return allBoards[boardId].nextTurnColor; } /// @notice This is the first function a player will be using in order to start playing. This function allows /// to register to an existing or a new board, depending on the current available boards. /// Upon registeration the player will pay the board's stakes and will be the black or white player. /// The black player also creates the board, and is the first player which gives a small advantage in the /// game, therefore we decided that the black player will be the one paying for the additional gas /// that is required to create the board. /// @param tableStakes The tablestakes to use, although this appears in the "value" of the message, we preferred to /// add it as an additional parameter for client use for clients that allow to customize the value parameter. /// @return The boardId the player registered to (either a new board or an existing board) function registerPlayerToBoard(uint tableStakes) external payable allowedValuesOnly(msg.value) whenNotPaused returns(uint) { // Make sure the value and tableStakes are the same require (msg.value == tableStakes); GoBoard storage boardToJoin; uint boardIDToJoin; // Check which board to connect to (boardIDToJoin, boardToJoin) = getOrCreateWaitingBoard(tableStakes); // Add the player to the board (they already paid) bool shouldStartGame = addPlayerToBoard(boardToJoin, tableStakes); // Fire the event for anyone listening PlayerAddedToBoard(boardIDToJoin, msg.sender); // If we have both players, start the game if (shouldStartGame) { // Start the game startBoardGame(boardToJoin, boardIDToJoin); } return boardIDToJoin; } /// @notice This function allows a player to cancel a match in the case they were waiting for an opponent for /// a long time but didn't find anyone and would want to get their deposit of table stakes back. /// That player may cancel the game as long as no opponent was found and the deposit will be returned in full (though gas fees still apply). The player will also need to withdraw funds from the contract after this action. /// @param boardId The board to cancel function cancelMatch(uint boardId) external { // Get the player GoBoard storage board = allBoards[boardId]; // Make sure this player is on board require(isPlayerOnBoard(boardId, msg.sender)); // Make sure that the game hasn't started require(board.status == BoardStatus.WaitForOpponent); // Update the board status to cancel (which also triggers the revenue sharing function) updateBoardStatus(board, boardId, BoardStatus.Canceled); } /// @dev Gets the current player boards to present to the player as needed /// @param activeTurnsOnly We might want to highlight the boards where the player is expected to act /// @return an array of PAGE_SIZE with the number of boards found and the actual IDs function getPlayerBoardsIDs(bool activeTurnsOnly) public view returns (uint, uint[PAGE_SIZE]) { uint[PAGE_SIZE] memory playerBoardIDsToReturn; uint numberOfPlayerBoardsToReturn = 0; // Look at the recent boards until you find a player board for (uint currBoard = allBoards.length; currBoard > 0 && numberOfPlayerBoardsToReturn < PAGE_SIZE; currBoard--) { uint boardID = currBoard - 1; // We only care about boards the player is in if (isPlayerOnBoard(boardID, msg.sender)) { // Check if the player is the next to act, or just include it if it wasn't requested if (!activeTurnsOnly || getNextTurnColor(boardID) == getPlayerColor(boardID, msg.sender)) { playerBoardIDsToReturn[numberOfPlayerBoardsToReturn] = boardID; ++numberOfPlayerBoardsToReturn; } } } return (numberOfPlayerBoardsToReturn, playerBoardIDsToReturn); } /// @dev Creates a new board in case no board was found for a player to register /// @param tableStakesToUse The value used to set the board /// @return the id of new board (which is it's position in the allBoards array) function createNewGoBoard(uint tableStakesToUse) private returns(uint, GoBoard storage) { GoBoard memory newBoard = GoBoard({lastUpdate: now, isHonorableLoss: false, tableStakes: tableStakesToUse, boardBalance: 0, blackAddress: 0, whiteAddress: 0, blackPeriodsRemaining: PLAYER_START_PERIODS, whitePeriodsRemaining: PLAYER_START_PERIODS, nextTurnColor: PlayerColor.None, status:BoardStatus.WaitForOpponent, didPassPrevTurn:false}); uint boardId = allBoards.push(newBoard) - 1; return (boardId, allBoards[boardId]); } /// @dev Creates a new board in case no board was found for a player to register /// @param tableStakes The value used to set the board /// @return the id of new board (which is it's position in the allBoards array) function getOrCreateWaitingBoard(uint tableStakes) private returns(uint, GoBoard storage) { bool wasFound = false; uint selectedBoardId = 0; GoBoard storage board; // First, try to find a board that has an empty spot and the right table stakes for (uint i = allBoards.length; i > 0 && !wasFound; --i) { board = allBoards[i - 1]; // Make sure this board is already waiting and it's stakes are the same if (board.tableStakes == tableStakes) { // If this board is waiting for an opponent if (board.status == BoardStatus.WaitForOpponent) { // Awesome, we have the board and we are done wasFound = true; selectedBoardId = i - 1; } // If we found the rights stakes board but it isn't waiting for player we won't have another empty board. // We need to create a new one break; } } // Create a new board if we couldn't find one if (!wasFound) { (selectedBoardId, board) = createNewGoBoard(tableStakes); } return (selectedBoardId, board); } /// @dev Starts the game and sets everything up for the match /// @param board The board to update with the starting data /// @param boardId The board's Id function startBoardGame(GoBoard storage board, uint boardId) private { // Make sure both players are present require(board.blackAddress != 0 && board.whiteAddress != 0); // The black is always the first player in GO board.nextTurnColor = PlayerColor.Black; // Save the game start time and set the game status to in progress updateBoardStatus(board, boardId, BoardStatus.InProgress); } /// @dev Handles the registration of a player to a board /// @param board The board to update with the starting data /// @param paidAmount The amount the player paid to start playing (will be added to the board balance) /// @return true if the game should be started function addPlayerToBoard(GoBoard storage board, uint paidAmount) private returns(bool) { // Make suew we are still waitinf for opponent (otherwise we can't add players) bool shouldStartTheGame = false; require(board.status == BoardStatus.WaitForOpponent); // Check that the player isn't already on the board, otherwise they would pay twice for a single board... :( require(!isPlayerOnBoard(board, msg.sender)); // We always add the black player first as they created the board if (board.blackAddress == 0) { board.blackAddress = msg.sender; // If we have a black player, add the white player } else if (board.whiteAddress == 0) { board.whiteAddress = msg.sender; // Once the white player has been added, we can start the match shouldStartTheGame = true; // If both addresses are occuipied and we got here, it's a problem } else { revert(); } // Credit the board with what we know board.boardBalance += paidAmount; return shouldStartTheGame; } /// @dev Helper function to caclulate how much time a player used since now /// @param lastUpdate the timestamp of last update of the board /// @return the number of periods used for this time function getTimePeriodsUsed(uint lastUpdate) private view returns(uint8) { return uint8(now.sub(lastUpdate).div(PLAYER_TURN_SINGLE_PERIOD)); } /// @notice Convinience function to help present how much time a player has. /// @param boardId the board to check. /// @param color the color of the player to check. /// @return The number of time periods the player has, the number of seconds per each period and the total number of seconds for convinience. function getPlayerRemainingTime(uint boardId, PlayerColor color) view external returns (uint, uint, uint) { GoBoard storage board = allBoards[boardId]; // Always verify we can act require(board.status == BoardStatus.InProgress); // Get the total remaining time: uint timePeriods = getPlayerTimePeriods(board, color); uint totalTimeRemaining = timePeriods * PLAYER_TURN_SINGLE_PERIOD; // If this is the acting player if (color == board.nextTurnColor) { // Calc time periods for player uint timePeriodsUsed = getTimePeriodsUsed(board.lastUpdate); if (timePeriods > timePeriodsUsed) { timePeriods -= timePeriodsUsed; } else { timePeriods = 0; } // Calc total time remaining for player uint timeUsed = (now - board.lastUpdate); // Safely reduce the time used if (totalTimeRemaining > timeUsed) { totalTimeRemaining -= timeUsed; // A player can't have less than zero time to act } else { totalTimeRemaining = 0; } } return (timePeriods, PLAYER_TURN_SINGLE_PERIOD, totalTimeRemaining); } /// @dev After a player acted we might need to reduce the number of remaining time periods. /// @param board The board the player acted upon. /// @param color the color of the player that acted. /// @param timePeriodsUsed the number of periods the player used. function updatePlayerTimePeriods(GoBoard storage board, PlayerColor color, uint8 timePeriodsUsed) internal { // Reduce from the black player if (color == PlayerColor.Black) { // The player can't have less than 0 periods remaining board.blackPeriodsRemaining = board.blackPeriodsRemaining > timePeriodsUsed ? board.blackPeriodsRemaining - timePeriodsUsed : 0; // Reduce from the white player } else if (color == PlayerColor.White) { // The player can't have less than 0 periods remaining board.whitePeriodsRemaining = board.whitePeriodsRemaining > timePeriodsUsed ? board.whitePeriodsRemaining - timePeriodsUsed : 0; // We are not supposed to get here } else { revert(); } } /// @dev Helper function to access the time periods of a player in a board. /// @param board The board to check. /// @param color the color of the player to check. /// @return The number of time periods remaining for this player function getPlayerTimePeriods(GoBoard storage board, PlayerColor color) internal view returns (uint8) { // For the black player if (color == PlayerColor.Black) { return board.blackPeriodsRemaining; // For the white player } else if (color == PlayerColor.White) { return board.whitePeriodsRemaining; // We are not supposed to get here } else { revert(); } } /// @notice The main function to split game revenues, this is triggered only by changing the game's state /// to one of the ending game states. /// We make sure this board has a balance and that it's only running once a board game has ended /// We used numbers for easier read through as this function is critical for the revenue sharing model /// @param board The board the credit will come from. function creditBoardGameRevenues(GoBoard storage board) private boardGameEnded(board) boardNotPaid(board) { // Get the shares from the globals uint updatedHostShare = HOST_SHARE; uint updatedLoserShare = 0; // Start accumulating funds for each participant and EthernalGo's CFO uint amountBlack = 0; uint amountWhite = 0; uint amountCFO = 0; uint fullAmount = 1000; // Incentivize resigns and quick end-games for the loser if (board.status == BoardStatus.BlackWin || board.status == BoardStatus.WhiteWin) { // In case the game ended honorably (not by time out), the loser will get credit (from the CFO's share) if (board.isHonorableLoss) { // Reduce the credit from the CFO updatedHostShare = HOST_SHARE - HONORABLE_LOSS_BONUS; // Add to the loser share updatedLoserShare = HONORABLE_LOSS_BONUS; } // If black won if (board.status == BoardStatus.BlackWin) { // Black should get the winner share amountBlack = board.boardBalance.mul(WINNER_SHARE).div(fullAmount); // White player should get the updated loser share (with or without the bonus) amountWhite = board.boardBalance.mul(updatedLoserShare).div(fullAmount); } // If white won if (board.status == BoardStatus.WhiteWin) { // White should get the winner share amountWhite = board.boardBalance.mul(WINNER_SHARE).div(fullAmount); // Black should get the updated loser share (with or without the bonus) amountBlack = board.boardBalance.mul(updatedLoserShare).div(fullAmount); } // The CFO should get the updates share if the game ended as expected amountCFO = board.boardBalance.mul(updatedHostShare).div(fullAmount); } // If the match ended in a draw or it was cancelled if (board.status == BoardStatus.Draw || board.status == BoardStatus.Canceled) { // The CFO is not taking a share from draw or a cancelled match amountCFO = 0; // If the white player was on board, we should split the balance in half if (board.whiteAddress != 0) { // Each player gets half of the balance amountBlack = board.boardBalance.div(2); amountWhite = board.boardBalance.div(2); // If there was only the black player, they should get the entire balance } else { amountBlack = board.boardBalance; } } // Make sure we are going to split the entire amount and nothing gets left behind assert(amountBlack + amountWhite + amountCFO == board.boardBalance); // Reset the balance board.boardBalance = 0; // Async sends to the participants (this means each participant will be required to withdraw funds) asyncSend(board.blackAddress, amountBlack); asyncSend(board.whiteAddress, amountWhite); asyncSend(CFO, amountCFO); } /// @dev withdraw accumulated balance, called by payee. function withdrawPayments() public { // Call Zeppelin's withdrawPayments super.withdrawPayments(); // Send an event PlayerWithdrawnBalance(msg.sender); } } // File: contracts/GoGameLogic.sol /// @title The actual game logic for EthernalGo - setting stones, capturing, etc. /// @author https://www.EthernalGo.com contract GoGameLogic is GoBoardMetaDetails { /// @dev The StoneAddedToBoard event is fired when a new stone is added to the board, /// and includes the board Id, stone color, row & column. This event will fire even if it was a suicide stone. event StoneAddedToBoard(uint boardId, PlayerColor color, uint8 row, uint8 col); /// @dev The PlayerPassedTurn event is fired when a player passes turn /// and includes the board Id, color. event PlayerPassedTurn(uint boardId, PlayerColor color); /// @dev Updating the player's time periods left, according to the current time - board last update time. /// If the player does not have enough time and chose to act, the game will end and the player will lose. /// @param board is the relevant board. /// @param boardId is the board's Id. /// @param color is the color of the player we want to update. /// @return true if the player can continue playing, otherwise false. function updatePlayerTime(GoBoard storage board, uint boardId, PlayerColor color) private returns(bool) { // Verify that the board is in progress and that it's the current player require(board.status == BoardStatus.InProgress && board.nextTurnColor == color); // Calculate time periods used by the player uint timePeriodsUsed = uint(now.sub(board.lastUpdate).div(PLAYER_TURN_SINGLE_PERIOD)); // Subtract time periods if needed if (timePeriodsUsed > 0) { // Can't spend more than MAX_UINT8 updatePlayerTimePeriods(board, color, timePeriodsUsed > MAX_UINT8 ? MAX_UINT8 : uint8(timePeriodsUsed)); // The player losses when there aren't any time periods left if (getPlayerTimePeriods(board, color) == 0) { playerLost(board, boardId, color); return false; } } return true; } /// @notice Updates the board status according to the players score. /// Can only be called when the board is in a 'waitingToResolve' status. /// @param boardId is the board to check and update function checkVictoryByScore(uint boardId) external boardWaitingToResolve(boardId) { uint8 blackScore; uint8 whiteScore; // Get the players' score (blackScore, whiteScore) = calculateBoardScore(boardId); // Default to Draw BoardStatus status = BoardStatus.Draw; // If black's score is bigger than white's score, black is the winner if (blackScore > whiteScore) { status = BoardStatus.BlackWin; // If white's score is bigger, white is the winner } else if (whiteScore > blackScore) { status = BoardStatus.WhiteWin; } // Update the board's status updateBoardStatus(boardId, status); } /// @notice Performs a pass action on a psecific board, only by the current active color player. /// @param boardId is the board to perform pass on. function passTurn(uint boardId) external { // Get the board & player GoBoard storage board = allBoards[boardId]; PlayerColor activeColor = getPlayerColor(board, msg.sender); // Verify the player can act require(board.status == BoardStatus.InProgress && board.nextTurnColor == activeColor); // Check if this player can act if (updatePlayerTime(board, boardId, activeColor)) { // If it's the second straight pass, the game is over if (board.didPassPrevTurn) { // Finishing the game like this is considered honorable board.isHonorableLoss = true; // On second pass, the board status changes to 'WaitingToResolve' updateBoardStatus(board, boardId, BoardStatus.WaitingToResolve); // If it's the first pass, we can simply continue } else { // Move to the next player, flag that it was a pass action nextTurn(board); board.didPassPrevTurn = true; // Notify the player passed turn PlayerPassedTurn(boardId, activeColor); } } } /// @notice Resigns a player from a specific board, can get called by either player on the board. /// @param boardId is the board to resign from. function resignFromMatch(uint boardId) external { // Get the board, make sure it's in progress GoBoard storage board = allBoards[boardId]; require(board.status == BoardStatus.InProgress); // Get the sender's color PlayerColor activeColor = getPlayerColor(board, msg.sender); // Finishing the game like this is considered honorable board.isHonorableLoss = true; // Set that color as the losing player playerLost(board, boardId, activeColor); } /// @notice Claiming the current acting player on the board is out of time, thus losses the game. /// @param boardId is the board to claim it on. function claimActingPlayerOutOfTime(uint boardId) external { // Get the board, make sure it's in progress GoBoard storage board = allBoards[boardId]; require(board.status == BoardStatus.InProgress); // Get the acting player color PlayerColor actingPlayerColor = getNextTurnColor(boardId); // Calculate remaining allowed time for the acting player uint playerTimeRemaining = PLAYER_TURN_SINGLE_PERIOD * getPlayerTimePeriods(board, actingPlayerColor); // If the player doesn't have enough time left, the player losses if (playerTimeRemaining < now - board.lastUpdate) { playerLost(board, boardId, actingPlayerColor); } } /// @dev Update a board status with a losing color /// @param board is the board to update. /// @param boardId is the board's Id. /// @param color is the losing player's color. function playerLost(GoBoard storage board, uint boardId, PlayerColor color) private { // If black is the losing color, white wins if (color == PlayerColor.Black) { updateBoardStatus(board, boardId, BoardStatus.WhiteWin); // If white is the losing color, black wins } else if (color == PlayerColor.White) { updateBoardStatus(board, boardId, BoardStatus.BlackWin); // There's an error, revert } else { revert(); } } /// @dev Internally used to move to the next turn, by switching sides and updating the board last update time. /// @param board is the board to update. function nextTurn(GoBoard storage board) private { // Switch sides board.nextTurnColor = board.nextTurnColor == PlayerColor.Black ? PlayerColor.White : PlayerColor.Black; // Last update time board.lastUpdate = now; } /// @notice Adding a stone to a specific board and position (row & col). /// Requires the board to be in progress, that the caller is the acting player, /// and that the spot on the board is empty. /// @param boardId is the board to add the stone to. /// @param row is the row for the new stone. /// @param col is the column for the new stone. function addStoneToBoard(uint boardId, uint8 row, uint8 col) external { // Get the board & sender's color GoBoard storage board = allBoards[boardId]; PlayerColor activeColor = getPlayerColor(board, msg.sender); // Verify the player can act require(board.status == BoardStatus.InProgress && board.nextTurnColor == activeColor); // Calculate the position uint8 position = row * BOARD_ROW_SIZE + col; // Check that it's an empty spot require(board.positionToColor[position] == 0); // Update the player timeout (if the player doesn't have time left, discontinue) if (updatePlayerTime(board, boardId, activeColor)) { // Set the stone on the board board.positionToColor[position] = uint8(activeColor); // Run capture / suidice logic updateCaptures(board, position, uint8(activeColor)); // Next turn logic nextTurn(board); // Clear the pass flag if (board.didPassPrevTurn) { board.didPassPrevTurn = false; } // Fire the event StoneAddedToBoard(boardId, activeColor, row, col); } } /// @notice Returns a board's row details, specifies which color occupies which cell in that row. /// @dev It returns a row and not the entire board because some nodes might fail to return arrays larger than ~50. /// @param boardId is the board to inquire. /// @param row is the row to get details on. /// @return an array that contains the colors occupying each cell in that row. function getBoardRowDetails(uint boardId, uint8 row) external view returns (uint8[BOARD_ROW_SIZE]) { // The array to return uint8[BOARD_ROW_SIZE] memory rowToReturn; // For all columns, calculate the position and get the current status for (uint8 col = 0; col < BOARD_ROW_SIZE; col++) { uint8 position = row * BOARD_ROW_SIZE + col; rowToReturn[col] = allBoards[boardId].positionToColor[position]; } // Return the array return (rowToReturn); } /// @notice Returns the current color of a specific position in a board. /// @param boardId is the board to inquire. /// @param row is part of the position to get details on. /// @param col is part of the position to get details on. /// @return the color occupying that position. function getBoardSingleSpaceDetails(uint boardId, uint8 row, uint8 col) external view returns (uint8) { uint8 position = row * BOARD_ROW_SIZE + col; return allBoards[boardId].positionToColor[position]; } /// @dev Calcultes whether a position captures an enemy group, or whether it's a suicide. /// Updates the board accoridngly (clears captured groups, or the suiciding stone). /// @param board the board to check and update /// @param position the position of the new stone /// @param positionColor the color of the new stone (this param is sent to spare another reading op) function updateCaptures(GoBoard storage board, uint8 position, uint8 positionColor) private { // Group positions, used later uint8[BOARD_SIZE] memory group; // Is group captured, or free bool isGroupCaptured; // In order to save gas, we check suicide only if the position is fully surrounded and doesn't capture enemy groups bool shouldCheckSuicide = true; // Get the position's adjacent cells uint8[MAX_ADJACENT_CELLS] memory adjacentArray = getAdjacentCells(position); // Run as long as there an adjacent cell, or until we reach the end of the array for (uint8 currAdjacentIndex = 0; currAdjacentIndex < MAX_ADJACENT_CELLS && adjacentArray[currAdjacentIndex] < MAX_UINT8; currAdjacentIndex++) { // Get the adjacent cell's color uint8 currColor = board.positionToColor[adjacentArray[currAdjacentIndex]]; // If the enemy's color if (currColor != 0 && currColor != positionColor) { // Get the group's info (group, isGroupCaptured) = getGroup(board, adjacentArray[currAdjacentIndex], currColor); // Captured a group if (isGroupCaptured) { // Clear the group from the board for (uint8 currGroupIndex = 0; currGroupIndex < BOARD_SIZE && group[currGroupIndex] < MAX_UINT8; currGroupIndex++) { board.positionToColor[group[currGroupIndex]] = 0; } // Shouldn't check suicide shouldCheckSuicide = false; } // There's an empty adjacent cell } else if (currColor == 0) { // Shouldn't check suicide shouldCheckSuicide = false; } } // Detect suicide if needed if (shouldCheckSuicide) { // Get the new stone's surrounding group (group, isGroupCaptured) = getGroup(board, position, positionColor); // If the group is captured, it's a suicide move, remove it if (isGroupCaptured) { // Clear added stone board.positionToColor[position] = 0; } } } /// @dev Internally used to set a flag in a shrinked board array (used to save gas costs). /// @param visited the array to update. /// @param position the position on the board we want to flag. /// @param flag the flag we want to set (either 1 or 2). function setFlag(uint8[SHRINKED_BOARD_SIZE] visited, uint8 position, uint8 flag) private pure { visited[position / 4] |= flag << ((position % 4) * 2); } /// @dev Internally used to check whether a flag in a shrinked board array is set. /// @param visited the array to check. /// @param position the position on the board we want to check. /// @param flag the flag we want to check (either 1 or 2). /// @return true if that flag is set, false otherwise. function isFlagSet(uint8[SHRINKED_BOARD_SIZE] visited, uint8 position, uint8 flag) private pure returns (bool) { return (visited[position / 4] & (flag << ((position % 4) * 2)) > 0); } // Get group visited flags uint8 constant FLAG_POSITION_WAS_IN_STACK = 1; uint8 constant FLAG_DID_VISIT_POSITION = 2; /// @dev Gets a group starting from the position & color sent. In order for a stone to be part of the group, /// it must match the original stone's color, and be connected to it - either directly, or through adjacent cells. /// A group is captured if there aren't any empty cells around it. /// The function supports both returning colored groups - white/black, and empty groups (for that case, isGroupCaptured isn't relevant). /// @param board the board to check and update /// @param position the position of the starting stone /// @param positionColor the color of the starting stone (this param is sent to spare another reading op) /// @return an array that contains the positions of the group, /// a boolean that specifies whether the group is captured or not. /// In order to save gas, if a group isn't captured, the array might not contain the enitre group. function getGroup(GoBoard storage board, uint8 position, uint8 positionColor) private view returns (uint8[BOARD_SIZE], bool isGroupCaptured) { // The return array, and its size uint8[BOARD_SIZE] memory groupPositions; uint8 groupSize = 0; // Flagging visited locations uint8[SHRINKED_BOARD_SIZE] memory visited; // Stack of waiting positions, the first position to check is the sent position uint8[BOARD_SIZE] memory stack; stack[0] = position; uint8 stackSize = 1; // That position was added to the stack setFlag(visited, position, FLAG_POSITION_WAS_IN_STACK); // Run as long as there are positions in the stack while (stackSize > 0) { // Take the last position and clear it position = stack[--stackSize]; stack[stackSize] = 0; // Only if we didn't visit that stone before if (!isFlagSet(visited, position, FLAG_DID_VISIT_POSITION)) { // Set the flag so we won't visit it again setFlag(visited, position, FLAG_DID_VISIT_POSITION); // Add that position to the return value groupPositions[groupSize++] = position; // Get that position adjacent cells uint8[MAX_ADJACENT_CELLS] memory adjacentArray = getAdjacentCells(position); // Run over the adjacent cells for (uint8 currAdjacentIndex = 0; currAdjacentIndex < MAX_ADJACENT_CELLS && adjacentArray[currAdjacentIndex] < MAX_UINT8; currAdjacentIndex++) { // Get the current adjacent cell color uint8 currColor = board.positionToColor[adjacentArray[currAdjacentIndex]]; // If it's the same color as the original position color if (currColor == positionColor) { // Add that position to the stack if (!isFlagSet(visited, adjacentArray[currAdjacentIndex], FLAG_POSITION_WAS_IN_STACK)) { stack[stackSize++] = adjacentArray[currAdjacentIndex]; setFlag(visited, adjacentArray[currAdjacentIndex], FLAG_POSITION_WAS_IN_STACK); } // If that position is empty, the group isn't captured, no need to continue running } else if (currColor == 0) { return (groupPositions, false); } } } } // Flag the end of the group array only if needed if (groupSize < BOARD_SIZE) { groupPositions[groupSize] = MAX_UINT8; } // The group is captured, return it return (groupPositions, true); } /// The max number of adjacent cells is 4 uint8 constant MAX_ADJACENT_CELLS = 4; /// @dev returns the adjacent positions for a given position. /// @param position to get its adjacents. /// @return the adjacent positions array, filled with MAX_INT8 in case there aren't 4 adjacent positions. function getAdjacentCells(uint8 position) private pure returns (uint8[MAX_ADJACENT_CELLS]) { // Init the return array and current index uint8[MAX_ADJACENT_CELLS] memory returnCells = [MAX_UINT8, MAX_UINT8, MAX_UINT8, MAX_UINT8]; uint8 adjacentCellsIndex = 0; // Set the up position, if relevant if (position / BOARD_ROW_SIZE > 0) { returnCells[adjacentCellsIndex++] = position - BOARD_ROW_SIZE; } // Set the down position, if relevant if (position / BOARD_ROW_SIZE < BOARD_ROW_SIZE - 1) { returnCells[adjacentCellsIndex++] = position + BOARD_ROW_SIZE; } // Set the left position, if relevant if (position % BOARD_ROW_SIZE > 0) { returnCells[adjacentCellsIndex++] = position - 1; } // Set the right position, if relevant if (position % BOARD_ROW_SIZE < BOARD_ROW_SIZE - 1) { returnCells[adjacentCellsIndex++] = position + 1; } return returnCells; } /// @notice Calculates the board's score, using area scoring. /// @param boardId the board to calculate the score for. /// @return blackScore & whiteScore, the players' scores. function calculateBoardScore(uint boardId) public view returns (uint8 blackScore, uint8 whiteScore) { GoBoard storage board = allBoards[boardId]; uint8[BOARD_SIZE] memory boardEmptyGroups; uint8 maxEmptyGroupId; (boardEmptyGroups, maxEmptyGroupId) = getBoardEmptyGroups(board); uint8[BOARD_SIZE] memory groupsSize; uint8[BOARD_SIZE] memory groupsState; blackScore = 0; whiteScore = 0; // Count stones and find empty territories for (uint8 position = 0; position < BOARD_SIZE; position++) { if (PlayerColor(board.positionToColor[position]) == PlayerColor.Black) { blackScore++; } else if (PlayerColor(board.positionToColor[position]) == PlayerColor.White) { whiteScore++; } else { uint8 groupId = boardEmptyGroups[position]; groupsSize[groupId]++; // Checking is needed only if we didn't find the group is adjacent to the two colors already if ((groupsState[groupId] & uint8(PlayerColor.Black) == 0) || (groupsState[groupId] & uint8(PlayerColor.White) == 0)) { uint8[MAX_ADJACENT_CELLS] memory adjacentArray = getAdjacentCells(position); // Check adjacent cells to mark the group's bounderies for (uint8 currAdjacentIndex = 0; currAdjacentIndex < MAX_ADJACENT_CELLS && adjacentArray[currAdjacentIndex] < MAX_UINT8; currAdjacentIndex++) { // Check if the group has a black boundry if ((PlayerColor(board.positionToColor[adjacentArray[currAdjacentIndex]]) == PlayerColor.Black) && (groupsState[groupId] & uint8(PlayerColor.Black) == 0)) { groupsState[groupId] |= uint8(PlayerColor.Black); // Check if the group has a white boundry } else if ((PlayerColor(board.positionToColor[adjacentArray[currAdjacentIndex]]) == PlayerColor.White) && (groupsState[groupId] & uint8(PlayerColor.White) == 0)) { groupsState[groupId] |= uint8(PlayerColor.White); } } } } } // Add territories size to the relevant player for (uint8 currGroupId = 1; currGroupId < maxEmptyGroupId; currGroupId++) { // Check if it's a black territory if ((groupsState[currGroupId] & uint8(PlayerColor.Black) > 0) && (groupsState[currGroupId] & uint8(PlayerColor.White) == 0)) { blackScore += groupsSize[currGroupId]; // Check if it's a white territory } else if ((groupsState[currGroupId] & uint8(PlayerColor.White) > 0) && (groupsState[currGroupId] & uint8(PlayerColor.Black) == 0)) { whiteScore += groupsSize[currGroupId]; } } return (blackScore, whiteScore); } /// @dev IDs empty groups on the board. /// @param board the board to map. /// @return an array that contains the mapped empty group ids, and the max empty group id function getBoardEmptyGroups(GoBoard storage board) private view returns (uint8[BOARD_SIZE], uint8) { uint8[BOARD_SIZE] memory boardEmptyGroups; uint8 nextGroupId = 1; for (uint8 position = 0; position < BOARD_SIZE; position++) { PlayerColor currPositionColor = PlayerColor(board.positionToColor[position]); if ((currPositionColor == PlayerColor.None) && (boardEmptyGroups[position] == 0)) { uint8[BOARD_SIZE] memory emptyGroup; bool isGroupCaptured; (emptyGroup, isGroupCaptured) = getGroup(board, position, 0); for (uint8 currGroupIndex = 0; currGroupIndex < BOARD_SIZE && emptyGroup[currGroupIndex] < MAX_UINT8; currGroupIndex++) { boardEmptyGroups[emptyGroup[currGroupIndex]] = nextGroupId; } nextGroupId++; } } return (boardEmptyGroups, nextGroupId); } }
withdraw accumulated balance, called by payee. Call Zeppelin's withdrawPayments Send an event
function withdrawPayments() public { super.withdrawPayments(); PlayerWithdrawnBalance(msg.sender); }
941,539
// Copyright (C) 2021 Argent Labs Ltd. <https://argent.xyz> // 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/>. // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.3; import "./IAuthoriser.sol"; import "./dapp/IFilter.sol"; contract DappRegistry is IAuthoriser { // The timelock period uint64 public timelockPeriod; // The new timelock period uint64 public newTimelockPeriod; // Time at which the new timelock becomes effective uint64 public timelockPeriodChangeAfter; // bit vector of enabled registry ids for each wallet mapping (address => bytes32) public enabledRegistryIds; // [wallet] => [bit vector of 256 registry ids] // authorised dapps and their filters for each registry id mapping (uint8 => mapping (address => bytes32)) public authorisations; // [registryId] => [dapp] => [{filter:160}{validAfter:64}] // pending authorised dapps and their filters for each registry id mapping (uint8 => mapping (address => bytes32)) public pendingFilterUpdates; // [registryId] => [dapp] => [{filter:160}{validAfter:64}] // owners for each registry id mapping (uint8 => address) public registryOwners; // [registryId] => [owner] event RegistryCreated(uint8 registryId, address registryOwner); event OwnerChanged(uint8 registryId, address newRegistryOwner); event TimelockChangeRequested(uint64 newTimelockPeriod); event TimelockChanged(uint64 newTimelockPeriod); event FilterUpdated(uint8 indexed registryId, address dapp, address filter, uint256 validAfter); event FilterUpdateRequested(uint8 indexed registryId, address dapp, address filter, uint256 validAfter); event DappAdded(uint8 indexed registryId, address dapp, address filter, uint256 validAfter); event DappRemoved(uint8 indexed registryId, address dapp); event ToggledRegistry(address indexed sender, uint8 registryId, bool enabled); modifier onlyOwner(uint8 _registryId) { validateOwner(_registryId); _; } constructor(uint64 _timelockPeriod) { // set the timelock period timelockPeriod = _timelockPeriod; // set the owner of the Argent Registry (registryId = 0) registryOwners[0] = msg.sender; emit RegistryCreated(0, msg.sender); emit TimelockChanged(_timelockPeriod); } /********* Wallet-centered functions *************/ /** * @notice Returns whether a registry is enabled for a wallet * @param _wallet The wallet * @param _registryId The registry id */ function isEnabledRegistry(address _wallet, uint8 _registryId) external view returns (bool isEnabled) { uint registries = uint(enabledRegistryIds[_wallet]); return (((registries >> _registryId) & 1) > 0) /* "is bit set for regId?" */ == (_registryId > 0) /* "not Argent registry?" */; } /** * @notice Returns whether a (_spender, _to, _data) call is authorised for a wallet * @param _wallet The wallet * @param _spender The spender of the tokens for token approvals, or the target of the transaction otherwise * @param _to The target of the transaction * @param _data The calldata of the transaction */ function isAuthorised(address _wallet, address _spender, address _to, bytes calldata _data) public view override returns (bool) { uint registries = uint(enabledRegistryIds[_wallet]); // Check Argent Default Registry first. It is enabled by default, implying that a zero // at position 0 of the `registries` bit vector means that the Argent Registry is enabled) for(uint registryId = 0; registryId == 0 || (registries >> registryId) > 0; registryId++) { bool isEnabled = (((registries >> registryId) & 1) > 0) /* "is bit set for regId?" */ == (registryId > 0) /* "not Argent registry?" */; if(isEnabled) { // if registryId is enabled uint auth = uint(authorisations[uint8(registryId)][_spender]); uint validAfter = auth & 0xffffffffffffffff; if (0 < validAfter && validAfter <= block.timestamp) { // if the current time is greater than the validity time address filter = address(uint160(auth >> 64)); if(filter == address(0) || IFilter(filter).isValid(_wallet, _spender, _to, _data)) { return true; } } } } return false; } /** * @notice Returns whether a collection of (_spender, _to, _data) calls are authorised for a wallet * @param _wallet The wallet * @param _spenders The spenders of the tokens for token approvals, or the targets of the transaction otherwise * @param _to The targets of the transaction * @param _data The calldata of the transaction */ function areAuthorised( address _wallet, address[] calldata _spenders, address[] calldata _to, bytes[] calldata _data ) external view override returns (bool) { for(uint i = 0; i < _spenders.length; i++) { if(!isAuthorised(_wallet, _spenders[i], _to[i], _data[i])) { return false; } } return true; } /** * @notice Allows a wallet to decide whether _registryId should be part of the list of enabled registries for that wallet * @param _registryId The id of the registry to enable/disable * @param _enabled Whether the registry should be enabled (true) or disabled (false) */ function toggleRegistry(uint8 _registryId, bool _enabled) external { require(registryOwners[_registryId] != address(0), "DR: unknown registry"); uint registries = uint(enabledRegistryIds[msg.sender]); bool current = (((registries >> _registryId) & 1) > 0) /* "is bit set for regId?" */ == (_registryId > 0) /* "not Argent registry?" */; if(current != _enabled) { enabledRegistryIds[msg.sender] = bytes32(registries ^ (uint(1) << _registryId)); // toggle [_registryId]^th bit emit ToggledRegistry(msg.sender, _registryId, _enabled); } } /************** Management of registry list *****************/ /** * @notice Create a new registry. Only the owner of the Argent registry (i.e. the registry with id 0 -- hence the use of `onlyOwner(0)`) * can create a new registry. * @param _registryId The id of the registry to create * @param _registryOwner The owner of that new registry */ function createRegistry(uint8 _registryId, address _registryOwner) external onlyOwner(0) { require(_registryOwner != address(0), "DR: registry owner is 0"); require(registryOwners[_registryId] == address(0), "DR: duplicate registry"); registryOwners[_registryId] = _registryOwner; emit RegistryCreated(_registryId, _registryOwner); } // Note: removeRegistry is not supported because that would allow the owner to replace registries that // have already been enabled by users with a new (potentially maliciously populated) registry /** * @notice Lets a registry owner change the owner of the registry. * @param _registryId The id of the registry * @param _newRegistryOwner The new owner of the registry */ function changeOwner(uint8 _registryId, address _newRegistryOwner) external onlyOwner(_registryId) { require(_newRegistryOwner != address(0), "DR: new registry owner is 0"); registryOwners[_registryId] = _newRegistryOwner; emit OwnerChanged(_registryId, _newRegistryOwner); } /** * @notice Request a change of the timelock value. Only the owner of the Argent registry (i.e. the registry with id 0 -- * hence the use of `onlyOwner(0)`) can perform that action. This action can be confirmed after the (old) timelock period. * @param _newTimelockPeriod The new timelock period */ function requestTimelockChange(uint64 _newTimelockPeriod) external onlyOwner(0) { newTimelockPeriod = _newTimelockPeriod; timelockPeriodChangeAfter = uint64(block.timestamp) + timelockPeriod; emit TimelockChangeRequested(_newTimelockPeriod); } /** * @notice Confirm a change of the timelock value requested by `requestTimelockChange()`. */ function confirmTimelockChange() external { uint64 newPeriod = newTimelockPeriod; require(timelockPeriodChangeAfter > 0 && timelockPeriodChangeAfter <= block.timestamp, "DR: can't (yet) change timelock"); timelockPeriod = newPeriod; newTimelockPeriod = 0; timelockPeriodChangeAfter = 0; emit TimelockChanged(newPeriod); } /************** Management of registries' content *****************/ /** * @notice Returns the (filter, validAfter) tuple recorded for a dapp in a given registry. * `filter` is the authorisation filter stored for the dapp (if any) and `validAfter` is the * timestamp after which the filter becomes active. * @param _registryId The registry id * @param _dapp The dapp */ function getAuthorisation(uint8 _registryId, address _dapp) external view returns (address filter, uint64 validAfter) { uint auth = uint(authorisations[_registryId][_dapp]); filter = address(uint160(auth >> 64)); validAfter = uint64(auth & 0xffffffffffffffff); } /** * @notice Add a new dapp to the registry with an optional filter * @param _registryId The id of the registry to modify * @param _dapp The address of the dapp contract to authorise. * @param _filter The address of the filter contract to use, if any. */ function addDapp(uint8 _registryId, address _dapp, address _filter) external onlyOwner(_registryId) { require(authorisations[_registryId][_dapp] == bytes32(0), "DR: dapp already added"); uint validAfter = block.timestamp + timelockPeriod; // Store the new authorisation as {filter:160}{validAfter:64}. authorisations[_registryId][_dapp] = bytes32((uint(uint160(_filter)) << 64) | validAfter); emit DappAdded(_registryId, _dapp, _filter, validAfter); } /** * @notice Deauthorise a dapp in a registry * @param _registryId The id of the registry to modify * @param _dapp The address of the dapp contract to deauthorise. */ function removeDapp(uint8 _registryId, address _dapp) external onlyOwner(_registryId) { require(authorisations[_registryId][_dapp] != bytes32(0), "DR: unknown dapp"); delete authorisations[_registryId][_dapp]; delete pendingFilterUpdates[_registryId][_dapp]; emit DappRemoved(_registryId, _dapp); } /** * @notice Request to change an authorisation filter for a dapp that has previously been authorised. We cannot * immediately override the existing filter and need to store the new filter for a timelock period before being * able to change the filter. * @param _registryId The id of the registry to modify * @param _dapp The address of the dapp contract to authorise. * @param _filter The address of the new filter contract to use. */ function requestFilterUpdate(uint8 _registryId, address _dapp, address _filter) external onlyOwner(_registryId) { require(authorisations[_registryId][_dapp] != bytes32(0), "DR: unknown dapp"); uint validAfter = block.timestamp + timelockPeriod; // Store the future authorisation as {filter:160}{validAfter:64} pendingFilterUpdates[_registryId][_dapp] = bytes32((uint(uint160(_filter)) << 64) | validAfter); emit FilterUpdateRequested(_registryId, _dapp, _filter, validAfter); } /** * @notice Confirm the filter change requested by `requestFilterUpdate` * @param _registryId The id of the registry to modify * @param _dapp The address of the dapp contract to authorise. */ function confirmFilterUpdate(uint8 _registryId, address _dapp) external { uint newAuth = uint(pendingFilterUpdates[_registryId][_dapp]); require(newAuth > 0, "DR: no pending filter update"); uint validAfter = newAuth & 0xffffffffffffffff; require(validAfter <= block.timestamp, "DR: too early to confirm auth"); authorisations[_registryId][_dapp] = bytes32(newAuth); emit FilterUpdated(_registryId, _dapp, address(uint160(newAuth >> 64)), validAfter); delete pendingFilterUpdates[_registryId][_dapp]; } /******** Internal Functions ***********/ function validateOwner(uint8 _registryId) internal view { address owner = registryOwners[_registryId]; require(owner != address(0), "DR: unknown registry"); require(msg.sender == owner, "DR: sender != registry owner"); } } // Copyright (C) 2021 Argent Labs Ltd. <https://argent.xyz> // 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/>. // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.3; interface IAuthoriser { function isAuthorised(address _sender, address _spender, address _to, bytes calldata _data) external view returns (bool); function areAuthorised( address _spender, address[] calldata _spenders, address[] calldata _to, bytes[] calldata _data ) external view returns (bool); } // Copyright (C) 2021 Argent Labs Ltd. <https://argent.xyz> // 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/>. // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.3; interface IFilter { function isValid(address _wallet, address _spender, address _to, bytes calldata _data) external view returns (bool valid); }
Returns whether a collection of (_spender, _to, _data) calls are authorised for a wallet _wallet The wallet _spenders The spenders of the tokens for token approvals, or the targets of the transaction otherwise _to The targets of the transaction _data The calldata of the transaction/
{ function areAuthorised( address _wallet, address[] calldata _spenders, address[] calldata _to, bytes[] calldata _data ) external view override returns (bool) for(uint i = 0; i < _spenders.length; i++) { if(!isAuthorised(_wallet, _spenders[i], _to[i], _data[i])) { return false; } } return true; function areAuthorised( address _wallet, address[] calldata _spenders, address[] calldata _to, bytes[] calldata _data ) external view override returns (bool) for(uint i = 0; i < _spenders.length; i++) { if(!isAuthorised(_wallet, _spenders[i], _to[i], _data[i])) { return false; } } return true; }
481,794
// SPDX-License-Identifier: AGPL-3.0-only /* Bounty.sol - SKALE Manager Copyright (C) 2020-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./delegation/DelegationController.sol"; import "./delegation/PartialDifferences.sol"; import "./delegation/TimeHelpers.sol"; import "./delegation/ValidatorService.sol"; import "./ConstantsHolder.sol"; import "./Nodes.sol"; import "./Permissions.sol"; contract BountyV2 is Permissions { using PartialDifferences for PartialDifferences.Value; using PartialDifferences for PartialDifferences.Sequence; struct BountyHistory { uint month; uint bountyPaid; } uint public constant YEAR1_BOUNTY = 3850e5 * 1e18; uint public constant YEAR2_BOUNTY = 3465e5 * 1e18; uint public constant YEAR3_BOUNTY = 3080e5 * 1e18; uint public constant YEAR4_BOUNTY = 2695e5 * 1e18; uint public constant YEAR5_BOUNTY = 2310e5 * 1e18; uint public constant YEAR6_BOUNTY = 1925e5 * 1e18; uint public constant EPOCHS_PER_YEAR = 12; uint public constant SECONDS_PER_DAY = 24 * 60 * 60; uint public constant BOUNTY_WINDOW_SECONDS = 3 * SECONDS_PER_DAY; uint private _nextEpoch; uint private _epochPool; uint private _bountyWasPaidInCurrentEpoch; bool public bountyReduction; uint public nodeCreationWindowSeconds; PartialDifferences.Value private _effectiveDelegatedSum; // validatorId amount of nodes mapping (uint => uint) public nodesByValidator; // deprecated // validatorId => BountyHistory mapping (uint => BountyHistory) private _bountyHistory; function calculateBounty(uint nodeIndex) external allow("SkaleManager") returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); require( _getNextRewardTimestamp(nodeIndex, nodes, timeHelpers) <= now, "Transaction is sent too early" ); uint validatorId = nodes.getValidatorId(nodeIndex); if (nodesByValidator[validatorId] > 0) { delete nodesByValidator[validatorId]; } uint currentMonth = timeHelpers.getCurrentMonth(); _refillEpochPool(currentMonth, timeHelpers, constantsHolder); _prepareBountyHistory(validatorId, currentMonth); uint bounty = _calculateMaximumBountyAmount( _epochPool, _effectiveDelegatedSum.getAndUpdateValue(currentMonth), _bountyWasPaidInCurrentEpoch, nodeIndex, _bountyHistory[validatorId].bountyPaid, delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth), delegationController.getAndUpdateDelegatedToValidatorNow(validatorId), constantsHolder, nodes ); _bountyHistory[validatorId].bountyPaid = _bountyHistory[validatorId].bountyPaid.add(bounty); bounty = _reduceBounty( bounty, nodeIndex, nodes, constantsHolder ); _epochPool = _epochPool.sub(bounty); _bountyWasPaidInCurrentEpoch = _bountyWasPaidInCurrentEpoch.add(bounty); return bounty; } function enableBountyReduction() external onlyOwner { bountyReduction = true; } function disableBountyReduction() external onlyOwner { bountyReduction = false; } function setNodeCreationWindowSeconds(uint window) external allow("Nodes") { nodeCreationWindowSeconds = window; } function handleDelegationAdd( uint amount, uint month ) external allow("DelegationController") { _effectiveDelegatedSum.addToValue(amount, month); } function handleDelegationRemoving( uint amount, uint month ) external allow("DelegationController") { _effectiveDelegatedSum.subtractFromValue(amount, month); } function populate() external onlyOwner { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); TimeHelpers timeHelpers = TimeHelpers(contractManager.getTimeHelpers()); uint currentMonth = timeHelpers.getCurrentMonth(); // clean existing data for ( uint i = _effectiveDelegatedSum.firstUnprocessedMonth; i < _effectiveDelegatedSum.lastChangedMonth.add(1); ++i ) { delete _effectiveDelegatedSum.addDiff[i]; delete _effectiveDelegatedSum.subtractDiff[i]; } delete _effectiveDelegatedSum.value; delete _effectiveDelegatedSum.lastChangedMonth; _effectiveDelegatedSum.firstUnprocessedMonth = currentMonth; uint[] memory validators = validatorService.getTrustedValidators(); for (uint i = 0; i < validators.length; ++i) { uint validatorId = validators[i]; uint currentEffectiveDelegated = delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth); uint[] memory effectiveDelegated = delegationController.getEffectiveDelegatedValuesByValidator(validatorId); if (effectiveDelegated.length > 0) { assert(currentEffectiveDelegated == effectiveDelegated[0]); } uint added = 0; for (uint j = 0; j < effectiveDelegated.length; ++j) { if (effectiveDelegated[j] != added) { if (effectiveDelegated[j] > added) { _effectiveDelegatedSum.addToValue(effectiveDelegated[j].sub(added), currentMonth + j); } else { _effectiveDelegatedSum.subtractFromValue(added.sub(effectiveDelegated[j]), currentMonth + j); } added = effectiveDelegated[j]; } } delete effectiveDelegated; } } function estimateBounty(uint nodeIndex) external view returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); uint currentMonth = timeHelpers.getCurrentMonth(); uint validatorId = nodes.getValidatorId(nodeIndex); uint stagePoolSize; (stagePoolSize, ) = _getEpochPool(currentMonth, timeHelpers, constantsHolder); return _calculateMaximumBountyAmount( stagePoolSize, _effectiveDelegatedSum.getValue(currentMonth), _nextEpoch == currentMonth.add(1) ? _bountyWasPaidInCurrentEpoch : 0, nodeIndex, _getBountyPaid(validatorId, currentMonth), delegationController.getEffectiveDelegatedToValidator(validatorId, currentMonth), delegationController.getDelegatedToValidator(validatorId, currentMonth), constantsHolder, nodes ); } function getNextRewardTimestamp(uint nodeIndex) external view returns (uint) { return _getNextRewardTimestamp( nodeIndex, Nodes(contractManager.getContract("Nodes")), TimeHelpers(contractManager.getContract("TimeHelpers")) ); } function getEffectiveDelegatedSum() external view returns (uint[] memory) { return _effectiveDelegatedSum.getValues(); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); _nextEpoch = 0; _epochPool = 0; _bountyWasPaidInCurrentEpoch = 0; bountyReduction = false; nodeCreationWindowSeconds = 3 * SECONDS_PER_DAY; } // private function _calculateMaximumBountyAmount( uint epochPoolSize, uint effectiveDelegatedSum, uint bountyWasPaidInCurrentEpoch, uint nodeIndex, uint bountyPaidToTheValidator, uint effectiveDelegated, uint delegated, ConstantsHolder constantsHolder, Nodes nodes ) private view returns (uint) { if (nodes.isNodeLeft(nodeIndex)) { return 0; } if (now < constantsHolder.launchTimestamp()) { // network is not launched // bounty is turned off return 0; } if (effectiveDelegatedSum == 0) { // no delegations in the system return 0; } if (constantsHolder.msr() == 0) { return 0; } uint bounty = _calculateBountyShare( epochPoolSize.add(bountyWasPaidInCurrentEpoch), effectiveDelegated, effectiveDelegatedSum, delegated.div(constantsHolder.msr()), bountyPaidToTheValidator ); return bounty; } function _calculateBountyShare( uint monthBounty, uint effectiveDelegated, uint effectiveDelegatedSum, uint maxNodesAmount, uint paidToValidator ) private pure returns (uint) { if (maxNodesAmount > 0) { uint totalBountyShare = monthBounty .mul(effectiveDelegated) .div(effectiveDelegatedSum); return _min( totalBountyShare.div(maxNodesAmount), totalBountyShare.sub(paidToValidator) ); } else { return 0; } } function _getFirstEpoch(TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private view returns (uint) { return timeHelpers.timestampToMonth(constantsHolder.launchTimestamp()); } function _getEpochPool( uint currentMonth, TimeHelpers timeHelpers, ConstantsHolder constantsHolder ) private view returns (uint epochPool, uint nextEpoch) { epochPool = _epochPool; for (nextEpoch = _nextEpoch; nextEpoch <= currentMonth; ++nextEpoch) { epochPool = epochPool.add(_getEpochReward(nextEpoch, timeHelpers, constantsHolder)); } } function _refillEpochPool(uint currentMonth, TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private { uint epochPool; uint nextEpoch; (epochPool, nextEpoch) = _getEpochPool(currentMonth, timeHelpers, constantsHolder); if (_nextEpoch < nextEpoch) { (_epochPool, _nextEpoch) = (epochPool, nextEpoch); _bountyWasPaidInCurrentEpoch = 0; } } function _getEpochReward( uint epoch, TimeHelpers timeHelpers, ConstantsHolder constantsHolder ) private view returns (uint) { uint firstEpoch = _getFirstEpoch(timeHelpers, constantsHolder); if (epoch < firstEpoch) { return 0; } uint epochIndex = epoch.sub(firstEpoch); uint year = epochIndex.div(EPOCHS_PER_YEAR); if (year >= 6) { uint power = year.sub(6).div(3).add(1); if (power < 256) { return YEAR6_BOUNTY.div(2 ** power).div(EPOCHS_PER_YEAR); } else { return 0; } } else { uint[6] memory customBounties = [ YEAR1_BOUNTY, YEAR2_BOUNTY, YEAR3_BOUNTY, YEAR4_BOUNTY, YEAR5_BOUNTY, YEAR6_BOUNTY ]; return customBounties[year].div(EPOCHS_PER_YEAR); } } function _reduceBounty( uint bounty, uint nodeIndex, Nodes nodes, ConstantsHolder constants ) private returns (uint reducedBounty) { if (!bountyReduction) { return bounty; } reducedBounty = bounty; if (!nodes.checkPossibilityToMaintainNode(nodes.getValidatorId(nodeIndex), nodeIndex)) { reducedBounty = reducedBounty.div(constants.MSR_REDUCING_COEFFICIENT()); } } function _prepareBountyHistory(uint validatorId, uint currentMonth) private { if (_bountyHistory[validatorId].month < currentMonth) { _bountyHistory[validatorId].month = currentMonth; delete _bountyHistory[validatorId].bountyPaid; } } function _getBountyPaid(uint validatorId, uint month) private view returns (uint) { require(_bountyHistory[validatorId].month <= month, "Can't get bounty paid"); if (_bountyHistory[validatorId].month == month) { return _bountyHistory[validatorId].bountyPaid; } else { return 0; } } function _getNextRewardTimestamp(uint nodeIndex, Nodes nodes, TimeHelpers timeHelpers) private view returns (uint) { uint lastRewardTimestamp = nodes.getNodeLastRewardDate(nodeIndex); uint lastRewardMonth = timeHelpers.timestampToMonth(lastRewardTimestamp); uint lastRewardMonthStart = timeHelpers.monthToTimestamp(lastRewardMonth); uint timePassedAfterMonthStart = lastRewardTimestamp.sub(lastRewardMonthStart); uint currentMonth = timeHelpers.getCurrentMonth(); assert(lastRewardMonth <= currentMonth); if (lastRewardMonth == currentMonth) { uint nextMonthStart = timeHelpers.monthToTimestamp(currentMonth.add(1)); uint nextMonthFinish = timeHelpers.monthToTimestamp(lastRewardMonth.add(2)); if (lastRewardTimestamp < lastRewardMonthStart.add(nodeCreationWindowSeconds)) { return nextMonthStart.sub(BOUNTY_WINDOW_SECONDS); } else { return _min(nextMonthStart.add(timePassedAfterMonthStart), nextMonthFinish.sub(BOUNTY_WINDOW_SECONDS)); } } else if (lastRewardMonth.add(1) == currentMonth) { uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth); uint currentMonthFinish = timeHelpers.monthToTimestamp(currentMonth.add(1)); return _min( currentMonthStart.add(_max(timePassedAfterMonthStart, nodeCreationWindowSeconds)), currentMonthFinish.sub(BOUNTY_WINDOW_SECONDS) ); } else { uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth); return currentMonthStart.add(nodeCreationWindowSeconds); } } function _min(uint a, uint b) private pure returns (uint) { if (a < b) { return a; } else { return b; } } function _max(uint a, uint b) private pure returns (uint) { if (a < b) { return b; } else { return a; } } } // SPDX-License-Identifier: AGPL-3.0-only /* ConstantsHolder.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./Permissions.sol"; /** * @title ConstantsHolder * @dev Contract contains constants and common variables for the SKALE Network. */ contract ConstantsHolder is Permissions { // initial price for creating Node (100 SKL) uint public constant NODE_DEPOSIT = 100 * 1e18; uint8 public constant TOTAL_SPACE_ON_NODE = 128; // part of Node for Small Skale-chain (1/128 of Node) uint8 public constant SMALL_DIVISOR = 128; // part of Node for Medium Skale-chain (1/32 of Node) uint8 public constant MEDIUM_DIVISOR = 32; // part of Node for Large Skale-chain (full Node) uint8 public constant LARGE_DIVISOR = 1; // part of Node for Medium Test Skale-chain (1/4 of Node) uint8 public constant MEDIUM_TEST_DIVISOR = 4; // typically number of Nodes for Skale-chain (16 Nodes) uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16; // number of Nodes for Test Skale-chain (2 Nodes) uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2; // number of Nodes for Test Skale-chain (4 Nodes) uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4; // number of seconds in one year uint32 public constant SECONDS_TO_YEAR = 31622400; // initial number of monitors uint public constant NUMBER_OF_MONITORS = 24; uint public constant OPTIMAL_LOAD_PERCENTAGE = 80; uint public constant ADJUSTMENT_SPEED = 1000; uint public constant COOLDOWN_TIME = 60; uint public constant MIN_PRICE = 10**6; uint public constant MSR_REDUCING_COEFFICIENT = 2; uint public constant DOWNTIME_THRESHOLD_PART = 30; uint public constant BOUNTY_LOCKUP_MONTHS = 2; // MSR - Minimum staking requirement uint public msr; // Reward period - 30 days (each 30 days Node would be granted for bounty) uint32 public rewardPeriod; // Allowable latency - 150000 ms by default uint32 public allowableLatency; /** * Delta period - 1 hour (1 hour before Reward period became Monitors need * to send Verdicts and 1 hour after Reward period became Node need to come * and get Bounty) */ uint32 public deltaPeriod; /** * Check time - 2 minutes (every 2 minutes monitors should check metrics * from checked nodes) */ uint public checkTime; //Need to add minimal allowed parameters for verdicts uint public launchTimestamp; uint public rotationDelay; uint public proofOfUseLockUpPeriodDays; uint public proofOfUseDelegationPercentage; uint public limitValidatorsPerDelegator; uint256 public firstDelegationsMonth; // deprecated // date when schains will be allowed for creation uint public schainCreationTimeStamp; uint public minimalSchainLifetime; uint public complaintTimelimit; /** * @dev Allows the Owner to set new reward and delta periods * This function is only for tests. */ function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external onlyOwner { require( newRewardPeriod >= newDeltaPeriod && newRewardPeriod - newDeltaPeriod >= checkTime, "Incorrect Periods" ); rewardPeriod = newRewardPeriod; deltaPeriod = newDeltaPeriod; } /** * @dev Allows the Owner to set the new check time. * This function is only for tests. */ function setCheckTime(uint newCheckTime) external onlyOwner { require(rewardPeriod - deltaPeriod >= checkTime, "Incorrect check time"); checkTime = newCheckTime; } /** * @dev Allows the Owner to set the allowable latency in milliseconds. * This function is only for testing purposes. */ function setLatency(uint32 newAllowableLatency) external onlyOwner { allowableLatency = newAllowableLatency; } /** * @dev Allows the Owner to set the minimum stake requirement. */ function setMSR(uint newMSR) external onlyOwner { msr = newMSR; } /** * @dev Allows the Owner to set the launch timestamp. */ function setLaunchTimestamp(uint timestamp) external onlyOwner { require(now < launchTimestamp, "Cannot set network launch timestamp because network is already launched"); launchTimestamp = timestamp; } /** * @dev Allows the Owner to set the node rotation delay. */ function setRotationDelay(uint newDelay) external onlyOwner { rotationDelay = newDelay; } /** * @dev Allows the Owner to set the proof-of-use lockup period. */ function setProofOfUseLockUpPeriod(uint periodDays) external onlyOwner { proofOfUseLockUpPeriodDays = periodDays; } /** * @dev Allows the Owner to set the proof-of-use delegation percentage * requirement. */ function setProofOfUseDelegationPercentage(uint percentage) external onlyOwner { require(percentage <= 100, "Percentage value is incorrect"); proofOfUseDelegationPercentage = percentage; } /** * @dev Allows the Owner to set the maximum number of validators that a * single delegator can delegate to. */ function setLimitValidatorsPerDelegator(uint newLimit) external onlyOwner { limitValidatorsPerDelegator = newLimit; } function setSchainCreationTimeStamp(uint timestamp) external onlyOwner { schainCreationTimeStamp = timestamp; } function setMinimalSchainLifetime(uint lifetime) external onlyOwner { minimalSchainLifetime = lifetime; } function setComplaintTimelimit(uint timelimit) external onlyOwner { complaintTimelimit = timelimit; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); msr = 0; rewardPeriod = 2592000; allowableLatency = 150000; deltaPeriod = 3600; checkTime = 300; launchTimestamp = uint(-1); rotationDelay = 12 hours; proofOfUseLockUpPeriodDays = 90; proofOfUseDelegationPercentage = 50; limitValidatorsPerDelegator = 20; firstDelegationsMonth = 0; complaintTimelimit = 1800; } } // SPDX-License-Identifier: AGPL-3.0-only /* ContractManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol"; import "./utils/StringUtils.sol"; /** * @title ContractManager * @dev Contract contains the actual current mapping from contract IDs * (in the form of human-readable strings) to addresses. */ contract ContractManager is OwnableUpgradeSafe { using StringUtils for string; using Address for address; string public constant BOUNTY = "Bounty"; string public constant CONSTANTS_HOLDER = "ConstantsHolder"; string public constant DELEGATION_PERIOD_MANAGER = "DelegationPeriodManager"; string public constant PUNISHER = "Punisher"; string public constant SKALE_TOKEN = "SkaleToken"; string public constant TIME_HELPERS = "TimeHelpers"; string public constant TOKEN_LAUNCH_LOCKER = "TokenLaunchLocker"; string public constant TOKEN_STATE = "TokenState"; string public constant VALIDATOR_SERVICE = "ValidatorService"; // mapping of actual smart contracts addresses mapping (bytes32 => address) public contracts; /** * @dev Emitted when contract is upgraded. */ event ContractUpgraded(string contractsName, address contractsAddress); function initialize() external initializer { OwnableUpgradeSafe.__Ownable_init(); } /** * @dev Allows the Owner to add contract to mapping of contract addresses. * * Emits a {ContractUpgraded} event. * * Requirements: * * - New address is non-zero. * - Contract is not already added. * - Contract address contains code. */ function setContractsAddress(string calldata contractsName, address newContractsAddress) external onlyOwner { // check newContractsAddress is not equal to zero require(newContractsAddress != address(0), "New address is equal zero"); // create hash of contractsName bytes32 contractId = keccak256(abi.encodePacked(contractsName)); // check newContractsAddress is not equal the previous contract's address require(contracts[contractId] != newContractsAddress, "Contract is already added"); require(newContractsAddress.isContract(), "Given contract address does not contain code"); // add newContractsAddress to mapping of actual contract addresses contracts[contractId] = newContractsAddress; emit ContractUpgraded(contractsName, newContractsAddress); } /** * @dev Returns contract address. * * Requirements: * * - Contract must exist. */ function getDelegationPeriodManager() external view returns (address) { return getContract(DELEGATION_PERIOD_MANAGER); } function getBounty() external view returns (address) { return getContract(BOUNTY); } function getValidatorService() external view returns (address) { return getContract(VALIDATOR_SERVICE); } function getTimeHelpers() external view returns (address) { return getContract(TIME_HELPERS); } function getTokenLaunchLocker() external view returns (address) { return getContract(TOKEN_LAUNCH_LOCKER); } function getConstantsHolder() external view returns (address) { return getContract(CONSTANTS_HOLDER); } function getSkaleToken() external view returns (address) { return getContract(SKALE_TOKEN); } function getTokenState() external view returns (address) { return getContract(TOKEN_STATE); } function getPunisher() external view returns (address) { return getContract(PUNISHER); } function getContract(string memory name) public view returns (address contractAddress) { contractAddress = contracts[keccak256(abi.encodePacked(name))]; if (contractAddress == address(0)) { revert(name.strConcat(" contract has not been found")); } } } // SPDX-License-Identifier: AGPL-3.0-only /* Decryption.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @title Decryption * @dev This contract performs encryption and decryption functions. * Decrypt is used by SkaleDKG contract to decrypt secret key contribution to * validate complaints during the DKG procedure. */ contract Decryption { /** * @dev Returns an encrypted text given a secret and a key. */ function encrypt(uint256 secretNumber, bytes32 key) external pure returns (bytes32 ciphertext) { return bytes32(secretNumber) ^ key; } /** * @dev Returns a secret given an encrypted text and a key. */ function decrypt(bytes32 ciphertext, bytes32 key) external pure returns (uint256 secretNumber) { return uint256(ciphertext ^ key); } } // SPDX-License-Identifier: AGPL-3.0-only /* KeyStorage.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Decryption.sol"; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./thirdparty/ECDH.sol"; import "./utils/Precompiled.sol"; import "./utils/FieldOperations.sol"; contract KeyStorage is Permissions { using Fp2Operations for Fp2Operations.Fp2Point; using G2Operations for G2Operations.G2Point; struct BroadcastedData { KeyShare[] secretKeyContribution; G2Operations.G2Point[] verificationVector; } struct KeyShare { bytes32[2] publicKey; bytes32 share; } // Unused variable!! mapping(bytes32 => mapping(uint => BroadcastedData)) private _data; // mapping(bytes32 => G2Operations.G2Point) private _publicKeysInProgress; mapping(bytes32 => G2Operations.G2Point) private _schainsPublicKeys; // Unused variable mapping(bytes32 => G2Operations.G2Point[]) private _schainsNodesPublicKeys; // mapping(bytes32 => G2Operations.G2Point[]) private _previousSchainsPublicKeys; function deleteKey(bytes32 schainId) external allow("SkaleDKG") { _previousSchainsPublicKeys[schainId].push(_schainsPublicKeys[schainId]); delete _schainsPublicKeys[schainId]; } function initPublicKeyInProgress(bytes32 schainId) external allow("SkaleDKG") { _publicKeysInProgress[schainId] = G2Operations.getG2Zero(); } function adding(bytes32 schainId, G2Operations.G2Point memory value) external allow("SkaleDKG") { require(value.isG2(), "Incorrect g2 point"); _publicKeysInProgress[schainId] = value.addG2(_publicKeysInProgress[schainId]); } function finalizePublicKey(bytes32 schainId) external allow("SkaleDKG") { if (!_isSchainsPublicKeyZero(schainId)) { _previousSchainsPublicKeys[schainId].push(_schainsPublicKeys[schainId]); } _schainsPublicKeys[schainId] = _publicKeysInProgress[schainId]; delete _publicKeysInProgress[schainId]; } function getCommonPublicKey(bytes32 schainId) external view returns (G2Operations.G2Point memory) { return _schainsPublicKeys[schainId]; } function getPreviousPublicKey(bytes32 schainId) external view returns (G2Operations.G2Point memory) { uint length = _previousSchainsPublicKeys[schainId].length; if (length == 0) { return G2Operations.getG2Zero(); } return _previousSchainsPublicKeys[schainId][length - 1]; } function getAllPreviousPublicKeys(bytes32 schainId) external view returns (G2Operations.G2Point[] memory) { return _previousSchainsPublicKeys[schainId]; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function _isSchainsPublicKeyZero(bytes32 schainId) private view returns (bool) { return _schainsPublicKeys[schainId].x.a == 0 && _schainsPublicKeys[schainId].x.b == 0 && _schainsPublicKeys[schainId].y.a == 0 && _schainsPublicKeys[schainId].y.b == 0; } function _getData() private view returns (BroadcastedData memory) { return _data[keccak256(abi.encodePacked("UnusedFunction"))][0]; } function _getNodesPublicKey() private view returns (G2Operations.G2Point memory) { return _schainsNodesPublicKeys[keccak256(abi.encodePacked("UnusedFunction"))][0]; } } // SPDX-License-Identifier: AGPL-3.0-only /* NodeRotation.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Strings.sol"; import "./Permissions.sol"; import "./ConstantsHolder.sol"; import "./SchainsInternal.sol"; import "./Schains.sol"; import "./Nodes.sol"; import "./interfaces/ISkaleDKG.sol"; /** * @title NodeRotation * @dev This contract handles all node rotation functionality. */ contract NodeRotation is Permissions { using StringUtils for string; using StringUtils for uint; using Strings for uint; /** * nodeIndex - index of Node which is in process of rotation (left from schain) * newNodeIndex - index of Node which is rotated(added to schain) * freezeUntil - time till which Node should be turned on * rotationCounter - how many rotations were on this schain */ struct Rotation { uint nodeIndex; uint newNodeIndex; uint freezeUntil; uint rotationCounter; } struct LeavingHistory { bytes32 schainIndex; uint finishedRotation; } mapping (bytes32 => Rotation) public rotations; mapping (uint => LeavingHistory[]) public leavingHistory; mapping (bytes32 => bool) public waitForNewNode; /** * @dev Allows SkaleManager to remove, find new node, and rotate node from * schain. * * Requirements: * * - A free node must exist. */ function exitFromSchain(uint nodeIndex) external allow("SkaleManager") returns (bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainId = schainsInternal.getActiveSchain(nodeIndex); require(_checkRotation(schainId), "No free Nodes available for rotating"); rotateNode(nodeIndex, schainId, true); return schainsInternal.getActiveSchain(nodeIndex) == bytes32(0) ? true : false; } /** * @dev Allows SkaleManager contract to freeze all schains on a given node. */ function freezeSchains(uint nodeIndex) external allow("SkaleManager") { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32[] memory schains = schainsInternal.getActiveSchains(nodeIndex); for (uint i = 0; i < schains.length; i++) { Rotation memory rotation = rotations[schains[i]]; if (rotation.nodeIndex == nodeIndex && now < rotation.freezeUntil) { continue; } string memory schainName = schainsInternal.getSchainName(schains[i]); string memory revertMessage = "Node cannot rotate on Schain "; revertMessage = revertMessage.strConcat(schainName); revertMessage = revertMessage.strConcat(", occupied by Node "); revertMessage = revertMessage.strConcat(rotation.nodeIndex.toString()); string memory dkgRevert = "DKG process did not finish on schain "; ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); require( skaleDKG.isLastDKGSuccessful(keccak256(abi.encodePacked(schainName))), dkgRevert.strConcat(schainName)); require(rotation.freezeUntil < now, revertMessage); _startRotation(schains[i], nodeIndex); } } /** * @dev Allows Schains contract to remove a rotation from an schain. */ function removeRotation(bytes32 schainIndex) external allow("Schains") { delete rotations[schainIndex]; } /** * @dev Allows Owner to immediately rotate an schain. */ function skipRotationDelay(bytes32 schainIndex) external onlyOwner { rotations[schainIndex].freezeUntil = now; } /** * @dev Returns rotation details for a given schain. */ function getRotation(bytes32 schainIndex) external view returns (Rotation memory) { return rotations[schainIndex]; } /** * @dev Returns leaving history for a given node. */ function getLeavingHistory(uint nodeIndex) external view returns (LeavingHistory[] memory) { return leavingHistory[nodeIndex]; } function isRotationInProgress(bytes32 schainIndex) external view returns (bool) { return rotations[schainIndex].freezeUntil >= now && !waitForNewNode[schainIndex]; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev Allows SkaleDKG and SkaleManager contracts to rotate a node from an * schain. */ function rotateNode( uint nodeIndex, bytes32 schainId, bool shouldDelay ) public allowTwo("SkaleDKG", "SkaleManager") returns (uint newNode) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); Schains schains = Schains(contractManager.getContract("Schains")); schainsInternal.removeNodeFromSchain(nodeIndex, schainId); newNode = selectNodeToGroup(schainId); uint8 space = schainsInternal.getSchainsPartOfNode(schainId); schains.addSpace(nodeIndex, space); _finishRotation(schainId, nodeIndex, newNode, shouldDelay); } /** * @dev Allows SkaleManager, Schains, and SkaleDKG contracts to * pseudo-randomly select a new Node for an Schain. * * Requirements: * * - Schain is active. * - A free node already exists. * - Free space can be allocated from the node. */ function selectNodeToGroup(bytes32 schainId) public allowThree("SkaleManager", "Schains", "SkaleDKG") returns (uint) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); require(schainsInternal.isSchainActive(schainId), "Group is not active"); uint8 space = schainsInternal.getSchainsPartOfNode(schainId); uint[] memory possibleNodes = schainsInternal.isEnoughNodes(schainId); require(possibleNodes.length > 0, "No free Nodes available for rotation"); uint nodeIndex; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number - 1)), schainId))); do { uint index = random % possibleNodes.length; nodeIndex = possibleNodes[index]; random = uint(keccak256(abi.encodePacked(random, nodeIndex))); } while (schainsInternal.checkException(schainId, nodeIndex)); require(nodes.removeSpaceFromNode(nodeIndex, space), "Could not remove space from nodeIndex"); schainsInternal.addSchainForNode(nodeIndex, schainId); schainsInternal.setException(schainId, nodeIndex); schainsInternal.setNodeInGroup(schainId, nodeIndex); return nodeIndex; } /** * @dev Initiates rotation of a node from an schain. */ function _startRotation(bytes32 schainIndex, uint nodeIndex) private { ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); rotations[schainIndex].nodeIndex = nodeIndex; rotations[schainIndex].newNodeIndex = nodeIndex; rotations[schainIndex].freezeUntil = now.add(constants.rotationDelay()); waitForNewNode[schainIndex] = true; } /** * @dev Completes rotation of a node from an schain. */ function _finishRotation( bytes32 schainIndex, uint nodeIndex, uint newNodeIndex, bool shouldDelay) private { ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); leavingHistory[nodeIndex].push( LeavingHistory(schainIndex, shouldDelay ? now.add(constants.rotationDelay()) : now) ); rotations[schainIndex].newNodeIndex = newNodeIndex; rotations[schainIndex].rotationCounter++; delete waitForNewNode[schainIndex]; ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainIndex); } /** * @dev Checks whether a rotation can be performed. * * Requirements: * * - Schain must exist. */ function _checkRotation(bytes32 schainId ) private view returns (bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainExist(schainId), "Schain does not exist for rotation"); return schainsInternal.isAnyFreeNode(schainId); } } // SPDX-License-Identifier: AGPL-3.0-only /* Nodes.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/utils/SafeCast.sol"; import "./delegation/DelegationController.sol"; import "./delegation/ValidatorService.sol"; import "./BountyV2.sol"; import "./ConstantsHolder.sol"; import "./Permissions.sol"; /** * @title Nodes * @dev This contract contains all logic to manage SKALE Network nodes states, * space availability, stake requirement checks, and exit functions. * * Nodes may be in one of several states: * * - Active: Node is registered and is in network operation. * - Leaving: Node has begun exiting from the network. * - Left: Node has left the network. * - In_Maintenance: Node is temporarily offline or undergoing infrastructure * maintenance * * Note: Online nodes contain both Active and Leaving states. */ contract Nodes is Permissions { using SafeCast for uint; // All Nodes states enum NodeStatus {Active, Leaving, Left, In_Maintenance} struct Node { string name; bytes4 ip; bytes4 publicIP; uint16 port; bytes32[2] publicKey; uint startBlock; uint lastRewardDate; uint finishTime; NodeStatus status; uint validatorId; string domainName; } // struct to note which Nodes and which number of Nodes owned by user struct CreatedNodes { mapping (uint => bool) isNodeExist; uint numberOfNodes; } struct SpaceManaging { uint8 freeSpace; uint indexInSpaceMap; } // TODO: move outside the contract struct NodeCreationParams { string name; bytes4 ip; bytes4 publicIp; uint16 port; bytes32[2] publicKey; uint16 nonce; string domainName; } // array which contain all Nodes Node[] public nodes; SpaceManaging[] public spaceOfNodes; // mapping for checking which Nodes and which number of Nodes owned by user mapping (address => CreatedNodes) public nodeIndexes; // mapping for checking is IP address busy mapping (bytes4 => bool) public nodesIPCheck; // mapping for checking is Name busy mapping (bytes32 => bool) public nodesNameCheck; // mapping for indication from Name to Index mapping (bytes32 => uint) public nodesNameToIndex; // mapping for indication from space to Nodes mapping (uint8 => uint[]) public spaceToNodes; mapping (uint => uint[]) public validatorToNodeIndexes; uint public numberOfActiveNodes; uint public numberOfLeavingNodes; uint public numberOfLeftNodes; /** * @dev Emitted when a node is created. */ event NodeCreated( uint nodeIndex, address owner, string name, bytes4 ip, bytes4 publicIP, uint16 port, uint16 nonce, string domainName, uint time, uint gasSpend ); /** * @dev Emitted when a node completes a network exit. */ event ExitCompleted( uint nodeIndex, uint time, uint gasSpend ); /** * @dev Emitted when a node begins to exit from the network. */ event ExitInitialized( uint nodeIndex, uint startLeavingPeriod, uint time, uint gasSpend ); modifier checkNodeExists(uint nodeIndex) { require(nodeIndex < nodes.length, "Node with such index does not exist"); _; } modifier onlyNodeOrAdmin(uint nodeIndex) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require( isNodeExist(msg.sender, nodeIndex) || _isAdmin(msg.sender) || getValidatorId(nodeIndex) == validatorService.getValidatorId(msg.sender), "Sender is not permitted to call this function" ); _; } /** * @dev Allows Schains and SchainsInternal contracts to occupy available * space on a node. * * Returns whether operation is successful. */ function removeSpaceFromNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allowTwo("NodeRotation", "SchainsInternal") returns (bool) { if (spaceOfNodes[nodeIndex].freeSpace < space) { return false; } if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).sub(space).toUint8() ); } return true; } /** * @dev Allows Schains contract to occupy free space on a node. * * Returns whether operation is successful. */ function addSpaceToNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allow("Schains") { if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).add(space).toUint8() ); } } /** * @dev Allows SkaleManager to change a node's last reward date. */ function changeNodeLastRewardDate(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].lastRewardDate = block.timestamp; } /** * @dev Allows SkaleManager to change a node's finish time. */ function changeNodeFinishTime(uint nodeIndex, uint time) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].finishTime = time; } /** * @dev Allows SkaleManager contract to create new node and add it to the * Nodes contract. * * Emits a {NodeCreated} event. * * Requirements: * * - Node IP must be non-zero. * - Node IP must be available. * - Node name must not already be registered. * - Node port must be greater than zero. */ function createNode(address from, NodeCreationParams calldata params) external allow("SkaleManager") // returns (uint nodeIndex) { // checks that Node has correct data require(params.ip != 0x0 && !nodesIPCheck[params.ip], "IP address is zero or is not available"); require(!nodesNameCheck[keccak256(abi.encodePacked(params.name))], "Name is already registered"); require(params.port > 0, "Port is zero"); require(from == _publicKeyToAddress(params.publicKey), "Public Key is incorrect"); uint validatorId = ValidatorService( contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from); // adds Node to Nodes contract uint nodeIndex = _addNode( from, params.name, params.ip, params.publicIp, params.port, params.publicKey, params.domainName, validatorId); emit NodeCreated( nodeIndex, from, params.name, params.ip, params.publicIp, params.port, params.nonce, params.domainName, block.timestamp, gasleft()); } /** * @dev Allows SkaleManager contract to initiate a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitInitialized} event. */ function initExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeActive(nodeIndex), "Node should be Active"); _setNodeLeaving(nodeIndex); emit ExitInitialized( nodeIndex, block.timestamp, block.timestamp, gasleft()); return true; } /** * @dev Allows SkaleManager contract to complete a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitCompleted} event. * * Requirements: * * - Node must have already initialized a node exit procedure. */ function completeExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeLeaving(nodeIndex), "Node is not Leaving"); _setNodeLeft(nodeIndex); _deleteNode(nodeIndex); emit ExitCompleted( nodeIndex, block.timestamp, gasleft()); return true; } /** * @dev Allows SkaleManager contract to delete a validator's node. * * Requirements: * * - Validator ID must exist. */ function deleteNodeForValidator(uint validatorId, uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); if (position < validatorNodes.length) { validatorToNodeIndexes[validatorId][position] = validatorToNodeIndexes[validatorId][validatorNodes.length.sub(1)]; } validatorToNodeIndexes[validatorId].pop(); address nodeOwner = _publicKeyToAddress(nodes[nodeIndex].publicKey); if (validatorService.getValidatorIdByNodeAddress(nodeOwner) == validatorId) { if (nodeIndexes[nodeOwner].numberOfNodes == 1 && !validatorService.validatorAddressExists(nodeOwner)) { validatorService.removeNodeAddress(validatorId, nodeOwner); } nodeIndexes[nodeOwner].isNodeExist[nodeIndex] = false; nodeIndexes[nodeOwner].numberOfNodes--; } } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to create another node. * * Requirements: * * - Validator must be included on trusted list if trusted list is enabled. * - Validator must have sufficient stake to operate an additional node. */ function checkPossibilityCreatingNode(address nodeAddress) external allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress); require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr(); require( validatorNodes.length.add(1).mul(msr) <= delegationsTotal, "Validator must meet the Minimum Staking Requirement"); } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to maintain a node. * * Returns whether validator can maintain node with current stake. * * Requirements: * * - Validator ID and nodeIndex must both exist. */ function checkPossibilityToMaintainNode( uint validatorId, uint nodeIndex ) external checkNodeExists(nodeIndex) allow("Bounty") returns (bool) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); require(position < validatorNodes.length, "Node does not exist for this Validator"); uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr(); return position.add(1).mul(msr) <= delegationsTotal; } /** * @dev Allows Node to set In_Maintenance status. * * Requirements: * * - Node must already be Active. * - `msg.sender` must be owner of Node, validator, or SkaleManager. */ function setNodeInMaintenance(uint nodeIndex) external onlyNodeOrAdmin(nodeIndex) { require(nodes[nodeIndex].status == NodeStatus.Active, "Node is not Active"); _setNodeInMaintenance(nodeIndex); } /** * @dev Allows Node to remove In_Maintenance status. * * Requirements: * * - Node must already be In Maintenance. * - `msg.sender` must be owner of Node, validator, or SkaleManager. */ function removeNodeFromInMaintenance(uint nodeIndex) external onlyNodeOrAdmin(nodeIndex) { require(nodes[nodeIndex].status == NodeStatus.In_Maintenance, "Node is not In Maintenance"); _setNodeActive(nodeIndex); } function setDomainName(uint nodeIndex, string memory domainName) external onlyNodeOrAdmin(nodeIndex) { nodes[nodeIndex].domainName = domainName; } /** * @dev Returns nodes with space availability. */ function getNodesWithFreeSpace(uint8 freeSpace) external view returns (uint[] memory) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint[] memory nodesWithFreeSpace = new uint[](countNodesWithFreeSpace(freeSpace)); uint cursor = 0; uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE(); for (uint8 i = freeSpace; i <= totalSpace; ++i) { for (uint j = 0; j < spaceToNodes[i].length; j++) { nodesWithFreeSpace[cursor] = spaceToNodes[i][j]; ++cursor; } } return nodesWithFreeSpace; } /** * @dev Checks whether it is time for a node's reward. */ function isTimeForReward(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex) <= now; } /** * @dev Returns IP address of a given node. * * Requirements: * * - Node must exist. */ function getNodeIP(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes4) { require(nodeIndex < nodes.length, "Node does not exist"); return nodes[nodeIndex].ip; } /** * @dev Returns domain name of a given node. * * Requirements: * * - Node must exist. */ function getNodeDomainName(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (string memory) { return nodes[nodeIndex].domainName; } /** * @dev Returns the port of a given node. * * Requirements: * * - Node must exist. */ function getNodePort(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint16) { return nodes[nodeIndex].port; } /** * @dev Returns the public key of a given node. */ function getNodePublicKey(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes32[2] memory) { return nodes[nodeIndex].publicKey; } /** * @dev Returns an address of a given node. */ function getNodeAddress(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (address) { return _publicKeyToAddress(nodes[nodeIndex].publicKey); } /** * @dev Returns the finish exit time of a given node. */ function getNodeFinishTime(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].finishTime; } /** * @dev Checks whether a node has left the network. */ function isNodeLeft(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Left; } function isNodeInMaintenance(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.In_Maintenance; } /** * @dev Returns a given node's last reward date. */ function getNodeLastRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].lastRewardDate; } /** * @dev Returns a given node's next reward date. */ function getNodeNextRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex); } /** * @dev Returns the total number of registered nodes. */ function getNumberOfNodes() external view returns (uint) { return nodes.length; } /** * @dev Returns the total number of online nodes. * * Note: Online nodes are equal to the number of active plus leaving nodes. */ function getNumberOnlineNodes() external view returns (uint) { return numberOfActiveNodes.add(numberOfLeavingNodes); } /** * @dev Returns IPs of active nodes. */ function getActiveNodeIPs() external view returns (bytes4[] memory activeNodeIPs) { activeNodeIPs = new bytes4[](numberOfActiveNodes); uint indexOfActiveNodeIPs = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIPs[indexOfActiveNodeIPs] = nodes[indexOfNodes].ip; indexOfActiveNodeIPs++; } } } /** * @dev Returns active nodes linked to the `msg.sender` (validator address). */ function getActiveNodesByAddress() external view returns (uint[] memory activeNodesByAddress) { activeNodesByAddress = new uint[](nodeIndexes[msg.sender].numberOfNodes); uint indexOfActiveNodesByAddress = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeExist(msg.sender, indexOfNodes) && isNodeActive(indexOfNodes)) { activeNodesByAddress[indexOfActiveNodesByAddress] = indexOfNodes; indexOfActiveNodesByAddress++; } } } /** * @dev Return active node IDs. */ function getActiveNodeIds() external view returns (uint[] memory activeNodeIds) { activeNodeIds = new uint[](numberOfActiveNodes); uint indexOfActiveNodeIds = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIds[indexOfActiveNodeIds] = indexOfNodes; indexOfActiveNodeIds++; } } } /** * @dev Return a given node's current status. */ function getNodeStatus(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (NodeStatus) { return nodes[nodeIndex].status; } /** * @dev Return a validator's linked nodes. * * Requirements: * * - Validator ID must exist. */ function getValidatorNodeIndexes(uint validatorId) external view returns (uint[] memory) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); return validatorToNodeIndexes[validatorId]; } /** * @dev constructor in Permissions approach. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); numberOfActiveNodes = 0; numberOfLeavingNodes = 0; numberOfLeftNodes = 0; } /** * @dev Returns the Validator ID for a given node. */ function getValidatorId(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].validatorId; } /** * @dev Checks whether a node exists for a given address. */ function isNodeExist(address from, uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodeIndexes[from].isNodeExist[nodeIndex]; } /** * @dev Checks whether a node's status is Active. */ function isNodeActive(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Active; } /** * @dev Checks whether a node's status is Leaving. */ function isNodeLeaving(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Leaving; } /** * @dev Returns number of nodes with available space. */ function countNodesWithFreeSpace(uint8 freeSpace) public view returns (uint count) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); count = 0; uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE(); for (uint8 i = freeSpace; i <= totalSpace; ++i) { count = count.add(spaceToNodes[i].length); } } /** * @dev Returns the index of a given node within the validator's node index. */ function _findNode(uint[] memory validatorNodeIndexes, uint nodeIndex) private pure returns (uint) { uint i; for (i = 0; i < validatorNodeIndexes.length; i++) { if (validatorNodeIndexes[i] == nodeIndex) { return i; } } return validatorNodeIndexes.length; } /** * @dev Moves a node to a new space mapping. */ function _moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) private { uint8 previousSpace = spaceOfNodes[nodeIndex].freeSpace; uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; if (indexInArray < spaceToNodes[previousSpace].length.sub(1)) { uint shiftedIndex = spaceToNodes[previousSpace][spaceToNodes[previousSpace].length.sub(1)]; spaceToNodes[previousSpace][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; spaceToNodes[previousSpace].pop(); } else { spaceToNodes[previousSpace].pop(); } spaceToNodes[newSpace].push(nodeIndex); spaceOfNodes[nodeIndex].freeSpace = newSpace; spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[newSpace].length.sub(1); } /** * @dev Changes a node's status to Active. */ function _setNodeActive(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Active; numberOfActiveNodes = numberOfActiveNodes.add(1); } /** * @dev Changes a node's status to In_Maintenance. */ function _setNodeInMaintenance(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.In_Maintenance; numberOfActiveNodes = numberOfActiveNodes.sub(1); } /** * @dev Changes a node's status to Left. */ function _setNodeLeft(uint nodeIndex) private { nodesIPCheck[nodes[nodeIndex].ip] = false; nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false; delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))]; if (nodes[nodeIndex].status == NodeStatus.Active) { numberOfActiveNodes--; } else { numberOfLeavingNodes--; } nodes[nodeIndex].status = NodeStatus.Left; numberOfLeftNodes++; } /** * @dev Changes a node's status to Leaving. */ function _setNodeLeaving(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Leaving; numberOfActiveNodes--; numberOfLeavingNodes++; } /** * @dev Adds node to array. */ function _addNode( address from, string memory name, bytes4 ip, bytes4 publicIP, uint16 port, bytes32[2] memory publicKey, string memory domainName, uint validatorId ) private returns (uint nodeIndex) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); nodes.push(Node({ name: name, ip: ip, publicIP: publicIP, port: port, //owner: from, publicKey: publicKey, startBlock: block.number, lastRewardDate: block.timestamp, finishTime: 0, status: NodeStatus.Active, validatorId: validatorId, domainName: domainName })); nodeIndex = nodes.length.sub(1); validatorToNodeIndexes[validatorId].push(nodeIndex); bytes32 nodeId = keccak256(abi.encodePacked(name)); nodesIPCheck[ip] = true; nodesNameCheck[nodeId] = true; nodesNameToIndex[nodeId] = nodeIndex; nodeIndexes[from].isNodeExist[nodeIndex] = true; nodeIndexes[from].numberOfNodes++; spaceOfNodes.push(SpaceManaging({ freeSpace: constantsHolder.TOTAL_SPACE_ON_NODE(), indexInSpaceMap: spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].length })); spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].push(nodeIndex); numberOfActiveNodes++; } /** * @dev Deletes node from array. */ function _deleteNode(uint nodeIndex) private { uint8 space = spaceOfNodes[nodeIndex].freeSpace; uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; if (indexInArray < spaceToNodes[space].length.sub(1)) { uint shiftedIndex = spaceToNodes[space][spaceToNodes[space].length.sub(1)]; spaceToNodes[space][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; spaceToNodes[space].pop(); } else { spaceToNodes[space].pop(); } delete spaceOfNodes[nodeIndex].freeSpace; delete spaceOfNodes[nodeIndex].indexInSpaceMap; } function _publicKeyToAddress(bytes32[2] memory pubKey) private pure returns (address) { bytes32 hash = keccak256(abi.encodePacked(pubKey[0], pubKey[1])); bytes20 addr; for (uint8 i = 12; i < 32; i++) { addr |= bytes20(hash[i] & 0xFF) >> ((i - 12) * 8); } return address(addr); } function _min(uint a, uint b) private pure returns (uint) { if (a < b) { return a; } else { return b; } } } // SPDX-License-Identifier: AGPL-3.0-only /* Permissions.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; import "./ContractManager.sol"; /** * @title Permissions * @dev Contract is connected module for Upgradeable approach, knows ContractManager */ contract Permissions is AccessControlUpgradeSafe { using SafeMath for uint; using Address for address; ContractManager public contractManager; /** * @dev Modifier to make a function callable only when caller is the Owner. * * Requirements: * * - The caller must be the owner. */ modifier onlyOwner() { require(_isOwner(), "Caller is not the owner"); _; } /** * @dev Modifier to make a function callable only when caller is an Admin. * * Requirements: * * - The caller must be an admin. */ modifier onlyAdmin() { require(_isAdmin(msg.sender), "Caller is not an admin"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName` contract. * * Requirements: * * - The caller must be the owner or `contractName`. */ modifier allow(string memory contractName) { require( contractManager.getContract(contractName) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1` or `contractName2` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, or `contractName2`. */ modifier allowTwo(string memory contractName1, string memory contractName2) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1`, `contractName2`, or `contractName3` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, `contractName2`, or * `contractName3`. */ modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || contractManager.getContract(contractName3) == msg.sender || _isOwner(), "Message sender is invalid"); _; } function initialize(address contractManagerAddress) public virtual initializer { AccessControlUpgradeSafe.__AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setContractManager(contractManagerAddress); } function _isOwner() internal view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); } function _isAdmin(address account) internal view returns (bool) { address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager"))); if (skaleManagerAddress != address(0)) { AccessControlUpgradeSafe skaleManager = AccessControlUpgradeSafe(skaleManagerAddress); return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner(); } else { return _isOwner(); } } function _setContractManager(address contractManagerAddress) private { require(contractManagerAddress != address(0), "ContractManager address is not set"); require(contractManagerAddress.isContract(), "Address is not contract"); contractManager = ContractManager(contractManagerAddress); } } // SPDX-License-Identifier: AGPL-3.0-only /* Schains.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./ConstantsHolder.sol"; import "./KeyStorage.sol"; import "./SkaleVerifier.sol"; import "./utils/FieldOperations.sol"; import "./NodeRotation.sol"; import "./interfaces/ISkaleDKG.sol"; /** * @title Schains * @dev Contains functions to manage Schains such as Schain creation, * deletion, and rotation. */ contract Schains is Permissions { using StringUtils for string; using StringUtils for uint; struct SchainParameters { uint lifetime; uint8 typeOfSchain; uint16 nonce; string name; } /** * @dev Emitted when an schain is created. */ event SchainCreated( string name, address owner, uint partOfNode, uint lifetime, uint numberOfNodes, uint deposit, uint16 nonce, bytes32 schainId, uint time, uint gasSpend ); /** * @dev Emitted when an schain is deleted. */ event SchainDeleted( address owner, string name, bytes32 indexed schainId ); /** * @dev Emitted when a node in an schain is rotated. */ event NodeRotated( bytes32 schainId, uint oldNode, uint newNode ); /** * @dev Emitted when a node is added to an schain. */ event NodeAdded( bytes32 schainId, uint newNode ); /** * @dev Emitted when a group of nodes is created for an schain. */ event SchainNodes( string name, bytes32 schainId, uint[] nodesInGroup, uint time, uint gasSpend ); bytes32 public constant SCHAIN_CREATOR_ROLE = keccak256("SCHAIN_CREATOR_ROLE"); /** * @dev Allows SkaleManager contract to create an Schain. * * Emits an {SchainCreated} event. * * Requirements: * * - Schain type is valid. * - There is sufficient deposit to create type of schain. */ function addSchain(address from, uint deposit, bytes calldata data) external allow("SkaleManager") { SchainParameters memory schainParameters = _fallbackSchainParametersDataConverter(data); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint schainCreationTimeStamp = constantsHolder.schainCreationTimeStamp(); uint minSchainLifetime = constantsHolder.minimalSchainLifetime(); require(now >= schainCreationTimeStamp, "It is not a time for creating Schain"); require( schainParameters.lifetime >= minSchainLifetime, "Minimal schain lifetime should be satisfied" ); require( getSchainPrice(schainParameters.typeOfSchain, schainParameters.lifetime) <= deposit, "Not enough money to create Schain"); _addSchain(from, deposit, schainParameters); } function addSchainByFoundation( uint lifetime, uint8 typeOfSchain, uint16 nonce, string calldata name ) external { require(hasRole(SCHAIN_CREATOR_ROLE, msg.sender), "Sender is not authorized to create schain"); SchainParameters memory schainParameters = SchainParameters({ lifetime: lifetime, typeOfSchain: typeOfSchain, nonce: nonce, name: name }); _addSchain(msg.sender, 0, schainParameters); } /** * @dev Allows SkaleManager to remove an schain from the network. * Upon removal, the space availability of each node is updated. * * Emits an {SchainDeleted} event. * * Requirements: * * - Executed by schain owner. */ function deleteSchain(address from, string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainId = keccak256(abi.encodePacked(name)); require( schainsInternal.isOwnerAddress(from, schainId), "Message sender is not the owner of the Schain" ); address nodesAddress = contractManager.getContract("Nodes"); // removes Schain from Nodes uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainId); uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainId); for (uint i = 0; i < nodesInGroup.length; i++) { uint schainIndex = schainsInternal.findSchainAtSchainsForNode( nodesInGroup[i], schainId ); if (schainsInternal.checkHoleForSchain(schainId, i)) { continue; } require( schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]), "Some Node does not contain given Schain"); schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainId); schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]); if (!Nodes(nodesAddress).isNodeLeft(nodesInGroup[i])) { this.addSpace(nodesInGroup[i], partOfNode); } } schainsInternal.deleteGroup(schainId); schainsInternal.removeSchain(schainId, from); schainsInternal.removeHolesForSchain(schainId); nodeRotation.removeRotation(schainId); emit SchainDeleted(from, name, schainId); } /** * @dev Allows SkaleManager to delete any Schain. * Upon removal, the space availability of each node is updated. * * Emits an {SchainDeleted} event. * * Requirements: * * - Schain exists. */ function deleteSchainByRoot(string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainId = keccak256(abi.encodePacked(name)); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainExist(schainId), "Schain does not exist"); // removes Schain from Nodes uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainId); uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainId); for (uint i = 0; i < nodesInGroup.length; i++) { uint schainIndex = schainsInternal.findSchainAtSchainsForNode( nodesInGroup[i], schainId ); if (schainsInternal.checkHoleForSchain(schainId, i)) { continue; } require( schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]), "Some Node does not contain given Schain"); schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainId); schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]); this.addSpace(nodesInGroup[i], partOfNode); } schainsInternal.deleteGroup(schainId); address from = schainsInternal.getSchainOwner(schainId); schainsInternal.removeSchain(schainId, from); schainsInternal.removeHolesForSchain(schainId); nodeRotation.removeRotation(schainId); emit SchainDeleted(from, name, schainId); } /** * @dev Allows SkaleManager contract to restart schain creation by forming a * new schain group. Executed when DKG procedure fails and becomes stuck. * * Emits a {NodeAdded} event. * * Requirements: * * - Previous DKG procedure must have failed. * - DKG failure got stuck because there were no free nodes to rotate in. * - A free node must be released in the network. */ function restartSchainCreation(string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainId = keccak256(abi.encodePacked(name)); ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); require(!skaleDKG.isLastDKGSuccessful(schainId), "DKG success"); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal")); require(schainsInternal.isAnyFreeNode(schainId), "No free Nodes for new group formation"); uint newNodeIndex = nodeRotation.selectNodeToGroup(schainId); skaleDKG.openChannel(schainId); emit NodeAdded(schainId, newNodeIndex); } /** * @dev addSpace - return occupied space to Node * @param nodeIndex - index of Node at common array of Nodes * @param partOfNode - divisor of given type of Schain */ function addSpace(uint nodeIndex, uint8 partOfNode) external allowTwo("Schains", "NodeRotation") { Nodes nodes = Nodes(contractManager.getContract("Nodes")); nodes.addSpaceToNode(nodeIndex, partOfNode); } /** * @dev Checks whether schain group signature is valid. */ function verifySchainSignature( uint signatureA, uint signatureB, bytes32 hash, uint counter, uint hashA, uint hashB, string calldata schainName ) external view returns (bool) { SkaleVerifier skaleVerifier = SkaleVerifier(contractManager.getContract("SkaleVerifier")); G2Operations.G2Point memory publicKey = KeyStorage( contractManager.getContract("KeyStorage") ).getCommonPublicKey( keccak256(abi.encodePacked(schainName)) ); return skaleVerifier.verify( Fp2Operations.Fp2Point({ a: signatureA, b: signatureB }), hash, counter, hashA, hashB, publicKey ); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev Returns the current price in SKL tokens for given Schain type and lifetime. */ function getSchainPrice(uint typeOfSchain, uint lifetime) public view returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint nodeDeposit = constantsHolder.NODE_DEPOSIT(); uint numberOfNodes; uint8 divisor; (numberOfNodes, divisor) = getNodesDataFromTypeOfSchain(typeOfSchain); if (divisor == 0) { return 1e18; } else { uint up = nodeDeposit.mul(numberOfNodes.mul(lifetime.mul(2))); uint down = uint( uint(constantsHolder.SMALL_DIVISOR()) .mul(uint(constantsHolder.SECONDS_TO_YEAR())) .div(divisor) ); return up.div(down); } } /** * @dev Returns the number of Nodes and resource divisor that is needed for a * given Schain type. */ function getNodesDataFromTypeOfSchain(uint typeOfSchain) public view returns (uint numberOfNodes, uint8 partOfNode) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_SCHAIN(); if (typeOfSchain == 1) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.SMALL_DIVISOR(); } else if (typeOfSchain == 2) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.MEDIUM_DIVISOR(); } else if (typeOfSchain == 3) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.LARGE_DIVISOR(); } else if (typeOfSchain == 4) { partOfNode = 0; numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_TEST_SCHAIN(); } else if (typeOfSchain == 5) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.MEDIUM_TEST_DIVISOR(); numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN(); } else { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); (partOfNode, numberOfNodes) = schainsInternal.schainTypes(typeOfSchain); if (numberOfNodes == 0) { revert("Bad schain type"); } } } /** * @dev Initializes an schain in the SchainsInternal contract. * * Requirements: * * - Schain name is not already in use. */ function _initializeSchainInSchainsInternal( string memory name, address from, uint deposit, uint lifetime) private { address dataAddress = contractManager.getContract("SchainsInternal"); require(SchainsInternal(dataAddress).isSchainNameAvailable(name), "Schain name is not available"); // initialize Schain SchainsInternal(dataAddress).initializeSchain( name, from, lifetime, deposit); SchainsInternal(dataAddress).setSchainIndex(keccak256(abi.encodePacked(name)), from); } /** * @dev Converts data from bytes to normal schain parameters of lifetime, * type, nonce, and name. */ function _fallbackSchainParametersDataConverter(bytes memory data) private pure returns (SchainParameters memory schainParameters) { (schainParameters.lifetime, schainParameters.typeOfSchain, schainParameters.nonce, schainParameters.name) = abi.decode(data, (uint, uint8, uint16, string)); } /** * @dev Allows creation of node group for Schain. * * Emits an {SchainNodes} event. */ function _createGroupForSchain( string memory schainName, bytes32 schainId, uint numberOfNodes, uint8 partOfNode ) private { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); uint[] memory nodesInGroup = schainsInternal.createGroupForSchain(schainId, numberOfNodes, partOfNode); ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainId); emit SchainNodes( schainName, schainId, nodesInGroup, block.timestamp, gasleft()); } /** * @dev Creates an schain. * * Emits an {SchainCreated} event. * * Requirements: * * - Schain type must be valid. */ function _addSchain(address from, uint deposit, SchainParameters memory schainParameters) private { uint numberOfNodes; uint8 partOfNode; SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); require(schainParameters.typeOfSchain <= schainsInternal.numberOfSchainTypes(), "Invalid type of Schain"); //initialize Schain _initializeSchainInSchainsInternal( schainParameters.name, from, deposit, schainParameters.lifetime); // create a group for Schain (numberOfNodes, partOfNode) = getNodesDataFromTypeOfSchain(schainParameters.typeOfSchain); _createGroupForSchain( schainParameters.name, keccak256(abi.encodePacked(schainParameters.name)), numberOfNodes, partOfNode ); emit SchainCreated( schainParameters.name, from, partOfNode, schainParameters.lifetime, numberOfNodes, deposit, schainParameters.nonce, keccak256(abi.encodePacked(schainParameters.name)), block.timestamp, gasleft()); } } // SPDX-License-Identifier: AGPL-3.0-only /* SchainsInternal.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./ConstantsHolder.sol"; import "./Nodes.sol"; import "./interfaces/ISkaleDKG.sol"; /** * @title SchainsInternal * @dev Contract contains all functionality logic to internally manage Schains. */ contract SchainsInternal is Permissions { struct Schain { string name; address owner; uint indexInOwnerList; uint8 partOfNode; uint lifetime; uint startDate; uint startBlock; uint deposit; uint64 index; } struct SchainType { uint8 partOfNode; uint numberOfNodes; } // mapping which contain all schains mapping (bytes32 => Schain) public schains; mapping (bytes32 => bool) public isSchainActive; mapping (bytes32 => uint[]) public schainsGroups; mapping (bytes32 => mapping (uint => bool)) private _exceptionsForGroups; // mapping shows schains by owner's address mapping (address => bytes32[]) public schainIndexes; // mapping shows schains which Node composed in mapping (uint => bytes32[]) public schainsForNodes; mapping (uint => uint[]) public holesForNodes; mapping (bytes32 => uint[]) public holesForSchains; // array which contain all schains bytes32[] public schainsAtSystem; uint64 public numberOfSchains; // total resources that schains occupied uint public sumOfSchainsResources; mapping (bytes32 => bool) public usedSchainNames; mapping (uint => SchainType) public schainTypes; uint public numberOfSchainTypes; // schain hash => node index => index of place // index of place is a number from 1 to max number of slots on node(128) mapping (bytes32 => mapping (uint => uint)) public placeOfSchainOnNode; /** * @dev Allows Schain contract to initialize an schain. */ function initializeSchain( string calldata name, address from, uint lifetime, uint deposit) external allow("Schains") { bytes32 schainId = keccak256(abi.encodePacked(name)); schains[schainId].name = name; schains[schainId].owner = from; schains[schainId].startDate = block.timestamp; schains[schainId].startBlock = block.number; schains[schainId].lifetime = lifetime; schains[schainId].deposit = deposit; schains[schainId].index = numberOfSchains; isSchainActive[schainId] = true; numberOfSchains++; schainsAtSystem.push(schainId); usedSchainNames[schainId] = true; } /** * @dev Allows Schain contract to create a node group for an schain. */ function createGroupForSchain( bytes32 schainId, uint numberOfNodes, uint8 partOfNode ) external allow("Schains") returns (uint[] memory) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); schains[schainId].partOfNode = partOfNode; if (partOfNode > 0) { sumOfSchainsResources = sumOfSchainsResources.add( numberOfNodes.mul(constantsHolder.TOTAL_SPACE_ON_NODE()).div(partOfNode) ); } return _generateGroup(schainId, numberOfNodes); } /** * @dev Allows Schains contract to set index in owner list. */ function setSchainIndex(bytes32 schainId, address from) external allow("Schains") { schains[schainId].indexInOwnerList = schainIndexes[from].length; schainIndexes[from].push(schainId); } /** * @dev Allows Schains contract to change the Schain lifetime through * an additional SKL token deposit. */ function changeLifetime(bytes32 schainId, uint lifetime, uint deposit) external allow("Schains") { schains[schainId].deposit = schains[schainId].deposit.add(deposit); schains[schainId].lifetime = schains[schainId].lifetime.add(lifetime); } /** * @dev Allows Schains contract to remove an schain from the network. * Generally schains are not removed from the system; instead they are * simply allowed to expire. */ function removeSchain(bytes32 schainId, address from) external allow("Schains") { isSchainActive[schainId] = false; uint length = schainIndexes[from].length; uint index = schains[schainId].indexInOwnerList; if (index != length.sub(1)) { bytes32 lastSchainId = schainIndexes[from][length.sub(1)]; schains[lastSchainId].indexInOwnerList = index; schainIndexes[from][index] = lastSchainId; } schainIndexes[from].pop(); // TODO: // optimize for (uint i = 0; i + 1 < schainsAtSystem.length; i++) { if (schainsAtSystem[i] == schainId) { schainsAtSystem[i] = schainsAtSystem[schainsAtSystem.length.sub(1)]; break; } } schainsAtSystem.pop(); delete schains[schainId]; numberOfSchains--; } /** * @dev Allows Schains and SkaleDKG contracts to remove a node from an * schain for node rotation or DKG failure. */ function removeNodeFromSchain( uint nodeIndex, bytes32 schainHash ) external allowThree("NodeRotation", "SkaleDKG", "Schains") { uint indexOfNode = _findNode(schainHash, nodeIndex); uint indexOfLastNode = schainsGroups[schainHash].length.sub(1); if (indexOfNode == indexOfLastNode) { schainsGroups[schainHash].pop(); } else { delete schainsGroups[schainHash][indexOfNode]; if (holesForSchains[schainHash].length > 0 && holesForSchains[schainHash][0] > indexOfNode) { uint hole = holesForSchains[schainHash][0]; holesForSchains[schainHash][0] = indexOfNode; holesForSchains[schainHash].push(hole); } else { holesForSchains[schainHash].push(indexOfNode); } } uint schainIndexOnNode = findSchainAtSchainsForNode(nodeIndex, schainHash); removeSchainForNode(nodeIndex, schainIndexOnNode); delete placeOfSchainOnNode[schainHash][nodeIndex]; } /** * @dev Allows Schains contract to remove node from exceptions */ function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) external allow("Schains") { _exceptionsForGroups[schainHash][nodeIndex] = false; } /** * @dev Allows Schains contract to delete a group of schains */ function deleteGroup(bytes32 schainId) external allow("Schains") { // delete channel ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); delete schainsGroups[schainId]; skaleDKG.deleteChannel(schainId); } /** * @dev Allows Schain and NodeRotation contracts to set a Node like * exception for a given schain and nodeIndex. */ function setException(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") { _exceptionsForGroups[schainId][nodeIndex] = true; } /** * @dev Allows Schains and NodeRotation contracts to add node to an schain * group. */ function setNodeInGroup(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") { if (holesForSchains[schainId].length == 0) { schainsGroups[schainId].push(nodeIndex); } else { schainsGroups[schainId][holesForSchains[schainId][0]] = nodeIndex; uint min = uint(-1); uint index = 0; for (uint i = 1; i < holesForSchains[schainId].length; i++) { if (min > holesForSchains[schainId][i]) { min = holesForSchains[schainId][i]; index = i; } } if (min == uint(-1)) { delete holesForSchains[schainId]; } else { holesForSchains[schainId][0] = min; holesForSchains[schainId][index] = holesForSchains[schainId][holesForSchains[schainId].length - 1]; holesForSchains[schainId].pop(); } } } /** * @dev Allows Schains contract to remove holes for schains */ function removeHolesForSchain(bytes32 schainHash) external allow("Schains") { delete holesForSchains[schainHash]; } /** * @dev Allows Admin to add schain type */ function addSchainType(uint8 partOfNode, uint numberOfNodes) external onlyAdmin { schainTypes[numberOfSchainTypes + 1].partOfNode = partOfNode; schainTypes[numberOfSchainTypes + 1].numberOfNodes = numberOfNodes; numberOfSchainTypes++; } /** * @dev Allows Admin to remove schain type */ function removeSchainType(uint typeOfSchain) external onlyAdmin { delete schainTypes[typeOfSchain].partOfNode; delete schainTypes[typeOfSchain].numberOfNodes; } /** * @dev Allows Admin to set number of schain types */ function setNumberOfSchainTypes(uint newNumberOfSchainTypes) external onlyAdmin { numberOfSchainTypes = newNumberOfSchainTypes; } /** * @dev Allows Admin to move schain to placeOfSchainOnNode map */ function moveToPlaceOfSchainOnNode(bytes32 schainHash) external onlyAdmin { for (uint i = 0; i < schainsGroups[schainHash].length; i++) { uint nodeIndex = schainsGroups[schainHash][i]; for (uint j = 0; j < schainsForNodes[nodeIndex].length; j++) { if (schainsForNodes[nodeIndex][j] == schainHash) { placeOfSchainOnNode[schainHash][nodeIndex] = j + 1; } } } } /** * @dev Returns all Schains in the network. */ function getSchains() external view returns (bytes32[] memory) { return schainsAtSystem; } /** * @dev Returns all occupied resources on one node for an Schain. */ function getSchainsPartOfNode(bytes32 schainId) external view returns (uint8) { return schains[schainId].partOfNode; } /** * @dev Returns number of schains by schain owner. */ function getSchainListSize(address from) external view returns (uint) { return schainIndexes[from].length; } /** * @dev Returns hashes of schain names by schain owner. */ function getSchainIdsByAddress(address from) external view returns (bytes32[] memory) { return schainIndexes[from]; } /** * @dev Returns hashes of schain names running on a node. */ function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory) { return schainsForNodes[nodeIndex]; } /** * @dev Returns the owner of an schain. */ function getSchainOwner(bytes32 schainId) external view returns (address) { return schains[schainId].owner; } /** * @dev Checks whether schain name is available. * TODO Need to delete - copy of web3.utils.soliditySha3 */ function isSchainNameAvailable(string calldata name) external view returns (bool) { bytes32 schainId = keccak256(abi.encodePacked(name)); return schains[schainId].owner == address(0) && !usedSchainNames[schainId] && keccak256(abi.encodePacked(name)) != keccak256(abi.encodePacked("Mainnet")); } /** * @dev Checks whether schain lifetime has expired. */ function isTimeExpired(bytes32 schainId) external view returns (bool) { return uint(schains[schainId].startDate).add(schains[schainId].lifetime) < block.timestamp; } /** * @dev Checks whether address is owner of schain. */ function isOwnerAddress(address from, bytes32 schainId) external view returns (bool) { return schains[schainId].owner == from; } /** * @dev Checks whether schain exists. */ function isSchainExist(bytes32 schainId) external view returns (bool) { return keccak256(abi.encodePacked(schains[schainId].name)) != keccak256(abi.encodePacked("")); } /** * @dev Returns schain name. */ function getSchainName(bytes32 schainId) external view returns (string memory) { return schains[schainId].name; } /** * @dev Returns last active schain of a node. */ function getActiveSchain(uint nodeIndex) external view returns (bytes32) { for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { return schainsForNodes[nodeIndex][i - 1]; } } return bytes32(0); } /** * @dev Returns active schains of a node. */ function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains) { uint activeAmount = 0; for (uint i = 0; i < schainsForNodes[nodeIndex].length; i++) { if (schainsForNodes[nodeIndex][i] != bytes32(0)) { activeAmount++; } } uint cursor = 0; activeSchains = new bytes32[](activeAmount); for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { activeSchains[cursor++] = schainsForNodes[nodeIndex][i - 1]; } } } /** * @dev Returns number of nodes in an schain group. */ function getNumberOfNodesInGroup(bytes32 schainId) external view returns (uint) { return schainsGroups[schainId].length; } /** * @dev Returns nodes in an schain group. */ function getNodesInGroup(bytes32 schainId) external view returns (uint[] memory) { return schainsGroups[schainId]; } /** * @dev Checks whether sender is a node address from a given schain group. */ function isNodeAddressesInGroup(bytes32 schainId, address sender) external view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); for (uint i = 0; i < schainsGroups[schainId].length; i++) { if (nodes.getNodeAddress(schainsGroups[schainId][i]) == sender) { return true; } } return false; } /** * @dev Returns node index in schain group. */ function getNodeIndexInGroup(bytes32 schainId, uint nodeId) external view returns (uint) { for (uint index = 0; index < schainsGroups[schainId].length; index++) { if (schainsGroups[schainId][index] == nodeId) { return index; } } return schainsGroups[schainId].length; } /** * @dev Checks whether there are any nodes with free resources for given * schain. */ function isAnyFreeNode(bytes32 schainId) external view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; uint[] memory nodesWithFreeSpace = nodes.getNodesWithFreeSpace(space); for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (_isCorrespond(schainId, nodesWithFreeSpace[i])) { return true; } } return false; } /** * @dev Returns whether any exceptions exist for node in a schain group. */ function checkException(bytes32 schainId, uint nodeIndex) external view returns (bool) { return _exceptionsForGroups[schainId][nodeIndex]; } function checkHoleForSchain(bytes32 schainHash, uint indexOfNode) external view returns (bool) { for (uint i = 0; i < holesForSchains[schainHash].length; i++) { if (holesForSchains[schainHash][i] == indexOfNode) { return true; } } return false; } /** * @dev Returns number of Schains on a node. */ function getLengthOfSchainsForNode(uint nodeIndex) external view returns (uint) { return schainsForNodes[nodeIndex].length; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); numberOfSchains = 0; sumOfSchainsResources = 0; numberOfSchainTypes = 5; } /** * @dev Allows Schains and NodeRotation contracts to add schain to node. */ function addSchainForNode(uint nodeIndex, bytes32 schainId) public allowTwo("Schains", "NodeRotation") { if (holesForNodes[nodeIndex].length == 0) { schainsForNodes[nodeIndex].push(schainId); placeOfSchainOnNode[schainId][nodeIndex] = schainsForNodes[nodeIndex].length; } else { uint lastHoleOfNode = holesForNodes[nodeIndex][holesForNodes[nodeIndex].length - 1]; schainsForNodes[nodeIndex][lastHoleOfNode] = schainId; placeOfSchainOnNode[schainId][nodeIndex] = lastHoleOfNode + 1; holesForNodes[nodeIndex].pop(); } } /** * @dev Allows Schains, NodeRotation, and SkaleDKG contracts to remove an * schain from a node. */ function removeSchainForNode(uint nodeIndex, uint schainIndex) public allowThree("NodeRotation", "SkaleDKG", "Schains") { uint length = schainsForNodes[nodeIndex].length; if (schainIndex == length.sub(1)) { schainsForNodes[nodeIndex].pop(); } else { schainsForNodes[nodeIndex][schainIndex] = bytes32(0); if (holesForNodes[nodeIndex].length > 0 && holesForNodes[nodeIndex][0] > schainIndex) { uint hole = holesForNodes[nodeIndex][0]; holesForNodes[nodeIndex][0] = schainIndex; holesForNodes[nodeIndex].push(hole); } else { holesForNodes[nodeIndex].push(schainIndex); } } } /** * @dev Returns index of Schain in list of schains for a given node. */ function findSchainAtSchainsForNode(uint nodeIndex, bytes32 schainId) public view returns (uint) { if (placeOfSchainOnNode[schainId][nodeIndex] == 0) return schainsForNodes[nodeIndex].length; return placeOfSchainOnNode[schainId][nodeIndex] - 1; } function isEnoughNodes(bytes32 schainId) public view returns (uint[] memory result) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; uint[] memory nodesWithFreeSpace = nodes.getNodesWithFreeSpace(space); uint counter = 0; for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (!_isCorrespond(schainId, nodesWithFreeSpace[i])) { counter++; } } if (counter < nodesWithFreeSpace.length) { result = new uint[](nodesWithFreeSpace.length.sub(counter)); counter = 0; for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (_isCorrespond(schainId, nodesWithFreeSpace[i])) { result[counter] = nodesWithFreeSpace[i]; counter++; } } } } /** * @dev Generates schain group using a pseudo-random generator. */ function _generateGroup(bytes32 schainId, uint numberOfNodes) private returns (uint[] memory nodesInGroup) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; nodesInGroup = new uint[](numberOfNodes); uint[] memory possibleNodes = isEnoughNodes(schainId); require(possibleNodes.length >= nodesInGroup.length, "Not enough nodes to create Schain"); uint ignoringTail = 0; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number.sub(1))), schainId))); for (uint i = 0; i < nodesInGroup.length; ++i) { uint index = random % (possibleNodes.length.sub(ignoringTail)); uint node = possibleNodes[index]; nodesInGroup[i] = node; _swap(possibleNodes, index, possibleNodes.length.sub(ignoringTail).sub(1)); ++ignoringTail; _exceptionsForGroups[schainId][node] = true; addSchainForNode(node, schainId); require(nodes.removeSpaceFromNode(node, space), "Could not remove space from Node"); } // set generated group schainsGroups[schainId] = nodesInGroup; } function _isCorrespond(bytes32 schainId, uint nodeIndex) private view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); return !_exceptionsForGroups[schainId][nodeIndex] && nodes.isNodeActive(nodeIndex); } /** * @dev Swaps one index for another in an array. */ function _swap(uint[] memory array, uint index1, uint index2) private pure { uint buffer = array[index1]; array[index1] = array[index2]; array[index2] = buffer; } /** * @dev Returns local index of node in schain group. */ function _findNode(bytes32 schainId, uint nodeIndex) private view returns (uint) { uint[] memory nodesInGroup = schainsGroups[schainId]; uint index; for (index = 0; index < nodesInGroup.length; index++) { if (nodesInGroup[index] == nodeIndex) { return index; } } return index; } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleVerifier.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./utils/Precompiled.sol"; import "./utils/FieldOperations.sol"; /** * @title SkaleVerifier * @dev Contains verify function to perform BLS signature verification. */ contract SkaleVerifier is Permissions { using Fp2Operations for Fp2Operations.Fp2Point; /** * @dev Verifies a BLS signature. * * Requirements: * * - Signature is in G1. * - Hash is in G1. * - G2.one in G2. * - Public Key in G2. */ function verify( Fp2Operations.Fp2Point calldata signature, bytes32 hash, uint counter, uint hashA, uint hashB, G2Operations.G2Point calldata publicKey ) external view returns (bool) { require(G1Operations.checkRange(signature), "Signature is not valid"); if (!_checkHashToGroupWithHelper( hash, counter, hashA, hashB ) ) { return false; } uint newSignB = G1Operations.negate(signature.b); require(G1Operations.isG1Point(signature.a, newSignB), "Sign not in G1"); require(G1Operations.isG1Point(hashA, hashB), "Hash not in G1"); G2Operations.G2Point memory g2 = G2Operations.getG2Generator(); require( G2Operations.isG2(publicKey), "Public Key not in G2" ); return Precompiled.bn256Pairing( signature.a, newSignB, g2.x.b, g2.x.a, g2.y.b, g2.y.a, hashA, hashB, publicKey.x.b, publicKey.x.a, publicKey.y.b, publicKey.y.a ); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } function _checkHashToGroupWithHelper( bytes32 hash, uint counter, uint hashA, uint hashB ) private pure returns (bool) { if (counter > 100) { return false; } uint xCoord = uint(hash) % Fp2Operations.P; xCoord = (xCoord.add(counter)) % Fp2Operations.P; uint ySquared = addmod( mulmod(mulmod(xCoord, xCoord, Fp2Operations.P), xCoord, Fp2Operations.P), 3, Fp2Operations.P ); if (hashB < Fp2Operations.P.div(2) || mulmod(hashB, hashB, Fp2Operations.P) != ySquared || xCoord != hashA) { return false; } return true; } } // SPDX-License-Identifier: AGPL-3.0-only /* DelegationController.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "../BountyV2.sol"; import "../Nodes.sol"; import "../Permissions.sol"; import "../utils/FractionUtils.sol"; import "../utils/MathUtils.sol"; import "./DelegationPeriodManager.sol"; import "./PartialDifferences.sol"; import "./Punisher.sol"; import "./TokenLaunchLocker.sol"; import "./TokenState.sol"; import "./ValidatorService.sol"; /** * @title Delegation Controller * @dev This contract performs all delegation functions including delegation * requests, and undelegation, etc. * * Delegators and validators may both perform delegations. Validators who perform * delegations to themselves are effectively self-delegating or self-bonding. * * IMPORTANT: Undelegation may be requested at any time, but undelegation is only * performed at the completion of the current delegation period. * * Delegated tokens may be in one of several states: * * - PROPOSED: token holder proposes tokens to delegate to a validator. * - ACCEPTED: token delegations are accepted by a validator and are locked-by-delegation. * - CANCELED: token holder cancels delegation proposal. Only allowed before the proposal is accepted by the validator. * - REJECTED: token proposal expires at the UTC start of the next month. * - DELEGATED: accepted delegations are delegated at the UTC start of the month. * - UNDELEGATION_REQUESTED: token holder requests delegations to undelegate from the validator. * - COMPLETED: undelegation request is completed at the end of the delegation period. */ contract DelegationController is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Sequence; using PartialDifferences for PartialDifferences.Value; using FractionUtils for FractionUtils.Fraction; uint public constant UNDELEGATION_PROHIBITION_WINDOW_SECONDS = 3 * 24 * 60 * 60; enum State { PROPOSED, ACCEPTED, CANCELED, REJECTED, DELEGATED, UNDELEGATION_REQUESTED, COMPLETED } struct Delegation { address holder; // address of token owner uint validatorId; uint amount; uint delegationPeriod; uint created; // time of delegation creation uint started; // month when a delegation becomes active uint finished; // first month after a delegation ends string info; } struct SlashingLogEvent { FractionUtils.Fraction reducingCoefficient; uint nextMonth; } struct SlashingLog { // month => slashing event mapping (uint => SlashingLogEvent) slashes; uint firstMonth; uint lastMonth; } struct DelegationExtras { uint lastSlashingMonthBeforeDelegation; } struct SlashingEvent { FractionUtils.Fraction reducingCoefficient; uint validatorId; uint month; } struct SlashingSignal { address holder; uint penalty; } struct LockedInPending { uint amount; uint month; } struct FirstDelegationMonth { // month uint value; //validatorId => month mapping (uint => uint) byValidator; } struct ValidatorsStatistics { // number of validators uint number; //validatorId => bool - is Delegated or not mapping (uint => uint) delegated; } /** * @dev Emitted when a delegation is proposed to a validator. */ event DelegationProposed( uint delegationId ); /** * @dev Emitted when a delegation is accepted by a validator. */ event DelegationAccepted( uint delegationId ); /** * @dev Emitted when a delegation is cancelled by the delegator. */ event DelegationRequestCanceledByUser( uint delegationId ); /** * @dev Emitted when a delegation is requested to undelegate. */ event UndelegationRequested( uint delegationId ); /// @dev delegations will never be deleted to index in this array may be used like delegation id Delegation[] public delegations; // validatorId => delegationId[] mapping (uint => uint[]) public delegationsByValidator; // holder => delegationId[] mapping (address => uint[]) public delegationsByHolder; // delegationId => extras mapping(uint => DelegationExtras) private _delegationExtras; // validatorId => sequence mapping (uint => PartialDifferences.Value) private _delegatedToValidator; // validatorId => sequence mapping (uint => PartialDifferences.Sequence) private _effectiveDelegatedToValidator; // validatorId => slashing log mapping (uint => SlashingLog) private _slashesOfValidator; // holder => sequence mapping (address => PartialDifferences.Value) private _delegatedByHolder; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Value)) private _delegatedByHolderToValidator; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Sequence)) private _effectiveDelegatedByHolderToValidator; SlashingEvent[] private _slashes; // holder => index in _slashes; mapping (address => uint) private _firstUnprocessedSlashByHolder; // holder => validatorId => month mapping (address => FirstDelegationMonth) private _firstDelegationMonth; // holder => locked in pending mapping (address => LockedInPending) private _lockedInPendingDelegations; mapping (address => ValidatorsStatistics) private _numberOfValidatorsPerDelegator; /** * @dev Modifier to make a function callable only if delegation exists. */ modifier checkDelegationExists(uint delegationId) { require(delegationId < delegations.length, "Delegation does not exist"); _; } /** * @dev Update and return a validator's delegations. */ function getAndUpdateDelegatedToValidatorNow(uint validatorId) external returns (uint) { return _getAndUpdateDelegatedToValidator(validatorId, _getCurrentMonth()); } /** * @dev Update and return the amount delegated. */ function getAndUpdateDelegatedAmount(address holder) external returns (uint) { return _getAndUpdateDelegatedByHolder(holder); } /** * @dev Update and return the effective amount delegated (minus slash) for * the given month. */ function getAndUpdateEffectiveDelegatedByHolderToValidator(address holder, uint validatorId, uint month) external allow("Distributor") returns (uint effectiveDelegated) { SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(holder); effectiveDelegated = _effectiveDelegatedByHolderToValidator[holder][validatorId] .getAndUpdateValueInSequence(month); _sendSlashingSignals(slashingSignals); } /** * @dev Allows a token holder to create a delegation proposal of an `amount` * and `delegationPeriod` to a `validatorId`. Delegation must be accepted * by the validator before the UTC start of the month, otherwise the * delegation will be rejected. * * The token holder may add additional information in each proposal. * * Emits a {DelegationProposed} event. * * Requirements: * * - Holder must have sufficient delegatable tokens. * - Delegation must be above the validator's minimum delegation amount. * - Delegation period must be allowed. * - Validator must be authorized if trusted list is enabled. * - Validator must be accepting new delegation requests. */ function delegate( uint validatorId, uint amount, uint delegationPeriod, string calldata info ) external { require( _getDelegationPeriodManager().isDelegationPeriodAllowed(delegationPeriod), "This delegation period is not allowed"); _getValidatorService().checkValidatorCanReceiveDelegation(validatorId, amount); _checkIfDelegationIsAllowed(msg.sender, validatorId); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(msg.sender); uint delegationId = _addDelegation( msg.sender, validatorId, amount, delegationPeriod, info); // check that there is enough money uint holderBalance = IERC777(contractManager.getSkaleToken()).balanceOf(msg.sender); uint forbiddenForDelegation = TokenState(contractManager.getTokenState()) .getAndUpdateForbiddenForDelegationAmount(msg.sender); require(holderBalance >= forbiddenForDelegation, "Token holder does not have enough tokens to delegate"); emit DelegationProposed(delegationId); _sendSlashingSignals(slashingSignals); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev Allows token holder to cancel a delegation proposal. * * Emits a {DelegationRequestCanceledByUser} event. * * Requirements: * * - `msg.sender` must be the token holder of the delegation proposal. * - Delegation state must be PROPOSED. */ function cancelPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require(msg.sender == delegations[delegationId].holder, "Only token holders can cancel delegation request"); require(getState(delegationId) == State.PROPOSED, "Token holders are only able to cancel PROPOSED delegations"); delegations[delegationId].finished = _getCurrentMonth(); _subtractFromLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); emit DelegationRequestCanceledByUser(delegationId); } /** * @dev Allows a validator to accept a proposed delegation. * Successful acceptance of delegations transition the tokens from a * PROPOSED state to ACCEPTED, and tokens are locked for the remainder of the * delegation period. * * Emits a {DelegationAccepted} event. * * Requirements: * * - Validator must be recipient of proposal. * - Delegation state must be PROPOSED. */ function acceptPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require( _getValidatorService().checkValidatorAddressToId(msg.sender, delegations[delegationId].validatorId), "No permissions to accept request"); _accept(delegationId); } /** * @dev Allows delegator to undelegate a specific delegation. * * Emits UndelegationRequested event. * * Requirements: * * - `msg.sender` must be the delegator. * - Delegation state must be DELEGATED. */ function requestUndelegation(uint delegationId) external checkDelegationExists(delegationId) { require(getState(delegationId) == State.DELEGATED, "Cannot request undelegation"); ValidatorService validatorService = _getValidatorService(); require( delegations[delegationId].holder == msg.sender || (validatorService.validatorAddressExists(msg.sender) && delegations[delegationId].validatorId == validatorService.getValidatorId(msg.sender)), "Permission denied to request undelegation"); _removeValidatorFromValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId); processAllSlashes(msg.sender); delegations[delegationId].finished = _calculateDelegationEndMonth(delegationId); require( now.add(UNDELEGATION_PROHIBITION_WINDOW_SECONDS) < _getTimeHelpers().monthToTimestamp(delegations[delegationId].finished), "Undelegation requests must be sent 3 days before the end of delegation period" ); _subtractFromAllStatistics(delegationId); emit UndelegationRequested(delegationId); } /** * @dev Allows Punisher contract to slash an `amount` of stake from * a validator. This slashes an amount of delegations of the validator, * which reduces the amount that the validator has staked. This consequence * may force the SKALE Manager to reduce the number of nodes a validator is * operating so the validator can meet the Minimum Staking Requirement. * * Emits a {SlashingEvent}. * * See {Punisher}. */ function confiscate(uint validatorId, uint amount) external allow("Punisher") { uint currentMonth = _getCurrentMonth(); FractionUtils.Fraction memory coefficient = _delegatedToValidator[validatorId].reduceValue(amount, currentMonth); uint initialEffectiveDelegated = _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth); uint[] memory initialSubtractions = new uint[](0); if (currentMonth < _effectiveDelegatedToValidator[validatorId].lastChangedMonth) { initialSubtractions = new uint[]( _effectiveDelegatedToValidator[validatorId].lastChangedMonth.sub(currentMonth) ); for (uint i = 0; i < initialSubtractions.length; ++i) { initialSubtractions[i] = _effectiveDelegatedToValidator[validatorId] .subtractDiff[currentMonth.add(i).add(1)]; } } _effectiveDelegatedToValidator[validatorId].reduceSequence(coefficient, currentMonth); _putToSlashingLog(_slashesOfValidator[validatorId], coefficient, currentMonth); _slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth})); BountyV2 bounty = _getBounty(); bounty.handleDelegationRemoving( initialEffectiveDelegated.sub( _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth) ), currentMonth ); for (uint i = 0; i < initialSubtractions.length; ++i) { bounty.handleDelegationAdd( initialSubtractions[i].sub( _effectiveDelegatedToValidator[validatorId].subtractDiff[currentMonth.add(i).add(1)] ), currentMonth.add(i).add(1) ); } } /** * @dev Allows Distributor contract to return and update the effective * amount delegated (minus slash) to a validator for a given month. */ function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month) external allowTwo("Bounty", "Distributor") returns (uint) { return _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(month); } /** * @dev Return and update the amount delegated to a validator for the * current month. */ function getAndUpdateDelegatedByHolderToValidatorNow(address holder, uint validatorId) external returns (uint) { return _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, _getCurrentMonth()); } function getEffectiveDelegatedValuesByValidator(uint validatorId) external view returns (uint[] memory) { return _effectiveDelegatedToValidator[validatorId].getValuesInSequence(); } function getEffectiveDelegatedToValidator(uint validatorId, uint month) external view returns (uint) { return _effectiveDelegatedToValidator[validatorId].getValueInSequence(month); } function getDelegatedToValidator(uint validatorId, uint month) external view returns (uint) { return _delegatedToValidator[validatorId].getValue(month); } /** * @dev Return Delegation struct. */ function getDelegation(uint delegationId) external view checkDelegationExists(delegationId) returns (Delegation memory) { return delegations[delegationId]; } /** * @dev Returns the first delegation month. */ function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint) { return _firstDelegationMonth[holder].byValidator[validatorId]; } /** * @dev Returns a validator's total number of delegations. */ function getDelegationsByValidatorLength(uint validatorId) external view returns (uint) { return delegationsByValidator[validatorId].length; } /** * @dev Returns a holder's total number of delegations. */ function getDelegationsByHolderLength(address holder) external view returns (uint) { return delegationsByHolder[holder].length; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } /** * @dev Process slashes up to the given limit. */ function processSlashes(address holder, uint limit) public { _sendSlashingSignals(_processSlashesWithoutSignals(holder, limit)); } /** * @dev Process all slashes. */ function processAllSlashes(address holder) public { processSlashes(holder, 0); } /** * @dev Returns the token state of a given delegation. */ function getState(uint delegationId) public view checkDelegationExists(delegationId) returns (State state) { if (delegations[delegationId].started == 0) { if (delegations[delegationId].finished == 0) { if (_getCurrentMonth() == _getTimeHelpers().timestampToMonth(delegations[delegationId].created)) { return State.PROPOSED; } else { return State.REJECTED; } } else { return State.CANCELED; } } else { if (_getCurrentMonth() < delegations[delegationId].started) { return State.ACCEPTED; } else { if (delegations[delegationId].finished == 0) { return State.DELEGATED; } else { if (_getCurrentMonth() < delegations[delegationId].finished) { return State.UNDELEGATION_REQUESTED; } else { return State.COMPLETED; } } } } } /** * @dev Returns the amount of tokens in PENDING delegation state. */ function getLockedInPendingDelegations(address holder) public view returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { return 0; } else { return _lockedInPendingDelegations[holder].amount; } } /** * @dev Checks whether there are any unprocessed slashes. */ function hasUnprocessedSlashes(address holder) public view returns (bool) { return _everDelegated(holder) && _firstUnprocessedSlashByHolder[holder] < _slashes.length; } // private /** * @dev Allows Nodes contract to get and update the amount delegated * to validator for a given month. */ function _getAndUpdateDelegatedToValidator(uint validatorId, uint month) private returns (uint) { return _delegatedToValidator[validatorId].getAndUpdateValue(month); } /** * @dev Adds a new delegation proposal. */ function _addDelegation( address holder, uint validatorId, uint amount, uint delegationPeriod, string memory info ) private returns (uint delegationId) { delegationId = delegations.length; delegations.push(Delegation( holder, validatorId, amount, delegationPeriod, now, 0, 0, info )); delegationsByValidator[validatorId].push(delegationId); delegationsByHolder[holder].push(delegationId); _addToLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); } /** * @dev Returns the month when a delegation ends. */ function _calculateDelegationEndMonth(uint delegationId) private view returns (uint) { uint currentMonth = _getCurrentMonth(); uint started = delegations[delegationId].started; if (currentMonth < started) { return started.add(delegations[delegationId].delegationPeriod); } else { uint completedPeriods = currentMonth.sub(started).div(delegations[delegationId].delegationPeriod); return started.add(completedPeriods.add(1).mul(delegations[delegationId].delegationPeriod)); } } function _addToDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].addToValue(amount, month); } function _addToEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].addToSequence(effectiveAmount, month); } function _addToDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].addToValue(amount, month); } function _addToDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].addToValue(amount, month); } function _addValidatorToValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.add(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].add(1); } function _removeFromDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].subtractFromValue(amount, month); } function _removeFromDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].subtractFromValue(amount, month); } function _removeValidatorFromValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 1) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.sub(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].sub(1); } function _addToEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].addToSequence(effectiveAmount, month); } function _removeFromEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].subtractFromSequence(effectiveAmount, month); } function _getAndUpdateDelegatedByHolder(address holder) private returns (uint) { uint currentMonth = _getCurrentMonth(); processAllSlashes(holder); return _delegatedByHolder[holder].getAndUpdateValue(currentMonth); } function _getAndUpdateDelegatedByHolderToValidator( address holder, uint validatorId, uint month) private returns (uint) { return _delegatedByHolderToValidator[holder][validatorId].getAndUpdateValue(month); } function _addToLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { _lockedInPendingDelegations[holder].amount = amount; _lockedInPendingDelegations[holder].month = currentMonth; } else { assert(_lockedInPendingDelegations[holder].month == currentMonth); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.add(amount); } } function _subtractFromLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); assert(_lockedInPendingDelegations[holder].month == currentMonth); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.sub(amount); } function _getCurrentMonth() private view returns (uint) { return _getTimeHelpers().getCurrentMonth(); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function _getAndUpdateLockedAmount(address wallet) private returns (uint) { return _getAndUpdateDelegatedByHolder(wallet).add(getLockedInPendingDelegations(wallet)); } function _updateFirstDelegationMonth(address holder, uint validatorId, uint month) private { if (_firstDelegationMonth[holder].value == 0) { _firstDelegationMonth[holder].value = month; _firstUnprocessedSlashByHolder[holder] = _slashes.length; } if (_firstDelegationMonth[holder].byValidator[validatorId] == 0) { _firstDelegationMonth[holder].byValidator[validatorId] = month; } } /** * @dev Checks whether the holder has performed a delegation. */ function _everDelegated(address holder) private view returns (bool) { return _firstDelegationMonth[holder].value > 0; } function _removeFromDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].subtractFromValue(amount, month); } function _removeFromEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].subtractFromSequence(effectiveAmount, month); } /** * @dev Returns the delegated amount after a slashing event. */ function _calculateDelegationAmountAfterSlashing(uint delegationId) private view returns (uint) { uint startMonth = _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation; uint validatorId = delegations[delegationId].validatorId; uint amount = delegations[delegationId].amount; if (startMonth == 0) { startMonth = _slashesOfValidator[validatorId].firstMonth; if (startMonth == 0) { return amount; } } for (uint i = startMonth; i > 0 && i < delegations[delegationId].finished; i = _slashesOfValidator[validatorId].slashes[i].nextMonth) { if (i >= delegations[delegationId].started) { amount = amount .mul(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.numerator) .div(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.denominator); } } return amount; } function _putToSlashingLog( SlashingLog storage log, FractionUtils.Fraction memory coefficient, uint month) private { if (log.firstMonth == 0) { log.firstMonth = month; log.lastMonth = month; log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; } else { require(log.lastMonth <= month, "Cannot put slashing event in the past"); if (log.lastMonth == month) { log.slashes[month].reducingCoefficient = log.slashes[month].reducingCoefficient.multiplyFraction(coefficient); } else { log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; log.slashes[log.lastMonth].nextMonth = month; log.lastMonth = month; } } } function _processSlashesWithoutSignals(address holder, uint limit) private returns (SlashingSignal[] memory slashingSignals) { if (hasUnprocessedSlashes(holder)) { uint index = _firstUnprocessedSlashByHolder[holder]; uint end = _slashes.length; if (limit > 0 && index.add(limit) < end) { end = index.add(limit); } slashingSignals = new SlashingSignal[](end.sub(index)); uint begin = index; for (; index < end; ++index) { uint validatorId = _slashes[index].validatorId; uint month = _slashes[index].month; uint oldValue = _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month); if (oldValue.muchGreater(0)) { _delegatedByHolderToValidator[holder][validatorId].reduceValueByCoefficientAndUpdateSum( _delegatedByHolder[holder], _slashes[index].reducingCoefficient, month); _effectiveDelegatedByHolderToValidator[holder][validatorId].reduceSequence( _slashes[index].reducingCoefficient, month); slashingSignals[index.sub(begin)].holder = holder; slashingSignals[index.sub(begin)].penalty = oldValue.boundedSub(_getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month)); } } _firstUnprocessedSlashByHolder[holder] = end; } } function _processAllSlashesWithoutSignals(address holder) private returns (SlashingSignal[] memory slashingSignals) { return _processSlashesWithoutSignals(holder, 0); } function _sendSlashingSignals(SlashingSignal[] memory slashingSignals) private { Punisher punisher = Punisher(contractManager.getPunisher()); address previousHolder = address(0); uint accumulatedPenalty = 0; for (uint i = 0; i < slashingSignals.length; ++i) { if (slashingSignals[i].holder != previousHolder) { if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } previousHolder = slashingSignals[i].holder; accumulatedPenalty = slashingSignals[i].penalty; } else { accumulatedPenalty = accumulatedPenalty.add(slashingSignals[i].penalty); } } if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } } function _addToAllStatistics(uint delegationId) private { uint currentMonth = _getCurrentMonth(); delegations[delegationId].started = currentMonth.add(1); if (_slashesOfValidator[delegations[delegationId].validatorId].lastMonth > 0) { _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation = _slashesOfValidator[delegations[delegationId].validatorId].lastMonth; } _addToDelegatedToValidator( delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolder( delegations[delegationId].holder, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _updateFirstDelegationMonth( delegations[delegationId].holder, delegations[delegationId].validatorId, currentMonth.add(1)); uint effectiveAmount = delegations[delegationId].amount.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)); _addToEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addToEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addValidatorToValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId ); } function _subtractFromAllStatistics(uint delegationId) private { uint amountAfterSlashing = _calculateDelegationAmountAfterSlashing(delegationId); _removeFromDelegatedToValidator( delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolder( delegations[delegationId].holder, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); uint effectiveAmount = amountAfterSlashing.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)); _removeFromEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _removeFromEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _getTokenLaunchLocker().handleDelegationRemoving( delegations[delegationId].holder, delegationId, delegations[delegationId].finished); _getBounty().handleDelegationRemoving( effectiveAmount, delegations[delegationId].finished); } /** * @dev Checks whether delegation to a validator is allowed. * * Requirements: * * - Delegator must not have reached the validator limit. * - Delegation must be made in or after the first delegation month. */ function _checkIfDelegationIsAllowed(address holder, uint validatorId) private view returns (bool) { require( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] > 0 || ( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0 && _numberOfValidatorsPerDelegator[holder].number < _getConstantsHolder().limitValidatorsPerDelegator() ), "Limit of validators is reached" ); } function _getDelegationPeriodManager() private view returns (DelegationPeriodManager) { return DelegationPeriodManager(contractManager.getDelegationPeriodManager()); } function _getBounty() private view returns (BountyV2) { return BountyV2(contractManager.getBounty()); } function _getValidatorService() private view returns (ValidatorService) { return ValidatorService(contractManager.getValidatorService()); } function _getTimeHelpers() private view returns (TimeHelpers) { return TimeHelpers(contractManager.getTimeHelpers()); } function _getTokenLaunchLocker() private view returns (TokenLaunchLocker) { return TokenLaunchLocker(contractManager.getTokenLaunchLocker()); } function _getConstantsHolder() private view returns (ConstantsHolder) { return ConstantsHolder(contractManager.getConstantsHolder()); } function _accept(uint delegationId) private { _checkIfDelegationIsAllowed(delegations[delegationId].holder, delegations[delegationId].validatorId); State currentState = getState(delegationId); if (currentState != State.PROPOSED) { if (currentState == State.ACCEPTED || currentState == State.DELEGATED || currentState == State.UNDELEGATION_REQUESTED || currentState == State.COMPLETED) { revert("The delegation has been already accepted"); } else if (currentState == State.CANCELED) { revert("The delegation has been cancelled by token holder"); } else if (currentState == State.REJECTED) { revert("The delegation request is outdated"); } } require(currentState == State.PROPOSED, "Cannot set delegation state to accepted"); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(delegations[delegationId].holder); _addToAllStatistics(delegationId); uint amount = delegations[delegationId].amount; _getTokenLaunchLocker().handleDelegationAdd( delegations[delegationId].holder, delegationId, amount, delegations[delegationId].started ); uint effectiveAmount = amount.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod) ); _getBounty().handleDelegationAdd( effectiveAmount, delegations[delegationId].started ); _sendSlashingSignals(slashingSignals); emit DelegationAccepted(delegationId); } } // SPDX-License-Identifier: AGPL-3.0-only /* DelegationPeriodManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../Permissions.sol"; /** * @title Delegation Period Manager * @dev This contract handles all delegation offerings. Delegations are held for * a specified period (months), and different durations can have different * returns or `stakeMultiplier`. Currently, only delegation periods can be added. */ contract DelegationPeriodManager is Permissions { mapping (uint => uint) public stakeMultipliers; /** * @dev Emitted when a new delegation period is specified. */ event DelegationPeriodWasSet( uint length, uint stakeMultiplier ); /** * @dev Allows the Owner to create a new available delegation period and * stake multiplier in the network. * * Emits a {DelegationPeriodWasSet} event. */ function setDelegationPeriod(uint monthsCount, uint stakeMultiplier) external onlyOwner { require(stakeMultipliers[monthsCount] == 0, "Delegation perios is already set"); stakeMultipliers[monthsCount] = stakeMultiplier; emit DelegationPeriodWasSet(monthsCount, stakeMultiplier); } /** * @dev Checks whether given delegation period is allowed. */ function isDelegationPeriodAllowed(uint monthsCount) external view returns (bool) { return stakeMultipliers[monthsCount] != 0; } /** * @dev Initial delegation period and multiplier settings. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); stakeMultipliers[2] = 100; // 2 months at 100 // stakeMultipliers[6] = 150; // 6 months at 150 // stakeMultipliers[12] = 200; // 12 months at 200 } } // SPDX-License-Identifier: AGPL-3.0-only /* PartialDifferences.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../utils/MathUtils.sol"; import "../utils/FractionUtils.sol"; /** * @title Partial Differences Library * @dev This library contains functions to manage Partial Differences data * structure. Partial Differences is an array of value differences over time. * * For example: assuming an array [3, 6, 3, 1, 2], partial differences can * represent this array as [_, 3, -3, -2, 1]. * * This data structure allows adding values on an open interval with O(1) * complexity. * * For example: add +5 to [3, 6, 3, 1, 2] starting from the second element (3), * instead of performing [3, 6, 3+5, 1+5, 2+5] partial differences allows * performing [_, 3, -3+5, -2, 1]. The original array can be restored by * adding values from partial differences. */ library PartialDifferences { using SafeMath for uint; using MathUtils for uint; struct Sequence { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; // month => value mapping (uint => uint) value; uint firstUnprocessedMonth; uint lastChangedMonth; } struct Value { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; uint value; uint firstUnprocessedMonth; uint lastChangedMonth; } // functions for sequence function addToSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.addDiff[month] = sequence.addDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function subtractFromSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function getAndUpdateValueInSequence(Sequence storage sequence, uint month) internal returns (uint) { if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { uint nextValue = sequence.value[i.sub(1)].add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.value[i] != nextValue) { sequence.value[i] = nextValue; } if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value[month]; } function getValueInSequence(Sequence storage sequence, uint month) internal view returns (uint) { if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value[sequence.firstUnprocessedMonth.sub(1)]; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]); } return value; } else { return sequence.value[month]; } } function getValuesInSequence(Sequence storage sequence) internal view returns (uint[] memory values) { if (sequence.firstUnprocessedMonth == 0) { return values; } uint begin = sequence.firstUnprocessedMonth.sub(1); uint end = sequence.lastChangedMonth.add(1); if (end <= begin) { end = begin.add(1); } values = new uint[](end.sub(begin)); values[0] = sequence.value[sequence.firstUnprocessedMonth.sub(1)]; for (uint i = 0; i.add(1) < values.length; ++i) { uint month = sequence.firstUnprocessedMonth.add(i); values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]); } } function reduceSequence( Sequence storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValueInSequence(sequence, month); if (value.approximatelyEqual(0)) { return; } sequence.value[month] = sequence.value[month] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { sequence.subtractDiff[i] = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); } } // functions for value function addToValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.addDiff[month] = sequence.addDiff[month].add(diff); } else { sequence.value = sequence.value.add(diff); } } function subtractFromValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month.add(1), "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); } else { sequence.value = sequence.value.boundedSub(diff); } } function getAndUpdateValue(Value storage sequence, uint month) internal returns (uint) { require( month.add(1) >= sequence.firstUnprocessedMonth, "Cannot calculate value in the past"); if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } if (sequence.value != value) { sequence.value = value; } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value; } function getValue(Value storage sequence, uint month) internal view returns (uint) { require( month.add(1) >= sequence.firstUnprocessedMonth, "Cannot calculate value in the past"); if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]); } return value; } else { return sequence.value; } } function getValues(Value storage sequence) internal view returns (uint[] memory values) { if (sequence.firstUnprocessedMonth == 0) { return values; } uint begin = sequence.firstUnprocessedMonth.sub(1); uint end = sequence.lastChangedMonth.add(1); if (end <= begin) { end = begin.add(1); } values = new uint[](end.sub(begin)); values[0] = sequence.value; for (uint i = 0; i.add(1) < values.length; ++i) { uint month = sequence.firstUnprocessedMonth.add(i); values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]); } } function reduceValue( Value storage sequence, uint amount, uint month) internal returns (FractionUtils.Fraction memory) { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (sequence.firstUnprocessedMonth == 0) { return FractionUtils.createFraction(0); } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return FractionUtils.createFraction(0); } uint _amount = amount; if (value < amount) { _amount = value; } FractionUtils.Fraction memory reducingCoefficient = FractionUtils.createFraction(value.boundedSub(_amount), value); reduceValueByCoefficient(sequence, reducingCoefficient, month); return reducingCoefficient; } function reduceValueByCoefficient( Value storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sequence, reducingCoefficient, month, false); } function reduceValueByCoefficientAndUpdateSum( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sumSequence, reducingCoefficient, month, true); } function reduceValueByCoefficientAndUpdateSumIfNeeded( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month, bool hasSumSequence) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (hasSumSequence) { require(month.add(1) >= sumSequence.firstUnprocessedMonth, "Cannot reduce value in the past"); } require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return; } uint newValue = sequence.value.mul(reducingCoefficient.numerator).div(reducingCoefficient.denominator); if (hasSumSequence) { subtractFromValue(sumSequence, sequence.value.boundedSub(newValue), month); } sequence.value = newValue; for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { uint newDiff = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); if (hasSumSequence) { sumSequence.subtractDiff[i] = sumSequence.subtractDiff[i] .boundedSub(sequence.subtractDiff[i].boundedSub(newDiff)); } sequence.subtractDiff[i] = newDiff; } } function clear(Value storage sequence) internal { for (uint i = sequence.firstUnprocessedMonth; i <= sequence.lastChangedMonth; ++i) { if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } if (sequence.value > 0) { delete sequence.value; } if (sequence.firstUnprocessedMonth > 0) { delete sequence.firstUnprocessedMonth; } if (sequence.lastChangedMonth > 0) { delete sequence.lastChangedMonth; } } } // SPDX-License-Identifier: AGPL-3.0-only /* Punisher.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../Permissions.sol"; import "../interfaces/delegation/ILocker.sol"; import "./ValidatorService.sol"; import "./DelegationController.sol"; /** * @title Punisher * @dev This contract handles all slashing and forgiving operations. */ contract Punisher is Permissions, ILocker { // holder => tokens mapping (address => uint) private _locked; /** * @dev Emitted upon slashing condition. */ event Slash( uint validatorId, uint amount ); /** * @dev Emitted upon forgive condition. */ event Forgive( address wallet, uint amount ); /** * @dev Allows SkaleDKG contract to execute slashing on a validator and * validator's delegations by an `amount` of tokens. * * Emits a {Slash} event. * * Requirements: * * - Validator must exist. */ function slash(uint validatorId, uint amount) external allow("SkaleDKG") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(validatorService.validatorExists(validatorId), "Validator does not exist"); delegationController.confiscate(validatorId, amount); emit Slash(validatorId, amount); } /** * @dev Allows the Admin to forgive a slashing condition. * * Emits a {Forgive} event. * * Requirements: * * - All slashes must have been processed. */ function forgive(address holder, uint amount) external onlyAdmin { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(!delegationController.hasUnprocessedSlashes(holder), "Not all slashes were calculated"); if (amount > _locked[holder]) { delete _locked[holder]; } else { _locked[holder] = _locked[holder].sub(amount); } emit Forgive(holder, amount); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev Allows DelegationController contract to execute slashing of * delegations. */ function handleSlash(address holder, uint amount) external allow("DelegationController") { _locked[holder] = _locked[holder].add(amount); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } // private /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function _getAndUpdateLockedAmount(address wallet) private returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); delegationController.processAllSlashes(wallet); return _locked[wallet]; } } // SPDX-License-Identifier: AGPL-3.0-only /* TimeHelpers.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../thirdparty/BokkyPooBahsDateTimeLibrary.sol"; /** * @title TimeHelpers * @dev The contract performs time operations. * * These functions are used to calculate monthly and Proof of Use epochs. */ contract TimeHelpers { using SafeMath for uint; uint constant private _ZERO_YEAR = 2020; function calculateProofOfUseLockEndTime(uint month, uint lockUpPeriodDays) external view returns (uint timestamp) { timestamp = BokkyPooBahsDateTimeLibrary.addDays(monthToTimestamp(month), lockUpPeriodDays); } function addDays(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addDays(fromTimestamp, n); } function addMonths(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addMonths(fromTimestamp, n); } function addYears(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addYears(fromTimestamp, n); } function getCurrentMonth() external view virtual returns (uint) { return timestampToMonth(now); } function timestampToDay(uint timestamp) external view returns (uint) { uint wholeDays = timestamp / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; uint zeroDay = BokkyPooBahsDateTimeLibrary.timestampFromDate(_ZERO_YEAR, 1, 1) / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; require(wholeDays >= zeroDay, "Timestamp is too far in the past"); return wholeDays - zeroDay; } function timestampToYear(uint timestamp) external view virtual returns (uint) { uint year; (year, , ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); return year - _ZERO_YEAR; } function timestampToMonth(uint timestamp) public view virtual returns (uint) { uint year; uint month; (year, month, ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); month = month.sub(1).add(year.sub(_ZERO_YEAR).mul(12)); require(month > 0, "Timestamp is too far in the past"); return month; } function monthToTimestamp(uint month) public view virtual returns (uint timestamp) { uint year = _ZERO_YEAR; uint _month = month; year = year.add(_month.div(12)); _month = _month.mod(12); _month = _month.add(1); return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, _month, 1); } } // SPDX-License-Identifier: AGPL-3.0-only /* TokenLaunchLocker.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../Permissions.sol"; import "../interfaces/delegation/ILocker.sol"; import "../ConstantsHolder.sol"; import "../utils/MathUtils.sol"; import "./DelegationController.sol"; import "./TimeHelpers.sol"; import "./PartialDifferences.sol"; /** * @title TokenLaunchLocker * @dev This contract manages lockers applied to the launch process. */ contract TokenLaunchLocker is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Value; /** * @dev Emitted when an `amount` is unlocked. */ event Unlocked( address holder, uint amount ); /** * @dev Emitted when an `amount` is locked. */ event Locked( address holder, uint amount ); struct DelegatedAmountAndMonth { uint delegated; uint month; } // holder => tokens mapping (address => uint) private _locked; // holder => tokens mapping (address => PartialDifferences.Value) private _delegatedAmount; mapping (address => DelegatedAmountAndMonth) private _totalDelegatedAmount; // delegationId => tokens mapping (uint => uint) private _delegationAmount; /** * @dev Allows TokenLaunchManager contract to lock an amount of tokens in a * holder wallet. * * Emits a {Locked} event. */ function lock(address holder, uint amount) external allow("TokenLaunchManager") { _locked[holder] = _locked[holder].add(amount); emit Locked(holder, amount); } /** * @dev Allows DelegationController contract to notify TokenLaunchLocker * about new delegations. */ function handleDelegationAdd( address holder, uint delegationId, uint amount, uint month) external allow("DelegationController") { if (_locked[holder] > 0) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint fromLocked = amount; uint locked = _locked[holder].boundedSub(_getAndUpdateDelegatedAmount(holder, currentMonth)); if (fromLocked > locked) { fromLocked = locked; } if (fromLocked > 0) { require(_delegationAmount[delegationId] == 0, "Delegation was already added"); _addToDelegatedAmount(holder, fromLocked, month); _addToTotalDelegatedAmount(holder, fromLocked, month); _delegationAmount[delegationId] = fromLocked; } } } /** * @dev Allows DelegationController contract to notify TokenLaunchLocker * about new undelegation requests. */ function handleDelegationRemoving( address holder, uint delegationId, uint month) external allow("DelegationController") { if (_delegationAmount[delegationId] > 0) { if (_locked[holder] > 0) { _removeFromDelegatedAmount(holder, _delegationAmount[delegationId], month); } delete _delegationAmount[delegationId]; } } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { if (_locked[wallet] > 0) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint currentMonth = timeHelpers.getCurrentMonth(); if (_totalDelegatedSatisfiesProofOfUseCondition(wallet) && timeHelpers.calculateProofOfUseLockEndTime( _totalDelegatedAmount[wallet].month, constantsHolder.proofOfUseLockUpPeriodDays() ) <= now) { _unlock(wallet); return 0; } else { uint lockedByDelegationController = _getAndUpdateDelegatedAmount(wallet, currentMonth) .add(delegationController.getLockedInPendingDelegations(wallet)); if (_locked[wallet] > lockedByDelegationController) { return _locked[wallet].boundedSub(lockedByDelegationController); } else { return 0; } } } else { return 0; } } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address) external override returns (uint) { return 0; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } // private /** * @dev Returns and updates the current delegated amount. */ function _getAndUpdateDelegatedAmount(address holder, uint currentMonth) private returns (uint) { return _delegatedAmount[holder].getAndUpdateValue(currentMonth); } /** * @dev Adds a delegated amount to the given month. */ function _addToDelegatedAmount(address holder, uint amount, uint month) private { _delegatedAmount[holder].addToValue(amount, month); } /** * @dev Removes a delegated amount from the given month. */ function _removeFromDelegatedAmount(address holder, uint amount, uint month) private { _delegatedAmount[holder].subtractFromValue(amount, month); } /** * @dev Adds the amount to the total delegated for the given month. */ function _addToTotalDelegatedAmount(address holder, uint amount, uint month) private { require( _totalDelegatedAmount[holder].month == 0 || _totalDelegatedAmount[holder].month <= month, "Cannot add to total delegated in the past"); // do not update counter if it is big enough // because it will override month value if (!_totalDelegatedSatisfiesProofOfUseCondition(holder)) { _totalDelegatedAmount[holder].delegated = _totalDelegatedAmount[holder].delegated.add(amount); _totalDelegatedAmount[holder].month = month; } } /** * @dev Unlocks tokens. * * Emits an {Unlocked} event. */ function _unlock(address holder) private { emit Unlocked(holder, _locked[holder]); delete _locked[holder]; _deleteDelegatedAmount(holder); _deleteTotalDelegatedAmount(holder); } /** * @dev Deletes the delegated amount. */ function _deleteDelegatedAmount(address holder) private { _delegatedAmount[holder].clear(); } /** * @dev Deletes the total delegated amount. */ function _deleteTotalDelegatedAmount(address holder) private { delete _totalDelegatedAmount[holder].delegated; delete _totalDelegatedAmount[holder].month; } /** * @dev Checks whether total delegated satisfies Proof-of-Use. */ function _totalDelegatedSatisfiesProofOfUseCondition(address holder) private view returns (bool) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return _totalDelegatedAmount[holder].delegated.mul(100) >= _locked[holder].mul(constantsHolder.proofOfUseDelegationPercentage()); } } // SPDX-License-Identifier: AGPL-3.0-only /* TokenState.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../interfaces/delegation/ILocker.sol"; import "../Permissions.sol"; import "./DelegationController.sol"; import "./TimeHelpers.sol"; /** * @title Token State * @dev This contract manages lockers to control token transferability. * * The SKALE Network has three types of locked tokens: * * - Tokens that are transferrable but are currently locked into delegation with * a validator. * * - Tokens that are not transferable from one address to another, but may be * delegated to a validator `getAndUpdateLockedAmount`. This lock enforces * Proof-of-Use requirements. * * - Tokens that are neither transferable nor delegatable * `getAndUpdateForbiddenForDelegationAmount`. This lock enforces slashing. */ contract TokenState is Permissions, ILocker { string[] private _lockers; DelegationController private _delegationController; /** * @dev Emitted when a contract is added to the locker. */ event LockerWasAdded( string locker ); /** * @dev Emitted when a contract is removed from the locker. */ event LockerWasRemoved( string locker ); /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address holder) external override returns (uint) { if (address(_delegationController) == address(0)) { _delegationController = DelegationController(contractManager.getContract("DelegationController")); } uint locked = 0; if (_delegationController.getDelegationsByHolderLength(holder) > 0) { // the holder ever delegated for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); locked = locked.add(locker.getAndUpdateLockedAmount(holder)); } } return locked; } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address holder) external override returns (uint amount) { uint forbidden = 0; for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); forbidden = forbidden.add(locker.getAndUpdateForbiddenForDelegationAmount(holder)); } return forbidden; } /** * @dev Allows the Owner to remove a contract from the locker. * * Emits a {LockerWasRemoved} event. */ function removeLocker(string calldata locker) external onlyOwner { uint index; bytes32 hash = keccak256(abi.encodePacked(locker)); for (index = 0; index < _lockers.length; ++index) { if (keccak256(abi.encodePacked(_lockers[index])) == hash) { break; } } if (index < _lockers.length) { if (index < _lockers.length.sub(1)) { _lockers[index] = _lockers[_lockers.length.sub(1)]; } delete _lockers[_lockers.length.sub(1)]; _lockers.pop(); emit LockerWasRemoved(locker); } } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); addLocker("DelegationController"); addLocker("Punisher"); addLocker("TokenLaunchLocker"); } /** * @dev Allows the Owner to add a contract to the Locker. * * Emits a {LockerWasAdded} event. */ function addLocker(string memory locker) public onlyOwner { _lockers.push(locker); emit LockerWasAdded(locker); } } // SPDX-License-Identifier: AGPL-3.0-only /* ValidatorService.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/cryptography/ECDSA.sol"; import "../Permissions.sol"; import "../ConstantsHolder.sol"; import "./DelegationController.sol"; import "./TimeHelpers.sol"; /** * @title ValidatorService * @dev This contract handles all validator operations including registration, * node management, validator-specific delegation parameters, and more. * * TIP: For more information see our main instructions * https://forum.skale.network/t/skale-mainnet-launch-faq/182[SKALE MainNet Launch FAQ]. * * Validators register an address, and use this address to accept delegations and * register nodes. */ contract ValidatorService is Permissions { using ECDSA for bytes32; struct Validator { string name; address validatorAddress; address requestedAddress; string description; uint feeRate; uint registrationTime; uint minimumDelegationAmount; bool acceptNewRequests; } /** * @dev Emitted when a validator registers. */ event ValidatorRegistered( uint validatorId ); /** * @dev Emitted when a validator address changes. */ event ValidatorAddressChanged( uint validatorId, address newAddress ); /** * @dev Emitted when a validator is enabled. */ event ValidatorWasEnabled( uint validatorId ); /** * @dev Emitted when a validator is disabled. */ event ValidatorWasDisabled( uint validatorId ); /** * @dev Emitted when a node address is linked to a validator. */ event NodeAddressWasAdded( uint validatorId, address nodeAddress ); /** * @dev Emitted when a node address is unlinked from a validator. */ event NodeAddressWasRemoved( uint validatorId, address nodeAddress ); mapping (uint => Validator) public validators; mapping (uint => bool) private _trustedValidators; uint[] public trustedValidatorsList; // address => validatorId mapping (address => uint) private _validatorAddressToId; // address => validatorId mapping (address => uint) private _nodeAddressToValidatorId; // validatorId => nodeAddress[] mapping (uint => address[]) private _nodeAddresses; uint public numberOfValidators; bool public useWhitelist; modifier checkValidatorExists(uint validatorId) { require(validatorExists(validatorId), "Validator with such ID does not exist"); _; } /** * @dev Creates a new validator ID that includes a validator name, description, * commission or fee rate, and a minimum delegation amount accepted by the validator. * * Emits a {ValidatorRegistered} event. * * Requirements: * * - Sender must not already have registered a validator ID. * - Fee rate must be between 0 - 1000‰. Note: in per mille. */ function registerValidator( string calldata name, string calldata description, uint feeRate, uint minimumDelegationAmount ) external returns (uint validatorId) { require(!validatorAddressExists(msg.sender), "Validator with such address already exists"); require(feeRate <= 1000, "Fee rate of validator should be lower than 100%"); validatorId = ++numberOfValidators; validators[validatorId] = Validator( name, msg.sender, address(0), description, feeRate, now, minimumDelegationAmount, true ); _setValidatorAddress(validatorId, msg.sender); emit ValidatorRegistered(validatorId); } /** * @dev Allows Admin to enable a validator by adding their ID to the * trusted list. * * Emits a {ValidatorWasEnabled} event. * * Requirements: * * - Validator must not already be enabled. */ function enableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin { require(!_trustedValidators[validatorId], "Validator is already enabled"); _trustedValidators[validatorId] = true; trustedValidatorsList.push(validatorId); emit ValidatorWasEnabled(validatorId); } /** * @dev Allows Admin to disable a validator by removing their ID from * the trusted list. * * Emits a {ValidatorWasDisabled} event. * * Requirements: * * - Validator must not already be disabled. */ function disableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin { require(_trustedValidators[validatorId], "Validator is already disabled"); _trustedValidators[validatorId] = false; uint position = _find(trustedValidatorsList, validatorId); if (position < trustedValidatorsList.length) { trustedValidatorsList[position] = trustedValidatorsList[trustedValidatorsList.length.sub(1)]; } trustedValidatorsList.pop(); emit ValidatorWasDisabled(validatorId); } /** * @dev Owner can disable the trusted validator list. Once turned off, the * trusted list cannot be re-enabled. */ function disableWhitelist() external onlyOwner { useWhitelist = false; } /** * @dev Allows `msg.sender` to request a new address. * * Requirements: * * - `msg.sender` must already be a validator. * - New address must not be null. * - New address must not be already registered as a validator. */ function requestForNewAddress(address newValidatorAddress) external { require(newValidatorAddress != address(0), "New address cannot be null"); require(_validatorAddressToId[newValidatorAddress] == 0, "Address already registered"); // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].requestedAddress = newValidatorAddress; } /** * @dev Allows msg.sender to confirm an address change. * * Emits a {ValidatorAddressChanged} event. * * Requirements: * * - Must be owner of new address. */ function confirmNewAddress(uint validatorId) external checkValidatorExists(validatorId) { require( getValidator(validatorId).requestedAddress == msg.sender, "The validator address cannot be changed because it is not the actual owner" ); delete validators[validatorId].requestedAddress; _setValidatorAddress(validatorId, msg.sender); emit ValidatorAddressChanged(validatorId, validators[validatorId].validatorAddress); } /** * @dev Links a node address to validator ID. Validator must present * the node signature of the validator ID. * * Requirements: * * - Signature must be valid. * - Address must not be assigned to a validator. */ function linkNodeAddress(address nodeAddress, bytes calldata sig) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require( keccak256(abi.encodePacked(validatorId)).toEthSignedMessageHash().recover(sig) == nodeAddress, "Signature is not pass" ); require(_validatorAddressToId[nodeAddress] == 0, "Node address is a validator"); _addNodeAddress(validatorId, nodeAddress); emit NodeAddressWasAdded(validatorId, nodeAddress); } /** * @dev Unlinks a node address from a validator. * * Emits a {NodeAddressWasRemoved} event. */ function unlinkNodeAddress(address nodeAddress) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); this.removeNodeAddress(validatorId, nodeAddress); emit NodeAddressWasRemoved(validatorId, nodeAddress); } /** * @dev Allows a validator to set a minimum delegation amount. */ function setValidatorMDA(uint minimumDelegationAmount) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].minimumDelegationAmount = minimumDelegationAmount; } /** * @dev Allows a validator to set a new validator name. */ function setValidatorName(string calldata newName) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].name = newName; } /** * @dev Allows a validator to set a new validator description. */ function setValidatorDescription(string calldata newDescription) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].description = newDescription; } /** * @dev Allows a validator to start accepting new delegation requests. * * Requirements: * * - Must not have already enabled accepting new requests. */ function startAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(!isAcceptingNewRequests(validatorId), "Accepting request is already enabled"); validators[validatorId].acceptNewRequests = true; } /** * @dev Allows a validator to stop accepting new delegation requests. * * Requirements: * * - Must not have already stopped accepting new requests. */ function stopAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(isAcceptingNewRequests(validatorId), "Accepting request is already disabled"); validators[validatorId].acceptNewRequests = false; } function removeNodeAddress(uint validatorId, address nodeAddress) external allowTwo("ValidatorService", "Nodes") { require(_nodeAddressToValidatorId[nodeAddress] == validatorId, "Validator does not have permissions to unlink node"); delete _nodeAddressToValidatorId[nodeAddress]; for (uint i = 0; i < _nodeAddresses[validatorId].length; ++i) { if (_nodeAddresses[validatorId][i] == nodeAddress) { if (i + 1 < _nodeAddresses[validatorId].length) { _nodeAddresses[validatorId][i] = _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; } delete _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; _nodeAddresses[validatorId].pop(); break; } } } /** * @dev Returns the amount of validator bond (self-delegation). */ function getAndUpdateBondAmount(uint validatorId) external returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); return delegationController.getAndUpdateDelegatedByHolderToValidatorNow( getValidator(validatorId).validatorAddress, validatorId ); } /** * @dev Returns node addresses linked to the msg.sender. */ function getMyNodesAddresses() external view returns (address[] memory) { return getNodeAddresses(getValidatorId(msg.sender)); } /** * @dev Returns the list of trusted validators. */ function getTrustedValidators() external view returns (uint[] memory) { return trustedValidatorsList; } /** * @dev Checks whether the validator ID is linked to the validator address. */ function checkValidatorAddressToId(address validatorAddress, uint validatorId) external view returns (bool) { return getValidatorId(validatorAddress) == validatorId ? true : false; } /** * @dev Returns the validator ID linked to a node address. * * Requirements: * * - Node address must be linked to a validator. */ function getValidatorIdByNodeAddress(address nodeAddress) external view returns (uint validatorId) { validatorId = _nodeAddressToValidatorId[nodeAddress]; require(validatorId != 0, "Node address is not assigned to a validator"); } function checkValidatorCanReceiveDelegation(uint validatorId, uint amount) external view { require(isAuthorizedValidator(validatorId), "Validator is not authorized to accept delegation request"); require(isAcceptingNewRequests(validatorId), "The validator is not currently accepting new requests"); require( validators[validatorId].minimumDelegationAmount <= amount, "Amount does not meet the validator's minimum delegation amount" ); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); useWhitelist = true; } /** * @dev Returns a validator's node addresses. */ function getNodeAddresses(uint validatorId) public view returns (address[] memory) { return _nodeAddresses[validatorId]; } /** * @dev Checks whether validator ID exists. */ function validatorExists(uint validatorId) public view returns (bool) { return validatorId <= numberOfValidators && validatorId != 0; } /** * @dev Checks whether validator address exists. */ function validatorAddressExists(address validatorAddress) public view returns (bool) { return _validatorAddressToId[validatorAddress] != 0; } /** * @dev Checks whether validator address exists. */ function checkIfValidatorAddressExists(address validatorAddress) public view { require(validatorAddressExists(validatorAddress), "Validator address does not exist"); } /** * @dev Returns the Validator struct. */ function getValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (Validator memory) { return validators[validatorId]; } /** * @dev Returns the validator ID for the given validator address. */ function getValidatorId(address validatorAddress) public view returns (uint) { checkIfValidatorAddressExists(validatorAddress); return _validatorAddressToId[validatorAddress]; } /** * @dev Checks whether the validator is currently accepting new delegation requests. */ function isAcceptingNewRequests(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) { return validators[validatorId].acceptNewRequests; } function isAuthorizedValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) { return _trustedValidators[validatorId] || !useWhitelist; } // private /** * @dev Links a validator address to a validator ID. * * Requirements: * * - Address is not already in use by another validator. */ function _setValidatorAddress(uint validatorId, address validatorAddress) private { if (_validatorAddressToId[validatorAddress] == validatorId) { return; } require(_validatorAddressToId[validatorAddress] == 0, "Address is in use by another validator"); address oldAddress = validators[validatorId].validatorAddress; delete _validatorAddressToId[oldAddress]; _nodeAddressToValidatorId[validatorAddress] = validatorId; validators[validatorId].validatorAddress = validatorAddress; _validatorAddressToId[validatorAddress] = validatorId; } /** * @dev Links a node address to a validator ID. * * Requirements: * * - Node address must not be already linked to a validator. */ function _addNodeAddress(uint validatorId, address nodeAddress) private { if (_nodeAddressToValidatorId[nodeAddress] == validatorId) { return; } require(_nodeAddressToValidatorId[nodeAddress] == 0, "Validator cannot override node address"); _nodeAddressToValidatorId[nodeAddress] = validatorId; _nodeAddresses[validatorId].push(nodeAddress); } function _find(uint[] memory array, uint index) private pure returns (uint) { uint i; for (i = 0; i < array.length; i++) { if (array[i] == index) { return i; } } return array.length; } } // SPDX-License-Identifier: AGPL-3.0-only /* ISkaleDKG.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface to {SkaleDKG}. */ interface ISkaleDKG { /** * @dev See {SkaleDKG-openChannel}. */ function openChannel(bytes32 schainId) external; /** * @dev See {SkaleDKG-deleteChannel}. */ function deleteChannel(bytes32 schainId) external; /** * @dev See {SkaleDKG-isLastDKGSuccessful}. */ function isLastDKGSuccessful(bytes32 groupIndex) external view returns (bool); /** * @dev See {SkaleDKG-isChannelOpened}. */ function isChannelOpened(bytes32 schainId) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /* ILocker.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface of the Locker functions. */ interface ILocker { /** * @dev Returns and updates the total amount of locked tokens of a given * `holder`. */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Returns and updates the total non-transferrable and un-delegatable * amount of a given `holder`. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint); } pragma solidity ^0.6.0; // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.01 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence. // ---------------------------------------------------------------------------- library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { uint year; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { uint year; uint month; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } // SPDX-License-Identifier: GPL-3.0-or-later /* Modifications Copyright (C) 2018 SKALE Labs ec.sol by @jbaylina under GPL-3.0 License */ /** @file ECDH.sol * @author Jordi Baylina (@jbaylina) * @date 2016 */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; /** * @title ECDH * @dev This contract performs Elliptic-curve Diffie-Hellman key exchange to * support the DKG process. */ contract ECDH { using SafeMath for uint256; uint256 constant private _GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798; uint256 constant private _GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8; uint256 constant private _N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; uint256 constant private _A = 0; function publicKey(uint256 privKey) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, _GX, _GY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function deriveKey( uint256 privKey, uint256 pubX, uint256 pubY ) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, pubX, pubY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function jAdd( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(x2, z1, _N), _N), mulmod(z1, z2, _N)); } function jSub( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(_N.sub(x2), z1, _N), _N), mulmod(z1, z2, _N)); } function jMul( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, x2, _N), mulmod(z1, z2, _N)); } function jDiv( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, z2, _N), mulmod(z1, x2, _N)); } function inverse(uint256 a) public pure returns (uint256 invA) { require(a > 0 && a < _N, "Input is incorrect"); uint256 t = 0; uint256 newT = 1; uint256 r = _N; uint256 newR = a; uint256 q; while (newR != 0) { q = r.div(newR); (t, newT) = (newT, addmod(t, (_N.sub(mulmod(q, newT, _N))), _N)); (r, newR) = (newR, r % newR); } return t; } function ecAdd( uint256 x1, uint256 y1, uint256 z1, uint256 x2, uint256 y2, uint256 z2 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 ln; uint256 lz; uint256 da; uint256 db; // we use (0 0 1) as zero point, z always equal 1 if ((x1 == 0) && (y1 == 0)) { return (x2, y2, z2); } // we use (0 0 1) as zero point, z always equal 1 if ((x2 == 0) && (y2 == 0)) { return (x1, y1, z1); } if ((x1 == x2) && (y1 == y2)) { (ln, lz) = jMul(x1, z1, x1, z1); (ln, lz) = jMul(ln,lz,3,1); (ln, lz) = jAdd(ln,lz,_A,1); (da, db) = jMul(y1,z1,2,1); } else { (ln, lz) = jSub(y2,z2,y1,z1); (da, db) = jSub(x2,z2,x1,z1); } (ln, lz) = jDiv(ln,lz,da,db); (x3, da) = jMul(ln,lz,ln,lz); (x3, da) = jSub(x3,da,x1,z1); (x3, da) = jSub(x3,da,x2,z2); (y3, db) = jSub(x1,z1,x3,da); (y3, db) = jMul(y3,db,ln,lz); (y3, db) = jSub(y3,db,y1,z1); if (da != db) { x3 = mulmod(x3, db, _N); y3 = mulmod(y3, da, _N); z3 = mulmod(da, db, _N); } else { z3 = da; } } function ecDouble( uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { (x3, y3, z3) = ecAdd( x1, y1, z1, x1, y1, z1 ); } function ecMul( uint256 d, uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 remaining = d; uint256 px = x1; uint256 py = y1; uint256 pz = z1; uint256 acx = 0; uint256 acy = 0; uint256 acz = 1; if (d == 0) { return (0, 0, 1); } while (remaining != 0) { if ((remaining & 1) != 0) { (acx, acy, acz) = ecAdd( acx, acy, acz, px, py, pz ); } remaining = remaining.div(2); (px, py, pz) = ecDouble(px, py, pz); } (x3, y3, z3) = (acx, acy, acz); } } // SPDX-License-Identifier: AGPL-3.0-only /* FieldOperations.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "./Precompiled.sol"; library Fp2Operations { using SafeMath for uint; struct Fp2Point { uint a; uint b; } uint constant public P = 21888242871839275222246405745257275088696311157297823662689037894645226208583; function addFp2(Fp2Point memory value1, Fp2Point memory value2) internal pure returns (Fp2Point memory) { return Fp2Point({ a: addmod(value1.a, value2.a, P), b: addmod(value1.b, value2.b, P) }); } function scalarMulFp2(Fp2Point memory value, uint scalar) internal pure returns (Fp2Point memory) { return Fp2Point({ a: mulmod(scalar, value.a, P), b: mulmod(scalar, value.b, P) }); } function minusFp2(Fp2Point memory diminished, Fp2Point memory subtracted) internal pure returns (Fp2Point memory difference) { uint p = P; if (diminished.a >= subtracted.a) { difference.a = addmod(diminished.a, p - subtracted.a, p); } else { difference.a = (p - addmod(subtracted.a, p - diminished.a, p)).mod(p); } if (diminished.b >= subtracted.b) { difference.b = addmod(diminished.b, p - subtracted.b, p); } else { difference.b = (p - addmod(subtracted.b, p - diminished.b, p)).mod(p); } } function mulFp2( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (Fp2Point memory result) { uint p = P; Fp2Point memory point = Fp2Point({ a: mulmod(value1.a, value2.a, p), b: mulmod(value1.b, value2.b, p)}); result.a = addmod( point.a, mulmod(p - 1, point.b, p), p); result.b = addmod( mulmod( addmod(value1.a, value1.b, p), addmod(value2.a, value2.b, p), p), p - addmod(point.a, point.b, p), p); } function squaredFp2(Fp2Point memory value) internal pure returns (Fp2Point memory) { uint p = P; uint ab = mulmod(value.a, value.b, p); uint mult = mulmod(addmod(value.a, value.b, p), addmod(value.a, mulmod(p - 1, value.b, p), p), p); return Fp2Point({ a: mult, b: addmod(ab, ab, p) }); } function inverseFp2(Fp2Point memory value) internal view returns (Fp2Point memory result) { uint p = P; uint t0 = mulmod(value.a, value.a, p); uint t1 = mulmod(value.b, value.b, p); uint t2 = mulmod(p - 1, t1, p); if (t0 >= t2) { t2 = addmod(t0, p - t2, p); } else { t2 = (p - addmod(t2, p - t0, p)).mod(p); } uint t3 = Precompiled.bigModExp(t2, p - 2, p); result.a = mulmod(value.a, t3, p); result.b = (p - mulmod(value.b, t3, p)).mod(p); } function isEqual( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (bool) { return value1.a == value2.a && value1.b == value2.b; } } library G1Operations { using SafeMath for uint; using Fp2Operations for Fp2Operations.Fp2Point; function getG1Generator() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 1, b: 2 }); } function isG1Point(uint x, uint y) internal pure returns (bool) { uint p = Fp2Operations.P; return mulmod(y, y, p) == addmod(mulmod(mulmod(x, x, p), x, p), 3, p); } function isG1(Fp2Operations.Fp2Point memory point) internal pure returns (bool) { return isG1Point(point.a, point.b); } function checkRange(Fp2Operations.Fp2Point memory point) internal pure returns (bool) { return point.a < Fp2Operations.P && point.b < Fp2Operations.P; } function negate(uint y) internal pure returns (uint) { return Fp2Operations.P.sub(y).mod(Fp2Operations.P); } } library G2Operations { using SafeMath for uint; using Fp2Operations for Fp2Operations.Fp2Point; struct G2Point { Fp2Operations.Fp2Point x; Fp2Operations.Fp2Point y; } function getTWISTB() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 19485874751759354771024239261021720505790618469301721065564631296452457478373, b: 266929791119991161246907387137283842545076965332900288569378510910307636690 }); } function getG2Generator() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 10857046999023057135944570762232829481370756359578518086990519993285655852781, b: 11559732032986387107991004021392285783925812861821192530917403151452391805634 }), y: Fp2Operations.Fp2Point({ a: 8495653923123431417604973247489272438418190587263600148770280649306958101930, b: 4082367875863433681332203403145435568316851327593401208105741076214120093531 }) }); } function getG2Zero() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 0, b: 0 }), y: Fp2Operations.Fp2Point({ a: 1, b: 0 }) }); } function isG2Point(Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y) internal pure returns (bool) { if (isG2ZeroPoint(x, y)) { return true; } Fp2Operations.Fp2Point memory squaredY = y.squaredFp2(); Fp2Operations.Fp2Point memory res = squaredY.minusFp2( x.squaredFp2().mulFp2(x) ).minusFp2(getTWISTB()); return res.a == 0 && res.b == 0; } function isG2(G2Point memory value) internal pure returns (bool) { return isG2Point(value.x, value.y); } function isG2ZeroPoint( Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y ) internal pure returns (bool) { return x.a == 0 && x.b == 0 && y.a == 1 && y.b == 0; } function isG2Zero(G2Point memory value) internal pure returns (bool) { return value.x.a == 0 && value.x.b == 0 && value.y.a == 1 && value.y.b == 0; // return isG2ZeroPoint(value.x, value.y); } function addG2( G2Point memory value1, G2Point memory value2 ) internal view returns (G2Point memory sum) { if (isG2Zero(value1)) { return value2; } if (isG2Zero(value2)) { return value1; } if (isEqual(value1, value2)) { return doubleG2(value1); } Fp2Operations.Fp2Point memory s = value2.y.minusFp2(value1.y).mulFp2(value2.x.minusFp2(value1.x).inverseFp2()); sum.x = s.squaredFp2().minusFp2(value1.x.addFp2(value2.x)); sum.y = value1.y.addFp2(s.mulFp2(sum.x.minusFp2(value1.x))); uint p = Fp2Operations.P; sum.y.a = (p - sum.y.a).mod(p); sum.y.b = (p - sum.y.b).mod(p); } function isEqual( G2Point memory value1, G2Point memory value2 ) internal pure returns (bool) { return value1.x.isEqual(value2.x) && value1.y.isEqual(value2.y); } function doubleG2(G2Point memory value) internal view returns (G2Point memory result) { if (isG2Zero(value)) { return value; } else { Fp2Operations.Fp2Point memory s = value.x.squaredFp2().scalarMulFp2(3).mulFp2(value.y.scalarMulFp2(2).inverseFp2()); result.x = s.squaredFp2().minusFp2(value.x.addFp2(value.x)); result.y = value.y.addFp2(s.mulFp2(result.x.minusFp2(value.x))); uint p = Fp2Operations.P; result.y.a = (p - result.y.a).mod(p); result.y.b = (p - result.y.b).mod(p); } } } // SPDX-License-Identifier: AGPL-3.0-only /* FractionUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; library FractionUtils { using SafeMath for uint; struct Fraction { uint numerator; uint denominator; } function createFraction(uint numerator, uint denominator) internal pure returns (Fraction memory) { require(denominator > 0, "Division by zero"); Fraction memory fraction = Fraction({numerator: numerator, denominator: denominator}); reduceFraction(fraction); return fraction; } function createFraction(uint value) internal pure returns (Fraction memory) { return createFraction(value, 1); } function reduceFraction(Fraction memory fraction) internal pure { uint _gcd = gcd(fraction.numerator, fraction.denominator); fraction.numerator = fraction.numerator.div(_gcd); fraction.denominator = fraction.denominator.div(_gcd); } // numerator - is limited by 7*10^27, we could multiply it numerator * numerator - it would less than 2^256-1 function multiplyFraction(Fraction memory a, Fraction memory b) internal pure returns (Fraction memory) { return createFraction(a.numerator.mul(b.numerator), a.denominator.mul(b.denominator)); } function gcd(uint a, uint b) internal pure returns (uint) { uint _a = a; uint _b = b; if (_b > _a) { (_a, _b) = swap(_a, _b); } while (_b > 0) { _a = _a.mod(_b); (_a, _b) = swap (_a, _b); } return _a; } function swap(uint a, uint b) internal pure returns (uint, uint) { return (b, a); } } // SPDX-License-Identifier: AGPL-3.0-only /* StringUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; library MathUtils { uint constant private _EPS = 1e6; event UnderflowError( uint a, uint b ); function boundedSub(uint256 a, uint256 b) internal returns (uint256) { if (a >= b) { return a - b; } else { emit UnderflowError(a, b); return 0; } } function boundedSubWithoutEvent(uint256 a, uint256 b) internal pure returns (uint256) { if (a >= b) { return a - b; } else { return 0; } } function muchGreater(uint256 a, uint256 b) internal pure returns (bool) { assert(uint(-1) - _EPS > b); return a > b + _EPS; } function approximatelyEqual(uint256 a, uint256 b) internal pure returns (bool) { if (a > b) { return a - b < _EPS; } else { return b - a < _EPS; } } } // SPDX-License-Identifier: AGPL-3.0-only /* Precompiled.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; library Precompiled { function bigModExp(uint base, uint power, uint modulus) internal view returns (uint) { uint[6] memory inputToBigModExp; inputToBigModExp[0] = 32; inputToBigModExp[1] = 32; inputToBigModExp[2] = 32; inputToBigModExp[3] = base; inputToBigModExp[4] = power; inputToBigModExp[5] = modulus; uint[1] memory out; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 5, inputToBigModExp, mul(6, 0x20), out, 0x20) } require(success, "BigModExp failed"); return out[0]; } function bn256ScalarMul(uint x, uint y, uint k) internal view returns (uint , uint ) { uint[3] memory inputToMul; uint[2] memory output; inputToMul[0] = x; inputToMul[1] = y; inputToMul[2] = k; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 7, inputToMul, 0x60, output, 0x40) } require(success, "Multiplication failed"); return (output[0], output[1]); } function bn256Pairing( uint x1, uint y1, uint a1, uint b1, uint c1, uint d1, uint x2, uint y2, uint a2, uint b2, uint c2, uint d2) internal view returns (bool) { bool success; uint[12] memory inputToPairing; inputToPairing[0] = x1; inputToPairing[1] = y1; inputToPairing[2] = a1; inputToPairing[3] = b1; inputToPairing[4] = c1; inputToPairing[5] = d1; inputToPairing[6] = x2; inputToPairing[7] = y2; inputToPairing[8] = a2; inputToPairing[9] = b2; inputToPairing[10] = c2; inputToPairing[11] = d2; uint[1] memory out; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 8, inputToPairing, mul(12, 0x20), out, 0x20) } require(success, "Pairing check failed"); return out[0] != 0; } } // SPDX-License-Identifier: AGPL-3.0-only /* StringUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; library StringUtils { using SafeMath for uint; function strConcat(string memory a, string memory b) internal pure returns (string memory) { bytes memory _ba = bytes(a); bytes memory _bb = bytes(b); string memory ab = new string(_ba.length.add(_bb.length)); bytes memory strBytes = bytes(ab); uint k = 0; uint i = 0; for (i = 0; i < _ba.length; i++) { strBytes[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { strBytes[k++] = _bb[i]; } return string(strBytes); } } pragma solidity ^0.6.0; import "../Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, _msgSender())); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. */ abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } pragma solidity ^0.6.0; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } pragma solidity ^0.6.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.0; /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } pragma solidity ^0.6.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } }
Interface of the Locker functions./
interface ILocker { function getAndUpdateLockedAmount(address wallet) external returns (uint); function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint); } ILocker.sol - SKALE Manager }
401,503
./partial_match/1/0x908158D3A21738EC4d7120665f16b2D8E84C8D79/sources/HPOSI.sol
See {IERC20-balanceOf}./
function balanceOf(address account) public view virtual override returns (uint256) { return transferHelper.balanceOf(account); }
4,028,074
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "../../periphery/WithdrawableV2.sol"; import "../../interfaces/IPendleLiquidityMiningV2.sol"; import "../../interfaces/IPendlePausingManager.sol"; import "../../interfaces/IPendleWhitelist.sol"; import "../../libraries/MathLib.sol"; import "../../libraries/TokenUtilsLib.sol"; /* - stakeToken is the token to be used to stake into this contract to receive rewards - yieldToken is the token generated by stakeToken while it's being staked. For example, Sushi's LP token generates SUSHI(if it's in Onsen program), or Pendle's Aave LP generates aToken - If there is no yieldToken, it should be set to address(0) to save gas */ contract PendleLiquidityMiningBaseV2 is IPendleLiquidityMiningV2, WithdrawableV2, ReentrancyGuard { using Math for uint256; using SafeMath for uint256; using SafeERC20 for IERC20; struct EpochData { uint256 totalStakeUnits; uint256 totalRewards; uint256 lastUpdated; mapping(address => uint256) stakeUnitsForUser; mapping(address => uint256) availableRewardsForUser; } IPendleWhitelist public immutable whitelist; IPendlePausingManager public immutable pausingManager; uint256 public override numberOfEpochs; uint256 public override totalStake; mapping(uint256 => EpochData) internal epochData; mapping(address => uint256) public override balances; mapping(address => uint256) public lastTimeUserStakeUpdated; mapping(address => uint256) public lastEpochClaimed; address public immutable override pendleTokenAddress; address public immutable override stakeToken; address public immutable override yieldToken; uint256 public immutable override startTime; uint256 public immutable override epochDuration; uint256 public immutable override vestingEpochs; uint256 public constant MULTIPLIER = 10**20; // yieldToken-related mapping(address => uint256) public override dueInterests; mapping(address => uint256) public override lastParamL; uint256 public override lastNYield; uint256 public override paramL; modifier hasStarted() { require(_getCurrentEpochId() > 0, "NOT_STARTED"); _; } modifier nonContractOrWhitelisted() { bool isEOA = !Address.isContract(msg.sender) && tx.origin == msg.sender; require(isEOA || whitelist.whitelisted(msg.sender), "CONTRACT_NOT_WHITELISTED"); _; } modifier isUserAllowedToUse() { (bool paused, ) = pausingManager.checkLiqMiningStatus(address(this)); require(!paused, "LIQ_MINING_PAUSED"); require(numberOfEpochs > 0, "NOT_FUNDED"); require(_getCurrentEpochId() > 0, "NOT_STARTED"); _; } constructor( address _governanceManager, address _pausingManager, address _whitelist, address _pendleTokenAddress, address _stakeToken, address _yieldToken, uint256 _startTime, uint256 _epochDuration, uint256 _vestingEpochs ) PermissionsV2(_governanceManager) { require(_startTime > block.timestamp, "INVALID_START_TIME"); TokenUtils.requireERC20(_pendleTokenAddress); TokenUtils.requireERC20(_stakeToken); require(_vestingEpochs > 0, "INVALID_VESTING_EPOCHS"); // yieldToken can be zero address pausingManager = IPendlePausingManager(_pausingManager); whitelist = IPendleWhitelist(_whitelist); pendleTokenAddress = _pendleTokenAddress; stakeToken = _stakeToken; yieldToken = _yieldToken; startTime = _startTime; epochDuration = _epochDuration; vestingEpochs = _vestingEpochs; paramL = 1; } /** @notice set up emergencyMode by pulling all tokens back to this contract & approve spender to spend infinity amount */ function setUpEmergencyMode(address spender, bool) external virtual override { (, bool emergencyMode) = pausingManager.checkLiqMiningStatus(address(this)); require(emergencyMode, "NOT_EMERGENCY"); (address liqMiningEmergencyHandler, , ) = pausingManager.liqMiningEmergencyHandler(); require(msg.sender == liqMiningEmergencyHandler, "NOT_EMERGENCY_HANDLER"); // because we are not staking our tokens anywhere else, we can just approve IERC20(pendleTokenAddress).safeApprove(spender, type(uint256).max); IERC20(stakeToken).safeApprove(spender, type(uint256).max); if (yieldToken != address(0)) IERC20(yieldToken).safeApprove(spender, type(uint256).max); } /** @notice create new epochs & fund rewards for them @dev same logic as the function in V1 */ function fund(uint256[] calldata rewards) external virtual override onlyGovernance { // Once the program is over, it cannot be extended require(_getCurrentEpochId() <= numberOfEpochs, "LAST_EPOCH_OVER"); uint256 nNewEpochs = rewards.length; uint256 totalFunded; // all the funding will be used for new epochs for (uint256 i = 0; i < nNewEpochs; i++) { totalFunded = totalFunded.add(rewards[i]); epochData[numberOfEpochs + i + 1].totalRewards = rewards[i]; } numberOfEpochs = numberOfEpochs.add(nNewEpochs); IERC20(pendleTokenAddress).safeTransferFrom(msg.sender, address(this), totalFunded); emit Funded(rewards, numberOfEpochs); } /** @notice top up rewards of exisiting epochs @dev almost same logic as the function in V1 without the redundant isFunded check */ function topUpRewards(uint256[] calldata epochIds, uint256[] calldata rewards) external virtual override onlyGovernance { require(epochIds.length == rewards.length, "INVALID_ARRAYS"); uint256 curEpoch = _getCurrentEpochId(); uint256 endEpoch = numberOfEpochs; uint256 totalTopUp; for (uint256 i = 0; i < epochIds.length; i++) { require(curEpoch < epochIds[i] && epochIds[i] <= endEpoch, "INVALID_EPOCH_ID"); totalTopUp = totalTopUp.add(rewards[i]); epochData[epochIds[i]].totalRewards = epochData[epochIds[i]].totalRewards.add( rewards[i] ); } IERC20(pendleTokenAddress).safeTransferFrom(msg.sender, address(this), totalTopUp); emit RewardsToppedUp(epochIds, rewards); } /** @notice stake tokens in to receive rewards. It's allowed to stake for others @param forAddr the address to stake for @dev all staking data will be updated for `forAddr`, but msg.sender will be the one transferring tokens in */ function stake(address forAddr, uint256 amount) external virtual override nonReentrant nonContractOrWhitelisted isUserAllowedToUse { require(forAddr != address(0), "ZERO_ADDRESS"); require(amount != 0, "ZERO_AMOUNT"); require(_getCurrentEpochId() <= numberOfEpochs, "INCENTIVES_PERIOD_OVER"); _settleStake(forAddr, msg.sender, amount); emit Staked(forAddr, amount); } /** @notice withdraw tokens from the staking contract. It's allowed to withdraw to an address different from msg.sender @param toAddr the address to receive all tokens @dev all staking data will be updated for msg.sender, but `toAddr` will be the one receiving all tokens */ function withdraw(address toAddr, uint256 amount) external virtual override nonReentrant isUserAllowedToUse { require(amount != 0, "ZERO_AMOUNT"); require(toAddr != address(0), "ZERO_ADDRESS"); _settleWithdraw(msg.sender, toAddr, amount); emit Withdrawn(msg.sender, amount); } /** @notice redeem all available rewards from expired epochs. It's allowed to redeem for others @param user the address whose data will be updated & receive rewards */ function redeemRewards(address user) external virtual override nonReentrant isUserAllowedToUse returns (uint256 rewards) { require(user != address(0), "ZERO_ADDRESS"); rewards = _beforeTransferPendingRewards(user); if (rewards != 0) IERC20(pendleTokenAddress).safeTransfer(user, rewards); } /** @notice redeem all due interests. It's allowed to redeem for others @param user the address whose data will be updated & receive due interests */ function redeemDueInterests(address user) external virtual override nonReentrant isUserAllowedToUse returns (uint256 amountOut) { if (yieldToken == address(0)) return 0; require(user != address(0), "ZERO_ADDRESS"); amountOut = _beforeTransferDueInterests(user); amountOut = _pushYieldToken(user, amountOut); } function updateAndReadEpochData(uint256 epochId, address user) external override nonReentrant isUserAllowedToUse returns ( uint256 totalStakeUnits, uint256 totalRewards, uint256 lastUpdated, uint256 stakeUnitsForUser, uint256 availableRewardsForUser ) { _updatePendingRewards(user); return readEpochData(epochId, user); } function readEpochData(uint256 epochId, address user) public view override returns ( uint256 totalStakeUnits, uint256 totalRewards, uint256 lastUpdated, uint256 stakeUnitsForUser, uint256 availableRewardsForUser ) { totalStakeUnits = epochData[epochId].totalStakeUnits; totalRewards = epochData[epochId].totalRewards; lastUpdated = epochData[epochId].lastUpdated; stakeUnitsForUser = epochData[epochId].stakeUnitsForUser[user]; availableRewardsForUser = epochData[epochId].availableRewardsForUser[user]; } /** @notice update all reward-related data for user @dev to be called before user's stakeToken balance changes @dev same logic as the function in V1 */ function _updatePendingRewards(address user) internal virtual { _updateStakeData(); // user has not staked before, no need to do anything if (lastTimeUserStakeUpdated[user] == 0) { lastTimeUserStakeUpdated[user] = block.timestamp; return; } uint256 _curEpoch = _getCurrentEpochId(); uint256 _endEpoch = Math.min(numberOfEpochs, _curEpoch); // if _curEpoch<=numberOfEpochs => the endEpoch hasn't ended yet (since endEpoch=curEpoch) bool _isEndEpochOver = (_curEpoch > numberOfEpochs); // caching uint256 _balance = balances[user]; uint256 _lastTimeUserStakeUpdated = lastTimeUserStakeUpdated[user]; uint256 _totalStake = totalStake; uint256 _startEpoch = _epochOfTimestamp(_lastTimeUserStakeUpdated); // Go through all epochs until now to update stakeUnitsForUser and availableRewardsForEpoch for (uint256 epochId = _startEpoch; epochId <= _endEpoch; epochId++) { if (epochData[epochId].totalStakeUnits == 0) { // in the extreme case of zero staked tokens for this expiry even now, // => nothing to do from this epoch onwards if (_totalStake == 0) break; // nobody stakes anything in this epoch continue; } // updating stakeUnits for users. The logic of this is similar to _updateStakeDataForExpiry epochData[epochId].stakeUnitsForUser[user] = epochData[epochId] .stakeUnitsForUser[user] .add(_calcUnitsStakeInEpoch(_balance, _lastTimeUserStakeUpdated, epochId)); // all epochs prior to the endEpoch must have ended // if epochId == _endEpoch, we must check if the epoch has ended or not if (epochId == _endEpoch && !_isEndEpochOver) { break; } // Now this epoch has ended,let's distribute its reward to this user // calc the amount of rewards the user is eligible to receive from this epoch uint256 rewardsPerVestingEpoch = _calcAmountRewardsForUserInEpoch(user, epochId); // Now we distribute this rewards over the vestingEpochs starting from epochId + 1 // to epochId + vestingEpochs for (uint256 i = epochId + 1; i <= epochId + vestingEpochs; i++) { epochData[i].availableRewardsForUser[user] = epochData[i] .availableRewardsForUser[user] .add(rewardsPerVestingEpoch); } } lastTimeUserStakeUpdated[user] = block.timestamp; } /** @notice update staking data for the current epoch @dev same logic as the function in V1 */ function _updateStakeData() internal virtual { uint256 _curEpoch = _getCurrentEpochId(); // loop through all epochData in descending order for (uint256 i = Math.min(_curEpoch, numberOfEpochs); i > 0; i--) { uint256 epochEndTime = _endTimeOfEpoch(i); uint256 lastUpdatedForEpoch = epochData[i].lastUpdated; if (lastUpdatedForEpoch == epochEndTime) { break; // its already updated until this epoch, our job here is done } // if the epoch hasn't been fully updated yet, we will update it // just add the amount of units contributed by users since lastUpdatedForEpoch -> now // by calling _calcUnitsStakeInEpoch epochData[i].totalStakeUnits = epochData[i].totalStakeUnits.add( _calcUnitsStakeInEpoch(totalStake, lastUpdatedForEpoch, i) ); // If the epoch has ended, lastUpdated = epochEndTime // If not yet, lastUpdated = block.timestamp (aka now) epochData[i].lastUpdated = Math.min(block.timestamp, epochEndTime); } } /** @notice update all interest-related data for user @dev to be called before user's stakeToken balance changes or when user wants to update his interests @dev same logic as the function in CompoundLiquidityMiningV1 */ function _updateDueInterests(address user) internal virtual { if (yieldToken == address(0)) return; _updateParamL(); if (lastParamL[user] == 0) { lastParamL[user] = paramL; return; } uint256 principal = balances[user]; uint256 interestValuePerStakeToken = paramL.sub(lastParamL[user]); uint256 interestFromStakeToken = principal.mul(interestValuePerStakeToken).div(MULTIPLIER); dueInterests[user] = dueInterests[user].add(interestFromStakeToken); lastParamL[user] = paramL; } /** @notice update paramL, lastNYield & redeem interest from external sources @dev to be called only from _updateDueInterests @dev same logic as the function in V1 */ function _updateParamL() internal virtual { if (yieldToken == address(0) || !_checkNeedUpdateParamL()) return; _redeemExternalInterests(); uint256 currentNYield = IERC20(yieldToken).balanceOf(address(this)); (uint256 firstTerm, uint256 paramR) = _getFirstTermAndParamR(currentNYield); uint256 secondTerm; if (totalStake != 0) secondTerm = paramR.mul(MULTIPLIER).div(totalStake); // Update new states paramL = firstTerm.add(secondTerm); lastNYield = currentNYield; } /** @dev same logic as the function in CompoundLiquidityMining @dev to be called only from _updateParamL */ function _getFirstTermAndParamR(uint256 currentNYield) internal virtual returns (uint256 firstTerm, uint256 paramR) { firstTerm = paramL; paramR = currentNYield.sub(lastNYield); } /** @dev function is empty because by default yieldToken==0 */ function _checkNeedUpdateParamL() internal virtual returns (bool) {} /** @dev function is empty because by default yieldToken==0 */ function _redeemExternalInterests() internal virtual {} /** @notice Calc the amount of rewards that the user can receive now & clear all the pending rewards @dev To be called before any rewards is transferred out @dev same logic as the function in V1 */ function _beforeTransferPendingRewards(address user) internal virtual returns (uint256 amountOut) { _updatePendingRewards(user); uint256 _lastEpoch = Math.min(_getCurrentEpochId(), numberOfEpochs + vestingEpochs); for (uint256 i = lastEpochClaimed[user]; i <= _lastEpoch; i++) { if (epochData[i].availableRewardsForUser[user] > 0) { amountOut = amountOut.add(epochData[i].availableRewardsForUser[user]); epochData[i].availableRewardsForUser[user] = 0; } } lastEpochClaimed[user] = _lastEpoch; emit PendleRewardsSettled(user, amountOut); } /** @notice Calc the amount of interests that the user can receive now & clear all the due interests @dev To be called before any interests is transferred out @dev same logic as the function in V1 */ function _beforeTransferDueInterests(address user) internal virtual returns (uint256 amountOut) { if (yieldToken == address(0)) return 0; _updateDueInterests(user); amountOut = Math.min(dueInterests[user], lastNYield); dueInterests[user] = 0; lastNYield = lastNYield.sub(amountOut); } /** @param user the address whose all stake data will be updated @param payer the address which tokens will be pulled from @param amount amount of tokens to be staked @dev payer is only used to pass to _pullStakeToken */ function _settleStake( address user, address payer, uint256 amount ) internal virtual { _updatePendingRewards(user); _updateDueInterests(user); balances[user] = balances[user].add(amount); totalStake = totalStake.add(amount); _pullStakeToken(payer, amount); } /** @param user the address whose all stake data will be updated @param receiver the address which tokens will be pushed to @param amount amount of tokens to be withdrawn @dev receiver is only used to pass to _pullStakeToken */ function _settleWithdraw( address user, address receiver, uint256 amount ) internal virtual { _updatePendingRewards(user); _updateDueInterests(user); balances[user] = balances[user].sub(amount); totalStake = totalStake.sub(amount); _pushStakeToken(receiver, amount); } function _pullStakeToken(address from, uint256 amount) internal virtual { // For the case that we don't need to stake the stakeToken anywhere else, just pull it // into the current contract IERC20(stakeToken).safeTransferFrom(from, address(this), amount); } function _pushStakeToken(address to, uint256 amount) internal virtual { // For the case that we don't need to stake the stakeToken anywhere else, just transfer out // from the current contract if (amount != 0) IERC20(stakeToken).safeTransfer(to, amount); } function _pushYieldToken(address to, uint256 amount) internal virtual returns (uint256 outAmount) { outAmount = Math.min(amount, IERC20(yieldToken).balanceOf(address(this))); if (outAmount != 0) IERC20(yieldToken).safeTransfer(to, outAmount); } /** @notice returns the stakeUnits in the _epochId(th) epoch of an user if he stake from _startTime to now @dev to calculate durationStakeThisEpoch: user will stake from _startTime -> _endTime, while the epoch last from _startTimeOfEpoch -> _endTimeOfEpoch => the stakeDuration of user will be min(_endTime,_endTimeOfEpoch) - max(_startTime,_startTimeOfEpoch) @dev same logic as in V1 */ function _calcUnitsStakeInEpoch( uint256 _tokenAmount, uint256 _startTime, uint256 _epochId ) internal view returns (uint256 stakeUnitsForUser) { uint256 _endTime = block.timestamp; uint256 _l = Math.max(_startTime, _startTimeOfEpoch(_epochId)); uint256 _r = Math.min(_endTime, _endTimeOfEpoch(_epochId)); uint256 durationStakeThisEpoch = _r.subMax0(_l); return _tokenAmount.mul(durationStakeThisEpoch); } /** @notice calc the amount of rewards the user is eligible to receive from this epoch, but we will return the amount per vestingEpoch instead @dev same logic as in V1 */ function _calcAmountRewardsForUserInEpoch(address user, uint256 epochId) internal view returns (uint256 rewardsPerVestingEpoch) { rewardsPerVestingEpoch = epochData[epochId] .totalRewards .mul(epochData[epochId].stakeUnitsForUser[user]) .div(epochData[epochId].totalStakeUnits) .div(vestingEpochs); } function _startTimeOfEpoch(uint256 t) internal view returns (uint256) { // epoch id starting from 1 return startTime.add((t.sub(1)).mul(epochDuration)); } function _getCurrentEpochId() internal view returns (uint256) { return _epochOfTimestamp(block.timestamp); } function _epochOfTimestamp(uint256 t) internal view returns (uint256) { if (t < startTime) return 0; return (t.sub(startTime)).div(epochDuration).add(1); } // Although the name of this function is endTimeOfEpoch, it's actually the beginning of the next epoch function _endTimeOfEpoch(uint256 t) internal view returns (uint256) { // epoch id starting from 1 return startTime.add(t.mul(epochDuration)); } function _allowedToWithdraw(address _token) internal view override returns (bool allowed) { allowed = _token != pendleTokenAddress && _token != stakeToken && _token != yieldToken; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./PermissionsV2.sol"; abstract contract WithdrawableV2 is PermissionsV2 { using SafeERC20 for IERC20; event EtherWithdraw(uint256 amount, address sendTo); event TokenWithdraw(IERC20 token, uint256 amount, address sendTo); /** * @dev Allows governance to withdraw Ether in a Pendle contract * in case of accidental ETH transfer into the contract. * @param amount The amount of Ether to withdraw. * @param sendTo The recipient address. */ function withdrawEther(uint256 amount, address payable sendTo) external onlyGovernance { (bool success, ) = sendTo.call{value: amount}(""); require(success, "WITHDRAW_FAILED"); emit EtherWithdraw(amount, sendTo); } /** * @dev Allows governance to withdraw all IERC20 compatible tokens in a Pendle * contract in case of accidental token transfer into the contract. * @param token IERC20 The address of the token contract. * @param amount The amount of IERC20 tokens to withdraw. * @param sendTo The recipient address. */ function withdrawToken( IERC20 token, uint256 amount, address sendTo ) external onlyGovernance { require(_allowedToWithdraw(address(token)), "TOKEN_NOT_ALLOWED"); token.safeTransfer(sendTo, amount); emit TokenWithdraw(token, amount, sendTo); } // must be overridden by the sub contracts, so we must consider explicitly // in each and every contract which tokens are allowed to be withdrawn function _allowedToWithdraw(address) internal view virtual returns (bool allowed); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; interface IPendleLiquidityMiningV2 { event Funded(uint256[] rewards, uint256 numberOfEpochs); event RewardsToppedUp(uint256[] epochIds, uint256[] rewards); event Staked(address user, uint256 amount); event Withdrawn(address user, uint256 amount); event PendleRewardsSettled(address user, uint256 amount); function fund(uint256[] calldata rewards) external; function topUpRewards(uint256[] calldata epochIds, uint256[] calldata rewards) external; function stake(address forAddr, uint256 amount) external; function withdraw(address toAddr, uint256 amount) external; function redeemRewards(address user) external returns (uint256 rewards); function redeemDueInterests(address user) external returns (uint256 amountOut); function setUpEmergencyMode(address spender, bool) external; function updateAndReadEpochData(uint256 epochId, address user) external returns ( uint256 totalStakeUnits, uint256 totalRewards, uint256 lastUpdated, uint256 stakeUnitsForUser, uint256 availableRewardsForUser ); function balances(address user) external view returns (uint256); function startTime() external view returns (uint256); function epochDuration() external view returns (uint256); function readEpochData(uint256 epochId, address user) external view returns ( uint256 totalStakeUnits, uint256 totalRewards, uint256 lastUpdated, uint256 stakeUnitsForUser, uint256 availableRewardsForUser ); function numberOfEpochs() external view returns (uint256); function vestingEpochs() external view returns (uint256); function stakeToken() external view returns (address); function yieldToken() external view returns (address); function pendleTokenAddress() external view returns (address); function totalStake() external view returns (uint256); function dueInterests(address) external view returns (uint256); function lastParamL(address) external view returns (uint256); function lastNYield() external view returns (uint256); function paramL() external view returns (uint256); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; interface IPendlePausingManager { event AddPausingAdmin(address admin); event RemovePausingAdmin(address admin); event PendingForgeEmergencyHandler(address _pendingForgeHandler); event PendingMarketEmergencyHandler(address _pendingMarketHandler); event PendingLiqMiningEmergencyHandler(address _pendingLiqMiningHandler); event ForgeEmergencyHandlerSet(address forgeEmergencyHandler); event MarketEmergencyHandlerSet(address marketEmergencyHandler); event LiqMiningEmergencyHandlerSet(address liqMiningEmergencyHandler); event PausingManagerLocked(); event ForgeHandlerLocked(); event MarketHandlerLocked(); event LiqMiningHandlerLocked(); event SetForgePaused(bytes32 forgeId, bool settingToPaused); event SetForgeAssetPaused(bytes32 forgeId, address underlyingAsset, bool settingToPaused); event SetForgeAssetExpiryPaused( bytes32 forgeId, address underlyingAsset, uint256 expiry, bool settingToPaused ); event SetForgeLocked(bytes32 forgeId); event SetForgeAssetLocked(bytes32 forgeId, address underlyingAsset); event SetForgeAssetExpiryLocked(bytes32 forgeId, address underlyingAsset, uint256 expiry); event SetMarketFactoryPaused(bytes32 marketFactoryId, bool settingToPaused); event SetMarketPaused(bytes32 marketFactoryId, address market, bool settingToPaused); event SetMarketFactoryLocked(bytes32 marketFactoryId); event SetMarketLocked(bytes32 marketFactoryId, address market); event SetLiqMiningPaused(address liqMiningContract, bool settingToPaused); event SetLiqMiningLocked(address liqMiningContract); function forgeEmergencyHandler() external view returns ( address handler, address pendingHandler, uint256 timelockDeadline ); function marketEmergencyHandler() external view returns ( address handler, address pendingHandler, uint256 timelockDeadline ); function liqMiningEmergencyHandler() external view returns ( address handler, address pendingHandler, uint256 timelockDeadline ); function permLocked() external view returns (bool); function permForgeHandlerLocked() external view returns (bool); function permMarketHandlerLocked() external view returns (bool); function permLiqMiningHandlerLocked() external view returns (bool); function isPausingAdmin(address) external view returns (bool); function setPausingAdmin(address admin, bool isAdmin) external; function requestForgeHandlerChange(address _pendingForgeHandler) external; function requestMarketHandlerChange(address _pendingMarketHandler) external; function requestLiqMiningHandlerChange(address _pendingLiqMiningHandler) external; function applyForgeHandlerChange() external; function applyMarketHandlerChange() external; function applyLiqMiningHandlerChange() external; function lockPausingManagerPermanently() external; function lockForgeHandlerPermanently() external; function lockMarketHandlerPermanently() external; function lockLiqMiningHandlerPermanently() external; function setForgePaused(bytes32 forgeId, bool paused) external; function setForgeAssetPaused( bytes32 forgeId, address underlyingAsset, bool paused ) external; function setForgeAssetExpiryPaused( bytes32 forgeId, address underlyingAsset, uint256 expiry, bool paused ) external; function setForgeLocked(bytes32 forgeId) external; function setForgeAssetLocked(bytes32 forgeId, address underlyingAsset) external; function setForgeAssetExpiryLocked( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external; function checkYieldContractStatus( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external returns (bool _paused, bool _locked); function setMarketFactoryPaused(bytes32 marketFactoryId, bool paused) external; function setMarketPaused( bytes32 marketFactoryId, address market, bool paused ) external; function setMarketFactoryLocked(bytes32 marketFactoryId) external; function setMarketLocked(bytes32 marketFactoryId, address market) external; function checkMarketStatus(bytes32 marketFactoryId, address market) external returns (bool _paused, bool _locked); function setLiqMiningPaused(address liqMiningContract, bool settingToPaused) external; function setLiqMiningLocked(address liqMiningContract) external; function checkLiqMiningStatus(address liqMiningContract) external returns (bool _paused, bool _locked); } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; interface IPendleWhitelist { event AddedToWhiteList(address); event RemovedFromWhiteList(address); function whitelisted(address) external view returns (bool); function addToWhitelist(address[] calldata _addresses) external; function removeFromWhitelist(address[] calldata _addresses) external; function getWhitelist() external view returns (address[] memory list); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.7.0; pragma abicoder v2; import "@openzeppelin/contracts/math/SafeMath.sol"; library Math { using SafeMath for uint256; uint256 internal constant BIG_NUMBER = (uint256(1) << uint256(200)); uint256 internal constant PRECISION_BITS = 40; uint256 internal constant RONE = uint256(1) << PRECISION_BITS; uint256 internal constant PI = (314 * RONE) / 10**2; uint256 internal constant PI_PLUSONE = (414 * RONE) / 10**2; uint256 internal constant PRECISION_POW = 1e2; function checkMultOverflow(uint256 _x, uint256 _y) internal pure returns (bool) { if (_y == 0) return false; return (((_x * _y) / _y) != _x); } /** @notice find the integer part of log2(p/q) => find largest x s.t p >= q * 2^x => find largest x s.t 2^x <= p / q */ function log2Int(uint256 _p, uint256 _q) internal pure returns (uint256) { uint256 res = 0; uint256 remain = _p / _q; while (remain > 0) { res++; remain /= 2; } return res - 1; } /** @notice log2 for a number that it in [1,2) @dev _x is FP, return a FP @dev function is from Kyber. Long modified the condition to be (_x >= one) && (_x < two) to avoid the case where x = 2 may lead to incorrect result */ function log2ForSmallNumber(uint256 _x) internal pure returns (uint256) { uint256 res = 0; uint256 one = (uint256(1) << PRECISION_BITS); uint256 two = 2 * one; uint256 addition = one; require((_x >= one) && (_x < two), "MATH_ERROR"); require(PRECISION_BITS < 125, "MATH_ERROR"); for (uint256 i = PRECISION_BITS; i > 0; i--) { _x = (_x * _x) / one; addition = addition / 2; if (_x >= two) { _x = _x / 2; res += addition; } } return res; } /** @notice log2 of (p/q). returns result in FP form @dev function is from Kyber. @dev _p & _q is FP, return a FP */ function logBase2(uint256 _p, uint256 _q) internal pure returns (uint256) { uint256 n = 0; if (_p > _q) { n = log2Int(_p, _q); } require(n * RONE <= BIG_NUMBER, "MATH_ERROR"); require(!checkMultOverflow(_p, RONE), "MATH_ERROR"); require(!checkMultOverflow(n, RONE), "MATH_ERROR"); require(!checkMultOverflow(uint256(1) << n, _q), "MATH_ERROR"); uint256 y = (_p * RONE) / (_q * (uint256(1) << n)); uint256 log2Small = log2ForSmallNumber(y); assert(log2Small <= BIG_NUMBER); return n * RONE + log2Small; } /** @notice calculate ln(p/q). returned result >= 0 @dev function is from Kyber. @dev _p & _q is FP, return a FP */ function ln(uint256 p, uint256 q) internal pure returns (uint256) { uint256 ln2Numerator = 6931471805599453094172; uint256 ln2Denomerator = 10000000000000000000000; uint256 log2x = logBase2(p, q); require(!checkMultOverflow(ln2Numerator, log2x), "MATH_ERROR"); return (ln2Numerator * log2x) / ln2Denomerator; } /** @notice extract the fractional part of a FP @dev value is a FP, return a FP */ function fpart(uint256 value) internal pure returns (uint256) { return value % RONE; } /** @notice convert a FP to an Int @dev value is a FP, return an Int */ function toInt(uint256 value) internal pure returns (uint256) { return value / RONE; } /** @notice convert an Int to a FP @dev value is an Int, return a FP */ function toFP(uint256 value) internal pure returns (uint256) { return value * RONE; } /** @notice return e^exp in FP form @dev estimation by formula at http://pages.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/exp.html the function is based on exp function of: https://github.com/NovakDistributed/macroverse/blob/master/contracts/RealMath.sol @dev the function is expected to converge quite fast, after about 20 iteration @dev exp is a FP, return a FP */ function rpowe(uint256 exp) internal pure returns (uint256) { uint256 res = 0; uint256 curTerm = RONE; for (uint256 n = 0; ; n++) { res += curTerm; curTerm = rmul(curTerm, rdiv(exp, toFP(n + 1))); if (curTerm == 0) { break; } if (n == 500) { /* testing shows that in the most extreme case, it will take 430 turns to converge. however, it's expected that the numbers will not exceed 2^120 in normal situation the most extreme case is rpow((1<<256)-1,(1<<40)-1) (equal to rpow((2^256-1)/2^40,0.99..9)) */ revert("RPOWE_SLOW_CONVERGE"); } } return res; } /** @notice calculate base^exp with base and exp being FP int @dev to improve accuracy, base^exp = base^(int(exp)+frac(exp)) = base^int(exp) * base^frac @dev base & exp are FP, return a FP */ function rpow(uint256 base, uint256 exp) internal pure returns (uint256) { if (exp == 0) { // Anything to the 0 is 1 return RONE; } if (base == 0) { // 0 to anything except 0 is 0 return 0; } uint256 frac = fpart(exp); // get the fractional part uint256 whole = exp - frac; uint256 wholePow = rpowi(base, toInt(whole)); // whole is a FP, convert to Int uint256 fracPow; // instead of calculating base ^ frac, we will calculate e ^ (frac*ln(base)) if (base < RONE) { /* since the base is smaller than 1.0, ln(base) < 0. Since 1 / (e^(frac*ln(1/base))) = e ^ (frac*ln(base)), we will calculate 1 / (e^(frac*ln(1/base))) instead. */ uint256 newExp = rmul(frac, ln(rdiv(RONE, base), RONE)); fracPow = rdiv(RONE, rpowe(newExp)); } else { /* base is greater than 1, calculate normally */ uint256 newExp = rmul(frac, ln(base, RONE)); fracPow = rpowe(newExp); } return rmul(wholePow, fracPow); } /** @notice return base^exp with base in FP form and exp in Int @dev this function use a technique called: exponentiating by squaring complexity O(log(q)) @dev function is from Kyber. @dev base is a FP, exp is an Int, return a FP */ function rpowi(uint256 base, uint256 exp) internal pure returns (uint256) { uint256 res = exp % 2 != 0 ? base : RONE; for (exp /= 2; exp != 0; exp /= 2) { base = rmul(base, base); if (exp % 2 != 0) { res = rmul(res, base); } } return res; } /** @dev y is an Int, returns an Int @dev babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) @dev from Uniswap */ function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } /** @notice divide 2 FP, return a FP @dev function is from Balancer. @dev x & y are FP, return a FP */ function rdiv(uint256 x, uint256 y) internal pure returns (uint256) { return (y / 2).add(x.mul(RONE)).div(y); } /** @notice multiply 2 FP, return a FP @dev function is from Balancer. @dev x & y are FP, return a FP */ function rmul(uint256 x, uint256 y) internal pure returns (uint256) { return (RONE / 2).add(x.mul(y)).div(RONE); } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function subMax0(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a - b : 0; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.7.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; library TokenUtils { function requireERC20(address tokenAddr) internal view { require(IERC20(tokenAddr).totalSupply() > 0, "INVALID_ERC20"); } function requireERC20(IERC20 token) internal view { require(token.totalSupply() > 0, "INVALID_ERC20"); } } // 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: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../core/PendleGovernanceManager.sol"; import "../interfaces/IPermissionsV2.sol"; abstract contract PermissionsV2 is IPermissionsV2 { PendleGovernanceManager public immutable override governanceManager; address internal initializer; constructor(address _governanceManager) { require(_governanceManager != address(0), "ZERO_ADDRESS"); initializer = msg.sender; governanceManager = PendleGovernanceManager(_governanceManager); } modifier initialized() { require(initializer == address(0), "NOT_INITIALIZED"); _; } modifier onlyGovernance() { require(msg.sender == _governance(), "ONLY_GOVERNANCE"); _; } function _governance() internal view returns (address) { return governanceManager.governance(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; contract PendleGovernanceManager { address public governance; address public pendingGovernance; event GovernanceClaimed(address newGovernance, address previousGovernance); event TransferGovernancePending(address pendingGovernance); constructor(address _governance) { require(_governance != address(0), "ZERO_ADDRESS"); governance = _governance; } modifier onlyGovernance() { require(msg.sender == governance, "ONLY_GOVERNANCE"); _; } /** * @dev Allows the pendingGovernance address to finalize the change governance process. */ function claimGovernance() external { require(pendingGovernance == msg.sender, "WRONG_GOVERNANCE"); emit GovernanceClaimed(pendingGovernance, governance); governance = pendingGovernance; pendingGovernance = address(0); } /** * @dev Allows the current governance to set the pendingGovernance address. * @param _governance The address to transfer ownership to. */ function transferGovernance(address _governance) external onlyGovernance { require(_governance != address(0), "ZERO_ADDRESS"); pendingGovernance = _governance; emit TransferGovernancePending(pendingGovernance); } } // SPDX-License-Identifier: MIT /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity 0.7.6; pragma abicoder v2; import "../core/PendleGovernanceManager.sol"; interface IPermissionsV2 { function governanceManager() external returns (PendleGovernanceManager); }
SPDX-License-Identifier: MIT MIT License =========== Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE/
interface IPendlePausingManager { event AddPausingAdmin(address admin); event RemovePausingAdmin(address admin); event PendingForgeEmergencyHandler(address _pendingForgeHandler); event PendingMarketEmergencyHandler(address _pendingMarketHandler); event PendingLiqMiningEmergencyHandler(address _pendingLiqMiningHandler); event ForgeEmergencyHandlerSet(address forgeEmergencyHandler); event MarketEmergencyHandlerSet(address marketEmergencyHandler); event LiqMiningEmergencyHandlerSet(address liqMiningEmergencyHandler); event PausingManagerLocked(); event ForgeHandlerLocked(); event MarketHandlerLocked(); event LiqMiningHandlerLocked(); event SetForgePaused(bytes32 forgeId, bool settingToPaused); event SetForgeAssetPaused(bytes32 forgeId, address underlyingAsset, bool settingToPaused); event SetForgeAssetExpiryPaused( bytes32 forgeId, address underlyingAsset, uint256 expiry, bool settingToPaused ); event SetForgeLocked(bytes32 forgeId); event SetForgeAssetLocked(bytes32 forgeId, address underlyingAsset); event SetForgeAssetExpiryLocked(bytes32 forgeId, address underlyingAsset, uint256 expiry); event SetMarketFactoryPaused(bytes32 marketFactoryId, bool settingToPaused); event SetMarketPaused(bytes32 marketFactoryId, address market, bool settingToPaused); event SetMarketFactoryLocked(bytes32 marketFactoryId); event SetMarketLocked(bytes32 marketFactoryId, address market); event SetLiqMiningPaused(address liqMiningContract, bool settingToPaused); event SetLiqMiningLocked(address liqMiningContract); function forgeEmergencyHandler() external view returns ( address handler, address pendingHandler, uint256 timelockDeadline ); function marketEmergencyHandler() external view returns ( address handler, address pendingHandler, uint256 timelockDeadline ); function liqMiningEmergencyHandler() external view returns ( address handler, address pendingHandler, uint256 timelockDeadline ); function permLocked() external view returns (bool); function permForgeHandlerLocked() external view returns (bool); function permMarketHandlerLocked() external view returns (bool); function permLiqMiningHandlerLocked() external view returns (bool); function isPausingAdmin(address) external view returns (bool); function setPausingAdmin(address admin, bool isAdmin) external; function requestForgeHandlerChange(address _pendingForgeHandler) external; function requestMarketHandlerChange(address _pendingMarketHandler) external; function requestLiqMiningHandlerChange(address _pendingLiqMiningHandler) external; function applyForgeHandlerChange() external; function applyMarketHandlerChange() external; function applyLiqMiningHandlerChange() external; function lockPausingManagerPermanently() external; function lockForgeHandlerPermanently() external; function lockMarketHandlerPermanently() external; function lockLiqMiningHandlerPermanently() external; function setForgePaused(bytes32 forgeId, bool paused) external; function setForgeAssetPaused( bytes32 forgeId, address underlyingAsset, bool paused ) external; function setForgeAssetExpiryPaused( bytes32 forgeId, address underlyingAsset, uint256 expiry, bool paused ) external; function setForgeLocked(bytes32 forgeId) external; function setForgeAssetLocked(bytes32 forgeId, address underlyingAsset) external; function setForgeAssetExpiryLocked( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external; function checkYieldContractStatus( bytes32 forgeId, address underlyingAsset, uint256 expiry ) external returns (bool _paused, bool _locked); function setMarketFactoryPaused(bytes32 marketFactoryId, bool paused) external; function setMarketPaused( bytes32 marketFactoryId, address market, bool paused ) external; function setMarketFactoryLocked(bytes32 marketFactoryId) external; function setMarketLocked(bytes32 marketFactoryId, address market) external; function checkMarketStatus(bytes32 marketFactoryId, address market) external returns (bool _paused, bool _locked); function setLiqMiningPaused(address liqMiningContract, bool settingToPaused) external; function setLiqMiningLocked(address liqMiningContract) external; function checkLiqMiningStatus(address liqMiningContract) external returns (bool _paused, bool _locked); }
1,567,074
./full_match/11155111/0xc9241Cf4cD7d9569cA044d8202EF1080405Bc6C9/sources/src/Drips.sol
Calculate the amount squeezable by a user from a single drips history entry. userId The ID of the user to squeeze drips for. dripsHistory The squeezed history entry. squeezeStartCap The squeezed time range start. squeezeEndCap The squeezed time range end. return squeezedAmt The squeezed amount. Binary search for the `idx` of the first occurrence of `userId`
function _squeezedAmt( uint256 userId, DripsHistory memory dripsHistory, uint32 squeezeStartCap, uint32 squeezeEndCap ) private view returns (uint128 squeezedAmt) { unchecked { DripsReceiver[] memory receivers = dripsHistory.receivers; uint256 idx = 0; for (uint256 idxCap = receivers.length; idx < idxCap;) { uint256 idxMid = (idx + idxCap) / 2; if (receivers[idxMid].userId < userId) { idx = idxMid + 1; idxCap = idxMid; } } uint32 updateTime = dripsHistory.updateTime; uint32 maxEnd = dripsHistory.maxEnd; uint256 amt = 0; for (; idx < receivers.length; idx++) { DripsReceiver memory receiver = receivers[idx]; if (receiver.userId != userId) break; (uint32 start, uint32 end) = _dripsRange(receiver, updateTime, maxEnd, squeezeStartCap, squeezeEndCap); amt += _drippedAmt(receiver.config.amtPerSec(), start, end); } return uint128(amt); } }
3,827,160
./partial_match/80001/0x636C4701Fdd1C46e47177cef7032b26402Bf7251/sources/minter1.sol
Returns the largest of two numbers./
function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; }
8,818,592
./partial_match/1/0x76Fa672E9962AD8bf78D8029178312C8b4792746/sources/ProToken.sol
approve token transfer to cover all possible scenarios add the liquidity
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(pcsV2Router), tokenAmount); address(this), tokenAmount, dead, block.timestamp ); }
4,016,036
// SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; pragma abicoder v2; import "./ERC1155WoonklyNFT.sol"; import "./BeaconProxy.sol"; import "./Ownable.sol"; /** * @dev This contract is for creating proxy to access ERC1155WoonklyNFT token. * * The beacon should be initialized before call ERC1155WoonklyNFTFactoryC2 constructor. * */ contract ERC1155WoonklyNFTFactoryC2 is Ownable{ address public beacon; address transferProxy; address lazyTransferProxy; event Create1155WoonklyNFTProxy(address proxy); event Create1155WoonklyNFTUserProxy(address proxy); constructor(address _beacon, address _transferProxy, address _lazyTransferProxy) { beacon = _beacon; transferProxy = _transferProxy; lazyTransferProxy = _lazyTransferProxy; } function createToken(string memory _name, string memory _symbol, string memory baseURI, string memory contractURI, uint salt) external { address beaconProxy = deployProxy(getData(_name, _symbol, baseURI, contractURI), salt); ERC1155WoonklyNFT token = ERC1155WoonklyNFT(beaconProxy); token.transferOwnership(_msgSender()); emit Create1155WoonklyNFTProxy(beaconProxy); } function createToken(string memory _name, string memory _symbol, string memory baseURI, string memory contractURI, address[] memory operators, uint salt) external { address beaconProxy = deployProxy(getData(_name, _symbol, baseURI, contractURI, operators), salt); ERC1155WoonklyNFT token = ERC1155WoonklyNFT(address(beaconProxy)); token.transferOwnership(_msgSender()); emit Create1155WoonklyNFTUserProxy(beaconProxy); } //deploying BeaconProxy contract with create2 function deployProxy(bytes memory data, uint salt) internal returns(address proxy){ bytes memory bytecode = getCreationBytecode(data); assembly { proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt) if iszero(extcodesize(proxy)) { revert(0, 0) } } } //adding constructor arguments to BeaconProxy bytecode function getCreationBytecode(bytes memory _data) internal view returns (bytes memory) { return abi.encodePacked(type(BeaconProxy).creationCode, abi.encode(beacon, _data)); } //returns address that contract with such arguments will be deployed on function getAddress(string memory _name, string memory _symbol, string memory baseURI, string memory contractURI, uint _salt) public view returns (address) { bytes memory bytecode = getCreationBytecode(getData(_name, _symbol, baseURI, contractURI)); bytes32 hash = keccak256( abi.encodePacked(bytes1(0xff), address(this), _salt, keccak256(bytecode)) ); return address(uint160(uint(hash))); } function getData(string memory _name, string memory _symbol, string memory baseURI, string memory contractURI) view internal returns(bytes memory){ return abi.encodeWithSelector(ERC1155WoonklyNFT(0).__ERC1155WoonklyNFT_init.selector, _name, _symbol, baseURI, contractURI, transferProxy, lazyTransferProxy); } //returns address that contract with such arguments will be deployed on function getAddress(string memory _name, string memory _symbol, string memory baseURI, string memory contractURI, address[] memory operators, uint _salt) public view returns (address) { bytes memory bytecode = getCreationBytecode(getData(_name, _symbol, baseURI, contractURI, operators)); bytes32 hash = keccak256( abi.encodePacked(bytes1(0xff), address(this), _salt, keccak256(bytecode)) ); return address(uint160(uint(hash))); } function getData(string memory _name, string memory _symbol, string memory baseURI, string memory contractURI, address[] memory operators) view internal returns(bytes memory){ return abi.encodeWithSelector(ERC1155WoonklyNFT(0).__ERC1155WoonklyNFTUser_init.selector, _name, _symbol, baseURI, contractURI, operators, transferProxy, lazyTransferProxy); } }
adding constructor arguments to BeaconProxy bytecode
function getCreationBytecode(bytes memory _data) internal view returns (bytes memory) { return abi.encodePacked(type(BeaconProxy).creationCode, abi.encode(beacon, _data)); }
1,704,973
./partial_match/1/0x95eb587da41BdE84c71ba43c1B3657E0276f8A52/sources/Presale.sol
Calculates the amount of token to get based on amount of ETH
function getAmount(uint amount) public view returns (uint) { return ((amount * terms.ethPrice) / getPrice()); }
9,181,719
pragma solidity 0.5.17; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20, SafeMath} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {ICore} from "../interfaces/ICore.sol"; import {IDUSD} from "../interfaces/IDUSD.sol"; import {Initializable} from "../common/Initializable.sol"; import {OwnableProxy} from "../common/OwnableProxy.sol"; contract LPTokenWrapper { using SafeMath for uint; using SafeERC20 for IERC20; IERC20 public dusd; uint public totalSupply; mapping(address => uint) private _balances; function balanceOf(address account) public view returns (uint) { return _balances[account]; } function stake(uint amount) public { totalSupply = totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); dusd.safeTransferFrom(msg.sender, address(this), amount); } function withdraw(uint amount) public { totalSupply = totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); } } contract StakeLPToken is OwnableProxy, Initializable, LPTokenWrapper { ICore public core; uint public rewardPerTokenStored; uint public deficit; bool public isPaused; mapping(address => uint) public userRewardPerTokenPaid; mapping(address => uint) public rewards; event Staked(address indexed user, uint indexed amount); event Withdrawn(address indexed user, uint indexed amount); event RewardPaid(address indexed user, uint indexed reward); event RewardPerTokenUpdated(uint indexed rewardPerToken, uint indexed when); event DeficitUpdated(uint indexed deficit); modifier onlyCore() { require( msg.sender == address(core), "Not authorized" ); _; } function initialize(ICore _core, IERC20 _dusd) public notInitialized { core = _core; dusd = _dusd; } modifier updateReward(address account) { if (account != address(0)) { rewards[account] = _earned(rewardPerTokenStored, account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } // stake visibility is public as overriding LPTokenWrapper's stake() function function stake(uint amount) public updateReward(msg.sender) { require(!isPaused, "Staking is paused"); require(amount > 0, "Cannot stake 0"); super.stake(amount); emit Staked(msg.sender, amount); } function withdraw(uint amount) public updateReward(msg.sender) { _withdraw(amount); } function exit() external { getReward(); _withdraw(balanceOf(msg.sender)); } function getReward() public updateReward(msg.sender) { uint reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; // this contract had received the reward tokens during the call to core.rewardDistributionCheckpoint() dusd.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } // View Functions function earned(address account) public view returns (uint) { return _earned(rewardPerTokenStored, account); } function withdrawAble(address account) public view returns(uint) { return balanceOf(account); } function toggleIsPaused(bool _isPaused) external onlyOwner { isPaused = _isPaused; } // Internal functions function _earned(uint _rewardPerTokenStored, address account) internal view returns(uint) { return balanceOf(account) .mul(_rewardPerTokenStored.sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } function _withdraw(uint amount) internal { if (amount == 0) { // there might be case where user has 0 staked funds, but called getReward() return; } super.withdraw(amount); dusd.safeTransfer(msg.sender, amount); } }
there might be case where user has 0 staked funds, but called getReward()
function _withdraw(uint amount) internal { if (amount == 0) { return; } super.withdraw(amount); dusd.safeTransfer(msg.sender, amount); }
13,022,003
pragma solidity ^0.5.17; /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. /// @author Stefan George - <[email protected]> contract MultiSigWallet { /* * Events */ event Confirmation(address indexed sender, uint256 indexed transactionId); event Revocation(address indexed sender, uint256 indexed transactionId); event Submission(uint256 indexed transactionId); event Execution(uint256 indexed transactionId); event ExecutionFailure(uint256 indexed transactionId); event Deposit(address indexed sender, uint256 value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint256 required); /* * Constants */ uint256 constant public MAX_OWNER_COUNT = 50; /* * Storage */ mapping (uint256 => Transaction) public transactions; mapping (uint256 => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; uint256 public required; uint256 public transactionCount; struct Transaction { address destination; uint256 value; bytes data; bool executed; uint256 timestamp; } /* * Modifiers */ modifier onlyWallet() { require(msg.sender == address(this), "Only wallet"); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner], "Owner exists"); _; } modifier ownerExists(address owner) { require(isOwner[owner], "Owner does not exists"); _; } modifier transactionExists(uint256 transactionId) { require(transactions[transactionId].destination != address(0), "Tx doesn't exist"); _; } modifier confirmed(uint256 transactionId, address owner) { require(confirmations[transactionId][owner], "not confirmed"); _; } modifier notConfirmed(uint256 transactionId, address owner) { require(!confirmations[transactionId][owner], "is already confirmed"); _; } modifier notExecuted(uint256 transactionId) { require(!transactions[transactionId].executed, "tx already executed"); _; } modifier notNull(address _address) { require(_address != address(0), "address is null"); _; } modifier validRequirement(uint256 ownerCount, uint256 _required) { require(ownerCount <= MAX_OWNER_COUNT && _required <= ownerCount && _required != 0 && ownerCount != 0, "invalid requirement"); _; } /// @dev Fallback function allows to deposit ether. function() external payable { if (msg.value > 0) emit Deposit(msg.sender, msg.value); } /* * Public functions */ /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. constructor(address[] memory _owners, uint256 _required) public validRequirement(_owners.length, _required) { for (uint256 i = 0; i < _owners.length; i++) { require(!isOwner[_owners[i]] && _owners[i] != address(0), "is already owner"); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param owner Address of new owner to add. function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); emit OwnerAddition(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param owner Address of owner to remove. function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint256 i = 0; i < owners.length - 1; i++){ if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); emit OwnerRemoval(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param owner Address of owner to be replaced. /// @param newOwner Address of new owner. function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for(uint256 i = 0; i < owners.length; i++) { if (owners[i] == owner) { owners[i] = newOwner; break; } } isOwner[owner] = false; isOwner[newOwner] = true; emit OwnerRemoval(owner); emit OwnerAddition(newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint256 _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; emit RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function submitTransaction(address destination, uint256 value, bytes memory data) public returns (uint256 transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint256 transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; emit Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint256 transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; emit Revocation(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint256 transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; if (external_call(txn.destination, txn.value, txn.data.length, txn.data)) emit Execution(transactionId); else { emit ExecutionFailure(transactionId); txn.executed = false; } } } // call has been separated into its own function in order to take advantage // of the Solidity's code generator to produce a loop that copies tx.data into memory. function external_call(address destination, uint256 value, uint256 dataLength, bytes memory data) internal returns (bool) { bool result; assembly { let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention) let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that result := call( sub(gas, 34710), // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) + // callNewAccountGas (25000, in case the destination address does not exist and needs creating) destination, value, d, dataLength, // Size of the input (in bytes) - this is what fixes the padding problem x, 0 // Output is ignored, therefore the output size is zero ) } return result; } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint256 transactionId) public view returns (bool) { uint256 count = 0; for (uint256 i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } } /* * Internal functions */ /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function addTransaction(address destination, uint256 value, bytes memory data) internal notNull(destination) returns (uint256 transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false, timestamp: now }); transactionCount += 1; emit Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint256 transactionId) public view returns (uint256 count) { for (uint256 i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; } } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public view returns (uint256 count) { for (uint256 i = 0; i < transactionCount; i++) { if ( pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; } } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public view returns (address[] memory) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint256 transactionId) public view returns (address[] memory _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint256 count = 0; uint256 i; for (i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } } _confirmations = new address[](count); for (i = 0; i < count; i++) { _confirmations[i] = confirmationsTemp[i]; } } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint256 from, uint256 to, bool pending, bool executed) public view returns (uint256[] memory _transactionIds) { uint256[] memory transactionIdsTemp = new uint256[](transactionCount); uint256 count = 0; uint256 i; for (i = 0; i < transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } _transactionIds = new uint256[](to - from); for (i = from; i < to; i++){ _transactionIds[i - from] = transactionIdsTemp[i]; } } function getTransaction(uint256 transactionId) public view returns (bytes memory, address, bool, uint256) { Transaction memory txn = transactions[transactionId]; return ( txn.data, txn.destination, txn.executed, txn.timestamp ); } }
Web3 call functions/ Returns number of confirmations of a transaction. transactionId Transaction ID. return Number of confirmations.
function getConfirmationCount(uint256 transactionId) public view returns (uint256 count) { for (uint256 i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; } }
193,839
./partial_match/4/0x0320EBFf242764a464E59a5e14225E9739719354/sources/Inflator.sol
Deflate position by `value` rounds Rounds to deflate (0 for full)/
function deflate(uint rounds, address donor) public auth(DEFLATE_ROLE) { for(uint i = 0; i < rounds || rounds == 0; i++) { uint amount = redeemBorrowAmount(); if (i == 0 && donor != address(0)) deflateOnceInternal(amount, donor); else deflateOnceInternal(amount, address(0)); } }
8,694,912
./partial_match/1/0x90c3F762e4AD84e105f172a44C526280498A5eb8/sources/Punk.sol
Tax fee Take liquidity fee
function collectFee(address account, uint256 amount, uint256 rate) private returns (uint256) { uint256 transferAmount = amount; if(_taxFee != 0){ uint256 taxFee = amount.mul(_taxFee).div(10**(_feeDecimal + 2)); transferAmount = transferAmount.sub(taxFee); _reflectionTotal = _reflectionTotal.sub(taxFee.mul(rate)); _taxFeeTotal = _taxFeeTotal.add(taxFee); emit RewardsDistributed(taxFee); } if(_liquidityFee != 0){ uint256 liquidityFee = amount.mul(_liquidityFee).div(10**(_feeDecimal + 2)); transferAmount = transferAmount.sub(liquidityFee); _reflectionBalance[address(this)] = _reflectionBalance[address(this)].add(liquidityFee.mul(rate)); _liquidityFeeTotal = _liquidityFeeTotal.add(liquidityFee); emit Transfer(account,address(this),liquidityFee); } return transferAmount; }
2,713,426
/** */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; library SafeMath { 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); } } function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } library Strings { bytes16 private constant alphabet = "0123456789abcdef"; function toString(uint256 value) internal pure returns (string memory) { 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); } 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); } 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] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "hi"); //Strings: hex length insufficient return string(buffer); } } library Address { function isContract(address account) internal view returns (bool) { uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "< balance!" // "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "unable" // "Address: unable to send value, recipient may have reverted" ); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "F!"); //"Address: low-level call failed" } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "F!" // "Address: low-level call with value failed" ); } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "broke" // "Address: insufficient balance for call" ); require(isContract(target), "nC"); //"Address: call to non-contract" // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: value}( data ); return _verifyCallResult(success, returndata, errorMessage); } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "f!" // "Address: low-level static call failed" ); } function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "nC"); //Address: static call to non-contract // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "cF" // "Address: low-level delegate call failed" ); } function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "nC"); //Address: delegate call to non-contract // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { if (returndata.length > 0) { // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } pragma solidity ^0.8.0; interface IERC721Receiver { function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } abstract contract ERC165 is IERC165 { function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } interface IERC721 is IERC165 { event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); event NothingMinted(address sender, uint256 tokenId); event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom( address from, address to, uint256 tokenId ) external; function transferFrom( address from, address to, uint256 tokenId ) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } interface IERC721Enumerable is IERC721 { function totalSupply() external view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); function tokenByIndex(uint256 index) external view returns (uint256); } interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; return msg.data; } } pragma solidity ^0.8.0; abstract 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 virtual 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; } } contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; string private _name; string private _symbol; mapping(uint256 => address) private _owners; mapping(address => uint256) private _balances; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "zero" ); return _balances[owner]; } function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require( owner != address(0), "no" ); return owner; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "non" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } function _baseURI() internal view virtual returns (string memory) { return ""; } function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "app"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "nor" ); _approve(to, tokenId); } function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), "N-T" ); return _tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "aTc"); // "ERC721: approve to caller" _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "nor" ); _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "nO" ); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "tTnEi" // "ERC721: transfer to non ERC721Receiver implementer" ); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "oQnT" // "ERC721: operator query for nonexistent token" ); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "tNi" // "ERC721: transfer to non ERC721Receiver implementer" ); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "mZa"); // mint to zero address require(!_exists(tokenId), "minted"); _beforeTokenTransfer(address(0), to, tokenId, true); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId, true); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } function _burnSave(address owner, uint256 tokenId) internal virtual { _beforeTokenTransfer(owner, address(0), tokenId, false); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, "tTtNo" // "ERC721: transfer of token that is not own" ); require(to != address(0), "tTzA" ); //"ERC721: transfer to the zero address" _beforeTokenTransfer(from, to, tokenId, true); _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "tTzI" // "ERC721: transfer to non ERC721Receiver implementer" ); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId, bool isDelete ) internal virtual {} } pragma solidity ^0.8.0; abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { mapping(address => mapping(uint256 => uint256)) private _ownedTokens; mapping(uint256 => uint256) private _ownedTokensIndex; uint256[] private _allTokens; mapping(uint256 => uint256) private _allTokensIndex; function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require( index < ERC721.balanceOf(owner), "oIoB" // "ERC721Enumerable: owner index out of bounds" ); return _ownedTokens[owner][index]; } function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require( index < ERC721Enumerable.totalSupply(), "gIoB" // "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, bool isDelete ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId, isDelete); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0) && isDelete) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from && isDelete) { _addTokenToOwnerEnumeration(to, tokenId); } } function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _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 } 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(); } } contract Nothing888 is ERC721Enumerable, Ownable { using SafeMath for uint256; using Address for address; using Strings for uint256; uint256 public constant NFT_PRICE = 50000000000000000; uint256 public constant MAX_NFT_PURCHASE = 5; uint256 public MAX_SUPPLY = 888; bool public saleIsActive = true; string private _baseURIExtended; mapping(uint256 => string) _tokenURIs; constructor() ERC721("NOTHING", "NOTHING") {} function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } function XxX(uint256 num) public onlyOwner { uint256 supply = totalSupply(); uint256 i; for (i = 0; i < num; i++) { _safeMint(msg.sender, supply + i); } } function mint(uint256 numberOfTokensMax5) public payable { require(saleIsActive, "NO!"); require( numberOfTokensMax5 > 0, "NO!" ); require( totalSupply().add(numberOfTokensMax5) <= MAX_SUPPLY, "SOLD OUT!" ); require( numberOfTokensMax5 <= MAX_NFT_PURCHASE, "MAX 5" ); require( NFT_PRICE.mul(numberOfTokensMax5) == msg.value, "WrongAmt!" ); for (uint256 i = 0; i < numberOfTokensMax5; i++) { _safeMint(msg.sender, totalSupply()); } emit NothingMinted(msg.sender, totalSupply()); } function toString(uint256 value) internal pure returns (string memory) { 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); } function tokenURI(uint256 tokenId) public pure override returns (string memory) { // uint something = 666; string[4] memory parts; parts[ 0 ] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: #000005; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="230" y="340" class="base">'; parts[1] = toString(tokenId); parts[2] = " NOTHING"; if(tokenId < 11 || tokenId == 111 || tokenId == 222 || tokenId == 333 || tokenId == 444 || tokenId == 555 || tokenId == 666 || tokenId == 777 || tokenId == 888) { parts[2] = " SOMETHING"; } parts[3] = "</text></svg>"; string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2])); output = string(abi.encodePacked(output, parts[3])); string memory json = Base64.encode( bytes( string( abi.encodePacked( '{"name": " #', toString(tokenId), '", "description": "NOTHING", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}' ) ) ) ); output = string( abi.encodePacked("data:application/json;base64,", json) ); return output; } } library Base64 { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; uint256 encodedLen = 4 * ((len + 2) / 3); 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); } }
"Address: insufficient balance" solhint-disable-next-line avoid-low-level-calls, avoid-call-value "Address: unable to send value, recipient may have reverted"
function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "< balance!" ); require( success, "unable" ); }
6,250,018
./partial_match/5/0xe5573Cf4703fe9c7b1abD9bcD0AB73fCfCeCb29C/sources/contracts/PoS.sol
Instantiates a Proof of Stake _stakingAddress address of StakingInterface _blockSelectorAddress address of blockSelector contract _workerAuthAddress address of worker manager contract _difficultyAdjustmentParameter how quickly the difficulty gets updated according to the difference between time passed and desired draw time interval. _targetInterval how often we want to elect a block producer _rewardManagerAddress address containing the tokens that will be distributed
function instantiate( address _stakingAddress, address _blockSelectorAddress, address _workerAuthAddress, uint256 _minimumDifficulty, uint256 _initialDifficulty, uint256 _difficultyAdjustmentParameter, uint256 _targetInterval, address _rewardManagerAddress ) public onlyOwner() returns (uint256) { instance[currentIndex].staking = Staking(_stakingAddress); instance[currentIndex].blockSelector = BlockSelector(_blockSelectorAddress); instance[currentIndex].rewardManager = RewardManager( _rewardManagerAddress ); instance[currentIndex].workerAuth = WorkerAuthManager( _workerAuthAddress ); instance[currentIndex].blockSelectorIndex = instance[currentIndex] .blockSelector .instantiate( _minimumDifficulty, _initialDifficulty, _difficultyAdjustmentParameter, _targetInterval, address(this) ); active[currentIndex] = true; return currentIndex++; }
16,847,534
./partial_match/1/0x82F0137B5dd98688dd2a4128bdE21B1F3cF4BFc6/sources/TheBoysClub.sol
once enabled, can never be turned off
function startTrading() external onlyOwner { swappingStart = true; tradeActivate = true; lastLpBurnTime = block.timestamp; }
2,878,913
./full_match/5/0xEBE0506b0481f873b12C0BCF423f6ad241C40ACc/sources/home/felipenovaesrocha/Projects/1Hive/staking/packages/protocol/contracts/Staking.sol
Tell details of `_user`'s lock managed by `_lockManager` _user Address _lockManager Lock manager return Amount of locked tokens return Amount of tokens that lock manager is allowed to lock/
function getLock(address _user, address _lockManager) external view returns ( uint256 amount, uint256 allowance ) { Lock storage lock_ = accounts[_user].locks[_lockManager]; amount = lock_.amount; allowance = lock_.allowance; }
11,619,246
./full_match/421613/0x3b40C31DdAc6f1Ef4959c31177794A330F0C2BA8/sources/contracts/facets/KaijuFacet.sol
console.log('SOLIDITY: _beforeTokenTransfer'); console.log('from is not address(0)'); console.log( 'SOLIDITY: _beforeTokenTransfer loop for ids[i]', ids[i] );
function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override pausable { if (from != address(0)) { require( _token().pioneerTradingIsEnabled, 'Trading for Pioneer Kaijus is currently disabled' ); } for (uint256 i; i < ids.length; i++) { if (from != address(0)) { require( _token().isTokenTradable[ids[i]], 'Token locked for trading' ); _token().numTradesSinceTransmog[i] = 0; } .numTradesSinceTransmog[i] >= _constants().NUM_TRADES_ALLOWED_AFTER_TRANSMOG; if (tokenReachedTransmogTradeLimit == true) { revert('Token reached transmog limit'); _token().numTradesSinceTransmog[i]++; } _token().ownerOf[ids[i]] = to; } super._beforeTokenTransfer(operator, from, to, ids, amounts, data); }
11,567,649
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import { L1BuildAgent } from "./L1BuildAgent.sol"; import { L1BuildParam } from "./L1BuildParam.sol"; import { ChainStorageContainer } from "../../../L1/rollup/ChainStorageContainer.sol"; import { OasysStateCommitmentChain } from "../rollup/OasysStateCommitmentChain.sol"; import { BondManager } from "../../../L1/verification/BondManager.sol"; /** * @title L1BuildStep2 * @dev L1BuildStep2 is the parial contract to build the Verse-Layer. */ contract L1BuildStep2 { /********************** * Contract Variables * **********************/ address public agentAddress; address public paramAddress; address public verifierInfoAddress; /******************** * Public Functions * ********************/ /** * Sets the addresses of the L1BuildAgent and L1BuildParam contract. * @param _agentAddress Address of the L1BuildAgent contract. * @param _paramAddress Address of the L1BuildParam contract. * @param _verifierInfoAddress Address of the VerifierInfo contract. */ function initialize( address _agentAddress, address _paramAddress, address _verifierInfoAddress ) external { require( agentAddress == address(0) && paramAddress == address(0) && verifierInfoAddress == address(0), "initialize only once" ); agentAddress = _agentAddress; paramAddress = _paramAddress; verifierInfoAddress = _verifierInfoAddress; } /** * Deploys the contracts of CanonicalTransactionChain, StateCommitmentChain and BondManager. * @param _chainId Chain ID of the Verse-Layer network. */ function build(uint256 _chainId, address _builder) external { require(msg.sender == agentAddress, "only the L1BuildAgent can call"); address addressManager = L1BuildAgent(agentAddress).getAddressManager(_chainId); OasysStateCommitmentChain stateCommitmentChain = new OasysStateCommitmentChain( addressManager, L1BuildParam(paramAddress).fraudProofWindow(), L1BuildParam(paramAddress).sequencerPublishWindow(), verifierInfoAddress ); stateCommitmentChain.transferOwnership(_builder); ChainStorageContainer sccBatches = new ChainStorageContainer( addressManager, "StateCommitmentChain" ); BondManager bondManager = new BondManager(addressManager); L1BuildAgent(agentAddress).setStep2Addresses( _chainId, address(stateCommitmentChain), address(sccBatches), address(bondManager) ); } }
Deploys the contracts of CanonicalTransactionChain, StateCommitmentChain and BondManager. _chainId Chain ID of the Verse-Layer network./
function build(uint256 _chainId, address _builder) external { require(msg.sender == agentAddress, "only the L1BuildAgent can call"); address addressManager = L1BuildAgent(agentAddress).getAddressManager(_chainId); OasysStateCommitmentChain stateCommitmentChain = new OasysStateCommitmentChain( addressManager, L1BuildParam(paramAddress).fraudProofWindow(), L1BuildParam(paramAddress).sequencerPublishWindow(), verifierInfoAddress ); stateCommitmentChain.transferOwnership(_builder); ChainStorageContainer sccBatches = new ChainStorageContainer( addressManager, "StateCommitmentChain" ); BondManager bondManager = new BondManager(addressManager); L1BuildAgent(agentAddress).setStep2Addresses( _chainId, address(stateCommitmentChain), address(sccBatches), address(bondManager) ); }
5,357,973
/** * @title DVIP Contract. DCAsset Membership Token contract. * * @author Ray Pulver, [email protected] */ contract Relay { function relayReceiveApproval(address _caller, address _spender, uint256 _amount, bytes _extraData) returns (bool success); } contract DVIPBackend { uint8 public decimals; function assert(bool assertion) { if (!assertion) throw; } address public owner; event SetOwner(address indexed previousOwner, address indexed newOwner); modifier onlyOwner { assert(msg.sender == owner); _ } function setOwner(address newOwner) onlyOwner { SetOwner(owner, newOwner); owner = newOwner; } bool internal locked; event Locked(address indexed from); event PropertySet(address indexed from); modifier onlyIfUnlocked { assert(!locked); _ } modifier setter { _ PropertySet(msg.sender); } modifier onlyOwnerUnlocked { assert(!locked && msg.sender == owner); _ } function lock() onlyOwner onlyIfUnlocked { locked = true; Locked(msg.sender); } function isLocked() returns (bool status) { return locked; } bytes32 public standard = 'Token 0.1'; bytes32 public name; bytes32 public symbol; bool public allowTransactions; uint256 public totalSupply; event Approval(address indexed from, address indexed spender, uint256 amount); mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); function () { throw; } uint256 public expiry; uint8 public feeDecimals; mapping (address => uint256) public validAfter; uint256 public mustHoldFor; address public hotwalletAddress; address public frontendAddress; mapping (address => bool) public frozenAccount; mapping (address => uint256) public exportFee; event FeeSetup(address indexed from, address indexed target, uint256 amount); event Processed(address indexed sender); modifier onlyAsset { if (msg.sender != frontendAddress) throw; _ } /** * Constructor. * */ function DVIPBackend(address _hotwalletAddress, address _frontendAddress) { owner = msg.sender; hotwalletAddress = _hotwalletAddress; frontendAddress = _frontendAddress; allowTransactions = true; totalSupply = 0; name = "DVIP"; symbol = "DVIP"; feeDecimals = 6; expiry = 1514764800; //1 jan 2018 mustHoldFor = 86400; } function setHotwallet(address _address) onlyOwnerUnlocked { hotwalletAddress = _address; PropertySet(msg.sender); } function setFrontend(address _address) onlyOwnerUnlocked { frontendAddress = _address; PropertySet(msg.sender); } /** * @notice Transfer `_amount` from `msg.sender.address()` to `_to`. * * @param _to Address that will receive. * @param _amount Amount to be transferred. */ function transfer(address caller, address _to, uint256 _amount) onlyAsset returns (bool success) { assert(allowTransactions); assert(balanceOf[caller] >= _amount); assert(balanceOf[_to] + _amount >= balanceOf[_to]); assert(!frozenAccount[caller]); assert(!frozenAccount[_to]); balanceOf[caller] -= _amount; uint256 preBalance = balanceOf[_to]; balanceOf[_to] += _amount; if (preBalance <= 1 && balanceOf[_to] >= 1) { validAfter[_to] = now + mustHoldFor; } Transfer(caller, _to, _amount); return true; } /** * @notice Transfer `_amount` from `_from` to `_to`. * * @param _from Origin address * @param _to Address that will receive * @param _amount Amount to be transferred. * @return result of the method call */ function transferFrom(address caller, address _from, address _to, uint256 _amount) onlyAsset returns (bool success) { assert(allowTransactions); assert(balanceOf[_from] >= _amount); assert(balanceOf[_to] + _amount >= balanceOf[_to]); assert(_amount <= allowance[_from][caller]); assert(!frozenAccount[caller]); assert(!frozenAccount[_from]); assert(!frozenAccount[_to]); balanceOf[_from] -= _amount; uint256 preBalance = balanceOf[_to]; balanceOf[_to] += _amount; allowance[_from][caller] -= _amount; if (balanceOf[_to] >= 1 && preBalance <= 1) { validAfter[_to] = now + mustHoldFor; } Transfer(_from, _to, _amount); return true; } /** * @notice Approve spender `_spender` to transfer `_amount` from `msg.sender.address()` * * @param _spender Address that receives the cheque * @param _amount Amount on the cheque * @param _extraData Consequential contract to be executed by spender in same transcation. * @return result of the method call */ function approveAndCall(address caller, address _spender, uint256 _amount, bytes _extraData) onlyAsset returns (bool success) { assert(allowTransactions); allowance[caller][_spender] = _amount; Relay(frontendAddress).relayReceiveApproval(caller, _spender, _amount, _extraData); Approval(caller, _spender, _amount); return true; } /** * @notice Approve spender `_spender` to transfer `_amount` from `msg.sender.address()` * * @param _spender Address that receives the cheque * @param _amount Amount on the cheque * @return result of the method call */ function approve(address caller, address _spender, uint256 _amount) onlyAsset returns (bool success) { assert(allowTransactions); allowance[caller][_spender] = _amount; Approval(caller, _spender, _amount); return true; } /* --------------- multisig admin methods --------------*/ /** * @notice Sets the expiry time in milliseconds since 1970. * * @param ts milliseconds since 1970. * */ function setExpiry(uint256 ts) onlyOwner { expiry = ts; Processed(msg.sender); } /** * @notice Mints `mintedAmount` new tokens to the hotwallet `hotWalletAddress`. * * @param mintedAmount Amount of new tokens to be minted. */ function mint(uint256 mintedAmount) onlyOwner { balanceOf[hotwalletAddress] += mintedAmount; totalSupply += mintedAmount; Processed(msg.sender); } function freezeAccount(address target, bool frozen) onlyOwner { frozenAccount[target] = frozen; Processed(msg.sender); } function seizeTokens(address target, uint256 amount) onlyOwner { assert(balanceOf[target] >= amount); assert(frozenAccount[target]); balanceOf[target] -= amount; balanceOf[hotwalletAddress] += amount; Transfer(target, hotwalletAddress, amount); } function destroyTokens(uint256 amt) onlyOwner { assert(balanceOf[hotwalletAddress] >= amt); balanceOf[hotwalletAddress] -= amt; Processed(msg.sender); } /** * @notice Sets an export fee of `fee` on address `addr` * * @param addr Address for which the fee is valid * @param addr fee Fee * */ function setExportFee(address addr, uint256 fee) onlyOwner { exportFee[addr] = fee; Processed(msg.sender); } function setHoldingPeriod(uint256 ts) onlyOwner { mustHoldFor = ts; Processed(msg.sender); } function setAllowTransactions(bool allow) onlyOwner { allowTransactions = allow; Processed(msg.sender); } /* --------------- fee calculation method ---------------- */ /** * @notice 'Returns the fee for a transfer from `from` to `to` on an amount `amount`. * * Fee's consist of a possible * - import fee on transfers to an address * - export fee on transfers from an address * DVIP ownership on an address * - reduces fee on a transfer from this address to an import fee-ed address * - reduces the fee on a transfer to this address from an export fee-ed address * DVIP discount does not work for addresses that have an import fee or export fee set up against them. * * DVIP discount goes up to 100% * * @param from From address * @param to To address * @param amount Amount for which fee needs to be calculated. * */ function feeFor(address from, address to, uint256 amount) constant external returns (uint256 value) { uint256 fee = exportFee[from]; if (fee == 0) return 0; if ((exportFee[from] == 0 && balanceOf[from] != 0 && now < expiry && validAfter[from] <= now) || (balanceOf[to] != 0 && now < expiry && validAfter[to] <= now)) return 0; return div10(amount*fee, feeDecimals); } function div10(uint256 a, uint8 b) internal returns (uint256 result) { for (uint8 i = 0; i < b; i++) { a /= 10; } return a; } }
Approve spender `_spender` to transfer `_amount` from `msg.sender.address()` _spender Address that receives the cheque _amount Amount on the cheque _extraData Consequential contract to be executed by spender in same transcation. return result of the method call/
function approveAndCall(address caller, address _spender, uint256 _amount, bytes _extraData) onlyAsset returns (bool success) { assert(allowTransactions); allowance[caller][_spender] = _amount; Relay(frontendAddress).relayReceiveApproval(caller, _spender, _amount, _extraData); Approval(caller, _spender, _amount); return true; }
2,512,487
./partial_match/1/0x2Ccc01b6F6230FB6C59218ec4bEbAe273cE0E517/sources/contracts/DarwinSwapRouter.sol
REMOVE LIQUIDITY
function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) { address pair = DarwinSwapLibrary.pairFor(factory, tokenA, tokenB); (uint amount0, uint amount1) = IDarwinSwapPair(pair).burn(to); if ( msg.sender != address(IDarwinSwapFactory(factory).liquidityBundles()) ) { IDarwinSwapFactory(factory).liquidityBundles().update(pair); } (address token0, ) = DarwinSwapLibrary.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require( amountA >= amountAMin, "DarwinSwapRouter: INSUFFICIENT_A_AMOUNT" ); require( amountB >= amountBMin, "DarwinSwapRouter: INSUFFICIENT_B_AMOUNT" ); }
3,619,750
pragma solidity 0.5.13; import "@daostack/infra/contracts/Reputation.sol"; import "../controller/DAOToken.sol"; import "../controller/Avatar.sol"; import "../controller/Controller.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; /** * @title An on-chain "source of truth" for what DAOs * should be index into DAOstack's subgraph. */ contract DAOTracker is Ownable { // `blacklist` the DAO from the subgraph's cache. // Only able to be set by the owner of the DAOTracker. mapping(address=>bool) public blacklisted; event TrackDAO( address indexed _avatar, address _controller, address _reputation, address _daoToken, address _sender, string _arcVersion ); event BlacklistDAO( address indexed _avatar, string _explanationHash ); event ResetDAO( address indexed _avatar, string _explanationHash ); modifier onlyAvatarOwner(Avatar avatar) { require(avatar.owner() == msg.sender, "The caller must be the owner of the Avatar."); _; } modifier notBlacklisted(Avatar avatar) { require(blacklisted[address(avatar)] == false, "The avatar has been blacklisted."); _; } /** * @dev track a new organization. This function will tell the subgraph * to start ingesting events from the DAO's contracts. * NOTE: This function should be called as early as possible in the DAO deployment * process. **Smart Contract Events that are emitted from blocks prior to this function's * event being emitted WILL NOT be ingested into the subgraph**, leading to an incorrect * cache. If this happens to you, please contact the subgraph maintainer. Your DAO will * need to be added to the subgraph's startup config, and the cache will need to be rebuilt. * @param _avatar the organization avatar * @param _controller the organization controller */ function track(Avatar _avatar, Controller _controller, string memory _arcVersion) public onlyAvatarOwner(_avatar) notBlacklisted(_avatar) { // Only allow the information to be set once. In the case of a controller upgrades, // the subgraph will be updated via the UpgradeController event. require(_avatar != Avatar(0)); require(_controller != Controller(0)); emit TrackDAO( address(_avatar), address(_controller), address(_avatar.nativeReputation()), address(_avatar.nativeToken()), msg.sender, _arcVersion ); } /** * @dev blacklist a DAO from the cache. This should be callable by maintainer of the cache. * Blacklisting can be used to defend against DoS attacks, or to remove spam. In order * for this blacklisting to take affect within the cache, it would need to be rebuilt. * @param _avatar the organization avatar * @param _explanationHash A hash of a document explaining why this DAO was blacklisted */ function blacklist(Avatar _avatar, string memory _explanationHash) public onlyOwner { require(_avatar != Avatar(0)); blacklisted[address(_avatar)] = true; emit BlacklistDAO(address(_avatar), _explanationHash); } /** * @dev reset a DAO in the cache. This should be callable by the maintainer of the cache. * @param _avatar the organization avatar * @param _explanationHash A hash of a document explaining why this DAO was reset */ function reset(Avatar _avatar, string memory _explanationHash) public onlyOwner { require(_avatar != Avatar(0)); blacklisted[address(_avatar)] = false; emit ResetDAO(address(_avatar), _explanationHash); } }
track a new organization. This function will tell the subgraph to start ingesting events from the DAO's contracts. NOTE: This function should be called as early as possible in the DAO deployment process. Smart Contract Events that are emitted from blocks prior to this function's event being emitted WILL NOT be ingested into the subgraph, leading to an incorrect cache. If this happens to you, please contact the subgraph maintainer. Your DAO will need to be added to the subgraph's startup config, and the cache will need to be rebuilt. _avatar the organization avatar _controller the organization controller/ Only allow the information to be set once. In the case of a controller upgrades, the subgraph will be updated via the UpgradeController event.
function track(Avatar _avatar, Controller _controller, string memory _arcVersion) public onlyAvatarOwner(_avatar) notBlacklisted(_avatar) { require(_avatar != Avatar(0)); require(_controller != Controller(0)); emit TrackDAO( address(_avatar), address(_controller), address(_avatar.nativeReputation()), address(_avatar.nativeToken()), msg.sender, _arcVersion ); }
7,297,951
pragma solidity ^0.4.21; // import './DOTFactory.sol'; // import './Strings.sol'; // import './StringUtils.sol'; import '@daostack/arc/contracts/VotingMachines/GenesisProtocol.sol'; /** * @title MarketTrustInterface * @dev Interface for XOR Market Trust Contract for calculating trust score */ contract ExampleMarketGovernanceInterface { // Address from MarketCore function getDOTTokenAddress(uint _marketId) public returns(address); } contract ExampleMarketAvatarInterface { function createAvatar(bytes32 _strMarketId, DAOToken daoToken, Reputation reputation) public returns(address); } /** * @title ExampleMarketTrust * @dev Example Market Trust contract for showing trust score programmability. */ contract ExampleMarketGovernance { ExampleMarketGovernanceInterface exampleMarketGovernanceContract; ExampleMarketAvatarInterface exampleMarketAvatarContract; GenesisProtocol genesisProtocolContract; ExecutableInterface executableInterfaceContract; // Avatar avatar; address avatarAddress; /** * @dev Set the address of the sibling contract that tracks trust score. */ function setMarketGovernanceContractAddress(address _address) external { exampleMarketGovernanceContract = ExampleMarketGovernanceInterface(_address); } /** * @dev Get the address of the sibling contract that tracks trust score. */ function getMarketGovernanceContractAddress() external view returns(address) { return address(exampleMarketGovernanceContract); } /** * @dev Set the address of the sibling contract that tracks trust score. */ function setMarketAvatarContractAddress(address _address) external { exampleMarketAvatarContract = ExampleMarketAvatarInterface(_address); } /** * @dev Get the address of the sibling contract that tracks trust score. */ function getMarketAvatarContractAddress() external view returns(address) { return address(exampleMarketAvatarContract); } function getGenesisProtocolContractAddress() external view returns(address) { return address(genesisProtocolContract); } function createGovernance(uint _marketId, bytes32 _strMarketId) public { StandardToken dotToken = StandardToken(exampleMarketGovernanceContract.getDOTTokenAddress(_marketId)); genesisProtocolContract = new GenesisProtocol(dotToken); uint[12] memory params; params[0] = 50; params[1] = 60; params[2] = 60; params[3] = 1; params[4] = 1; params[5] = 0; params[6] = 0; params[7] = 60; params[8] = 1; params[9] = 1; params[10] = 10; params[11] = 80; genesisProtocolContract.setParameters(params); executableInterfaceContract = ExecutableInterface(address(this)); Reputation reputation = new Reputation(); DAOToken daoToken = DAOToken(exampleMarketGovernanceContract.getDOTTokenAddress(_marketId)); avatarAddress = exampleMarketAvatarContract.createAvatar(_strMarketId, daoToken, reputation); } function propose(uint _numOfChoices, address _proposer) public returns(bytes32) { genesisProtocolContract.propose(_numOfChoices, "", avatarAddress, executableInterfaceContract, msg.sender); } // function getParametersHash( // uint[12] _params) //use array here due to stack too deep issue. // public // returns(bytes32) { // return genesisProtocolContract.getParametersHash(_params); // } // function execute(bytes32 _proposalId) public { // genesisProtocolContract.execute(_proposalId); // } }
Get the address of the sibling contract that tracks trust score./
function getMarketAvatarContractAddress() external view returns(address) { return address(exampleMarketAvatarContract); }
14,084,142
./partial_match/1/0xA58B598d0503bAA97B877735c97C69Cc19c07904/sources/_contracts/synthetic/SyntheticTokenV1.sol
Add a new minter to the synthetic token. _minter The address of the minter to add _limit The starting limit for how much this synth can mint/
function addMinter( address _minter, uint256 _limit ) external onlyAdmin { require( _minters[_minter] != true, "SyntheticToken: Minter already exists" ); _mintersArray.push(_minter); _minters[_minter] = true; _minterLimits[_minter] = _limit; emit MinterAdded(_minter, _limit); }
4,271,037
./partial_match/42220/0x25271A160cf2E6Be20f462BbafB05849BbfCE3A9/sources/contracts/governance/MoolaGovernorBravoDelegate.sol
Admin function for setting the voting delay newVotingDelay new voting delay, in blocks/
function _setVotingDelay(uint256 newVotingDelay) external { require(msg.sender == admin, "GovernorBravo::_setVotingDelay: admin only"); require( newVotingDelay >= MIN_VOTING_DELAY && newVotingDelay <= MAX_VOTING_DELAY, "GovernorBravo::_setVotingDelay: invalid voting delay" ); uint256 oldVotingDelay = votingDelay; votingDelay = newVotingDelay; emit VotingDelaySet(oldVotingDelay, votingDelay); }
3,494,911
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/IPancakeRouter02.sol"; import "./interfaces/IPancakeFactory.sol"; import "./BEP20.sol"; /// @author The Development Team /// @title Token contract ConquerUranus is BEP20("ConquerUranus", "ANVS", 18) { 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 _isExcludedFromReward; address[] private _excludedFromReward; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 2543164 * 10**6 * 10**18; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; /// Control the amount on transfers to avoid dump price uint256 public _maxTxAmount = (_tTotal * 5).div(1000); uint256 private numTokensSellToAddToLiquidity = (_tTotal * 5).div(1000); /// Fee state variables section uint256 public _holderFee; uint256 public _liquidityFee; uint256 public _vaultFee; uint256 public totalSendedToTheVoid; uint256 public totalLiquidity; IPancakeRouter02 public immutable pancakeRouter; address public immutable pancakePair; address public blackHoleVaultAddress; address public spaceWasteVaultAddress; address public devAddress; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled; /// Event section event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event Burn(address indexed burner, uint256 amount); /// Modifiers section /// Modifier that uses a mutex pattern for swaps modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } /// Modifier that restricts the users who can send to the void modifier sendersToTheVoid { require( _msgSender() == owner() || _msgSender() == devAddress || _msgSender() == blackHoleVaultAddress ); _; } /// Modifier that restricts a function only for vault address modifier onlyVault { require(_msgSender() == blackHoleVaultAddress); _; } constructor ( address blackHoleVaultAddress_, address devAddress_, address routerAddress_, address spaceWasteVaultAddress_ ) { // Declaration of addresses blackHoleVaultAddress = blackHoleVaultAddress_; devAddress = devAddress_; spaceWasteVaultAddress = spaceWasteVaultAddress_; swapAndLiquifyEnabled = true; _rOwned[_msgSender()] = _rTotal; IPancakeRouter02 _pancakeRouter = IPancakeRouter02(routerAddress_); // Creation of pancake pair for the token pancakePair = IPancakeFactory(_pancakeRouter.factory()) .createPair(address(this), _pancakeRouter.WETH()); // set the rest of the contract variables pancakeRouter = _pancakeRouter; // Excluding main accounts from rewards excludeFromReward(address(this)); excludeFromReward(owner()); excludeFromReward(blackHoleVaultAddress); excludeFromReward(devAddress); excludeFromReward(spaceWasteVaultAddress); emit Transfer(address(0), _msgSender(), _tTotal); } //to recieve BNB from pancakeRouter when swaping receive() external payable {} /// This function include and account into reward system. Only an Owner can include. /// @param account The address of the account to include function includeInReward(address account) external onlyOwner { require(_isExcludedFromReward[account], "Account is already excluded"); for (uint256 i = 0; i < _excludedFromReward.length; i++) { if (_excludedFromReward[i] == account) { _excludedFromReward[i] = _excludedFromReward[_excludedFromReward.length - 1]; _tOwned[account] = 0; _isExcludedFromReward[account] = false; _excludedFromReward.pop(); break; } } } /// This function permits change the holder fee percent /// Only owner can change the fee /// @param holderFee is the new fee for holders function setHoldersFee(uint256 holderFee, uint256 liquidityFee, uint256 vaultFee) external onlyOwner { _holderFee = holderFee; _liquidityFee = liquidityFee; _vaultFee = vaultFee; } /// This function sets the max percent for transfers /// @param maxTxPercent is the new percentaje function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner { _maxTxAmount = _tTotal.mul(maxTxPercent).div( 10**2 ); } /// This function enable or disable the swap and liquify function /// @param _enabled is the boolean value to set function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } /// This is the public function to send the half of tokens in vault to the black hole /// and the other half to the dev wallet /// @return a boolean value function sendToTheVoidDevAndSpaceWasteWallet() public onlyVault returns (bool) { // Take tokens from vault uint256 amountToBlackHole = _tOwned[blackHoleVaultAddress].div(2); uint256 amountToDistribute = _tOwned[blackHoleVaultAddress].sub(amountToBlackHole); uint256 amountToDev = amountToDistribute.div(2); uint256 amountToSpaceWasteVault = amountToDistribute.sub(amountToDev); _tOwned[blackHoleVaultAddress] = 0; // We distribute to black hole and developers wallet // Sending to black hole _sendToTheVoid(amountToBlackHole); // Sending to devs wallet _tOwned[devAddress] = _tOwned[devAddress].add(amountToDev); _tOwned[spaceWasteVaultAddress] = _tOwned[spaceWasteVaultAddress].add(amountToSpaceWasteVault); emit Transfer(blackHoleVaultAddress, devAddress, amountToDev); emit Transfer(blackHoleVaultAddress, spaceWasteVaultAddress, amountToSpaceWasteVault); return true; } /// This is the public function to send tokens to the black hole /// @dev Only can burn Owner, Vault and Dev /// @param amount the quantity to burn /// @return a boolean value function sendToTheVoid(uint256 amount) public sendersToTheVoid returns (bool) { _sendToTheVoid(amount); return true; } /// This function deliver an amount to the totalFees /// @param tAmount is the quantity of token to deliver function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcludedFromReward[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); } /// This function exclude and account from reward, in case of the account have some reflection /// pass it to tokens. Only an Owner can include. /// @param account The address of the account to exclude function excludeFromReward(address account) public onlyOwner { require(!_isExcludedFromReward[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcludedFromReward[account] = true; _excludedFromReward.push(account); } /// This function calculates the conversion from normal token to reflection /// @param tAmount the quantity of token to convert /// @param deductTransferFee boolean that indicates if the conversion deduct fees in calculus or not /// @return the value in reflection 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; } } /// This function calculates the conversion from reflection to normal token /// @param rAmount the quantity of reflection to convert in token /// @return the value in token 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); } /// This function returns the total supply of tokens function totalSupply() public view override returns (uint256) { return _tTotal; } /// This functions shows the balance of an account /// @param account the account to get the balance /// @return an unsigned intger with the balance function balanceOf(address account) public view override returns (uint256) { if (_isExcludedFromReward[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } /// This function returns a boolean value depending on whether the account is /// excluded from rewards. /// @param account is the account to check if is excluded from reward /// @return boolean value with the status function isExcludedFromReward(address account) public view returns (bool) { return _isExcludedFromReward[account]; } /// This function gets a list of excluded accounts from reward. /// @return an array with the list of excluded accounts function getExcludedFromReward() public view returns (address[] memory) { return _excludedFromReward; } /// This functions return the total fees /// @return an unsigned integer with the total fees function totalFees() public view returns (uint256) { return _tFeeTotal; } /// This function burns an amount defined by param /// @param amount the amount that will be burn function _sendToTheVoid(uint256 amount) internal { require(amount <= _tTotal, "Amount must be less than total"); // Substract token to burn from sender account if(_tOwned[_msgSender()] > 0 && amount <= _tOwned[_msgSender()]){ _tOwned[_msgSender()] = _tOwned[_msgSender()].sub(amount, "Amount to burn exceeds token owned"); } // Only if account have reflection, but its not probably because dev, vault and owner are excluded from // reward uint256 ratedQuantity = amount.mul(_getRate()); if(_rOwned[_msgSender()] > 0 && ratedQuantity <= _rOwned[_msgSender()]){ _rOwned[_msgSender()] = _rOwned[_msgSender()].sub(ratedQuantity, "Amount to burn exceeds reflected token owned"); } _tOwned[address(1)] = _tOwned[address(1)].add(amount); _rOwned[address(1)] = _rOwned[address(1)].add(amount.mul(_getRate())); totalSendedToTheVoid = totalSendedToTheVoid.add((amount)); emit Transfer(_msgSender(), address(1), amount); } ///This function is responsible for transfering tokens, is modified from BEP20 /// and different functionalities have been added. /// @param from sender of the transfer /// @param to recipient of the transfer /// @param amount quantity of tokens to transfer function _transfer(address from, address to, uint256 amount) internal virtual override{ require(from != address(0), "BEP20: transfer from the zero address"); require(to != address(0), "BEP20: 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."); uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; /// Cases of condition: /// 1. The token balance of this contract is over the min number of /// tokens that we need to initiate a swap + liquidity lock (overMinTokenBalance checks it) /// 2. Avoid that don't get caught in a circular liquidity event using a mutex pattern with the modifier lockTheSwap. /// variable inSwapAndLiquify controls it /// 3. Avoid swap & liquify if sender is uniswap pair with from != pancakePair. /// 4. swapAndLiquifyEnable, must be enabled :) if ( overMinTokenBalance && !inSwapAndLiquify && from != pancakePair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; //add liquidity swapAndLiquify(contractTokenBalance); } // Transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount); } /// This function adds fee value to the total fee counter /// @param rFee is the value to substract from rTotal /// @param tFee is the value to add to tFeeTotal function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } /// This function sends token from an excluded from reward sender to excluded from reward recipient /// @param sender is the account that sends tokens /// @param recipient is the account that will receive tokens /// @param tAmount is the quantity to send function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tVault) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeVault(tVault); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } /// This function is in charge of dividing the balance sheets in two /// and making repurchases and liquidity additions. /// @param contractTokenBalance only tokenBalance function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // This part of code splits the contract balance into halves uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // Swap tokens of the contract for ETH swapTokensForETH(half); // // The balance of ETH to swap uint256 newBalance = address(this).balance.sub(initialBalance); // Add liquidity to pancake addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } /// This function is in charge of taking a part of the tokens to buy BNB that will later /// be added to the pair together with another amount of tokens. /// @param tokenAmount is the quantity of tokens to change for BNB function swapTokensForETH(uint256 tokenAmount) private { // Generate the Pancake swap pair path of Token -> BNB address[] memory path = new address[](2); path[0] = address(this); path[1] = pancakeRouter.WETH(); /// Gives the approve to router for taking tokens _approve(address(this), address(pancakeRouter), tokenAmount); /// Make the swap to get BNB pancakeRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of BNB path, address(this), block.timestamp ); } /// This functions adds liquidity to pair /// @param tokenAmount quantity of tokens to add /// @param ethAmount quantity of BNB to add function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(pancakeRouter), tokenAmount); // add the liquidity pancakeRouter.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); totalLiquidity = totalLiquidity.add(ethAmount); } /// This method is responsible for taking all fee, if takeFee is true /// @param sender is the address of account which will send the tokens /// @param recipient is the address of the account which will receive the tokens /// @param amount is the quantity to transfer function _tokenTransfer(address sender, address recipient, uint256 amount) private { if (_isExcludedFromReward[sender] && !_isExcludedFromReward[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcludedFromReward[sender] && _isExcludedFromReward[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcludedFromReward[sender] && !_isExcludedFromReward[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcludedFromReward[sender] && _isExcludedFromReward[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } } /// This function sends token from sender to recipient /// @param sender is the account that sends tokens /// @param recipient is the account that will receive tokens /// @param tAmount is the quantity to send function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tVault) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeVault(tVault); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } /// This function sends token from sender to excluded from reward recipient /// @param sender is the account that sends tokens /// @param recipient is the account that will receive tokens /// @param tAmount is the quantity to send function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tVault) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeVault(tVault); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } /// This function sends token from excluded from reward sender to recipient /// @param sender is the account that sends tokens /// @param recipient is the account that will receive tokens /// @param tAmount is the quantity to send function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tVault) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeVault(tVault); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } /// This function add liquidity into the contract for rOwned and tOwned (if account is excluded from reward) /// of the contract account /// @param tLiquidity quantity of liquidity to add function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcludedFromReward[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } /// This function add to vault the fee correspondant for it /// @param tVault quantity of tokens to add in vault function _takeVault(uint256 tVault) private { uint256 currentRate = _getRate(); uint256 rVault = tVault.mul(currentRate); _rOwned[blackHoleVaultAddress] = _rOwned[blackHoleVaultAddress].add(rVault); if(_isExcludedFromReward[address(this)]) _tOwned[blackHoleVaultAddress] = _tOwned[blackHoleVaultAddress].add(tVault); emit Transfer(_msgSender(), blackHoleVaultAddress, tVault); } /// This function calls _getTvalues and _getRValues to obtain all the values /// @return the same values returned in _getTValues and _getRValues function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tVault) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, tVault, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity, tVault); } /// This function is used to calculate different tValues with tAmount /// @param tAmount the value which is used to calculate /// @return tFee Value calculated with tax fee percentaje over tAmount /// @return tLiquidity Value calculated with liquidity fee percentaje over tAmount /// @return tLiquidity Value calculated with vault fee percentaje over tAmount /// @return tTransferAmount value extracted from the subtraction of tFee, tLiquidity and tVault over tAmount function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256) { (uint256 tFee, uint256 tLiquidity, uint256 tVault) = calculateFees(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity).sub(tVault); return (tTransferAmount, tFee, tLiquidity, tVault); } /// This function obtains the rate calculated with the current supply /// @return rate obtained with rSupply / tSupply function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } /// This function calculates rSupply and tSupply considering whether the account /// is excluded from the reward or not /// @return rSupply and tSupply || _rTotal and _tTotal depending on the conditions function _getCurrentSupply() private view returns(uint256, uint256) { uint256 tSupply = _tTotal; // add totalburned to avoid a decrease on reflection uint256 rSupply = _rTotal; for (uint256 i = 0; i < _excludedFromReward.length; i++) { if (_rOwned[_excludedFromReward[i]] > rSupply || _tOwned[_excludedFromReward[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excludedFromReward[i]]); tSupply = tSupply.sub(_tOwned[_excludedFromReward[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } /// This functions calculates fees for an amount /// @param _amount the quantity to calculate its fee /// @return fees for holders, liquidity and vault function calculateFees(uint256 _amount) private view returns (uint256, uint256, uint256){ uint256 tFee = _amount.mul(_holderFee).div(10**2); uint256 tLiquidity = _amount.mul(_liquidityFee).div(10**2); uint256 tVault = _amount.mul(_vaultFee).div(10**2); return (tFee, tLiquidity, tVault); } /// This function is used to calculate different tValues with tValues and the current rate /// @param tAmount the value which is used to calculate /// @param tFee is the tax fee of tAmount /// @param tLiquidity is the liquidity fee of tAmount /// @param currentRate rate obtained with the division rSupply / tSupply /// @return rAmount the result obtained by multiplying tAmount by currentRate /// @return rTransferAmount value extracted from the subtraction of rFee and rLiquidity over rAmount /// @return tTransferAmount value extracted from the subtraction of tFee and tLiquidity over tAmount function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 tVault, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity).sub(tVault.mul(currentRate)); return (rAmount, rTransferAmount, rFee); } }
This function permits change the holder fee percent Only owner can change the fee holderFee is the new fee for holders
function setHoldersFee(uint256 holderFee, uint256 liquidityFee, uint256 vaultFee) external onlyOwner { _holderFee = holderFee; _liquidityFee = liquidityFee; _vaultFee = vaultFee; }
1,063,152
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./BoneToken.sol"; import "./BoneLocker.sol"; interface IMigratorShib { // Perform LP token migration from legacy UniswapV2 to ShibaSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to UniswapV2 LP tokens. // ShibaSwap must mint EXACTLY the same amount of ShibaSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // TopDog is the master of Bone. He can make Bone and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once BONE is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract TopDog is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of BONEs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accBonePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accBonePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. BONEs to distribute per block. uint256 lastRewardBlock; // Last block number that BONEs distribution occurs. uint256 accBonePerShare; // Accumulated BONEs per share, times 1e12. See below. } // The BONE TOKEN! BoneToken public bone; // The Bone Token Locker contract BoneLocker public boneLocker; // Dev address. address public devBoneDistributor; address public tBoneBoneDistributor; address public xShibBoneDistributor; address public xLeashBoneDistributor; uint256 public devPercent; uint256 public tBonePercent; uint256 public xShibPercent; uint256 public xLeashPercent; // Block number when bonus BONE period ends. uint256 public bonusEndBlock; // BONE tokens created per block. uint256 public bonePerBlock; // Bonus muliplier for early bone makers. uint256 public constant BONUS_MULTIPLIER = 10; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorShib public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when BONE mining starts. uint256 public startBlock; // reward percentage to be sent to user directly uint256 public rewardMintPercent; // devReward percentage to be sent to user directly uint256 public devRewardMintPercent; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event RewardPerBlock(address indexed user, uint _newReward); event SetAddress(string indexed which, address indexed user, address newAddr); event SetPercent(string indexed which, address indexed user, uint256 newPercent); constructor( BoneToken _bone, BoneLocker _boneLocker, address _devBoneDistributor, address _tBoneBoneDistributor, address _xShibBoneDistributor, address _xLeashBoneDistributor, uint256 _bonePerBlock, uint256 _startBlock, uint256 _bonusEndBlock, uint256 _rewardMintPercent, uint256 _devRewardMintPercent ) public { require(address(_bone) != address(0), "_bone is a zero address"); require(address(_boneLocker) != address(0), "_boneLocker is a zero address"); bone = _bone; boneLocker = _boneLocker; devBoneDistributor = _devBoneDistributor; bonePerBlock = _bonePerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; tBoneBoneDistributor = _tBoneBoneDistributor; xShibBoneDistributor = _xShibBoneDistributor; xLeashBoneDistributor = _xLeashBoneDistributor; rewardMintPercent = _rewardMintPercent; devRewardMintPercent = _devRewardMintPercent; devPercent = 10; tBonePercent = 1; xShibPercent = 3; xLeashPercent = 1; } function poolLength() external view returns (uint256) { return poolInfo.length; } mapping(IERC20 => bool) public poolExistence; modifier nonDuplicated(IERC20 _lpToken) { require(poolExistence[_lpToken] == false, "nonDuplicated: duplicated lpToken"); _; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner nonDuplicated(_lpToken) { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolExistence[_lpToken] = true; poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accBonePerShare: 0 })); } // update Reward Rate function updateRewardPerBlock(uint256 _perBlock) public onlyOwner { massUpdatePools(); bonePerBlock = _perBlock; emit RewardPerBlock(msg.sender, _perBlock); } // Update the given pool's BONE allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorShib _migrator) public onlyOwner { migrator = _migrator; emit SetAddress("Migrator", msg.sender, address(_migrator)); } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_from < startBlock) { _from = startBlock; } if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending BONEs on frontend. function pendingBone(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accBonePerShare = pool.accBonePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 boneReward = multiplier.mul(bonePerBlock).mul(pool.allocPoint).div(totalAllocPoint); accBonePerShare = accBonePerShare.add(boneReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accBonePerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 boneReward = multiplier.mul(bonePerBlock).mul(pool.allocPoint).div(totalAllocPoint); uint256 devBoneReward = boneReward.mul(devPercent).div(100); // devPercent rewards to dev address bone.mint(devBoneDistributor, devBoneReward.mul(devRewardMintPercent).div(100)); // partial devPercent rewards to dev address if(devRewardMintPercent != 100) { bone.mint(address(boneLocker), devBoneReward.sub(devBoneReward.mul(devRewardMintPercent).div(100))); // rest devPercent rewards locked to bone token contract boneLocker.lock(devBoneDistributor, devBoneReward.sub(devBoneReward.mul(devRewardMintPercent).div(100)), true); } bone.mint(tBoneBoneDistributor, boneReward.mul(tBonePercent).div(100)); // tBonePercent rewards to tBoneBoneDistributor address bone.mint(xShibBoneDistributor, boneReward.mul(xShibPercent).div(100)); // xShibPercent rewards to xShibBoneDistributor address bone.mint(xLeashBoneDistributor, boneReward.mul(xLeashPercent).div(100)); // xLeashPercent rewards to xLeashBoneDistributor address bone.mint(address(this), boneReward); pool.accBonePerShare = pool.accBonePerShare.add(boneReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to TopDog for BONE allocation. function deposit(uint256 _pid, uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accBonePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { // safeBoneTransfer(msg.sender, pending); uint256 sendAmount = pending.mul(rewardMintPercent).div(100); safeBoneTransfer(msg.sender, sendAmount); if(rewardMintPercent != 100) { safeBoneTransfer(address(boneLocker), pending.sub(sendAmount)); // Rest amount sent to Bone token contract boneLocker.lock(msg.sender, pending.sub(sendAmount), false); //function called for token time-lock } } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accBonePerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from TopDog. function withdraw(uint256 _pid, uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accBonePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { uint256 sendAmount = pending.mul(rewardMintPercent).div(100); safeBoneTransfer(msg.sender, sendAmount); if(rewardMintPercent != 100) { safeBoneTransfer(address(boneLocker), pending.sub(sendAmount)); // Rest amount sent to Bone token contract boneLocker.lock(msg.sender, pending.sub(sendAmount), false); //function called for token time-lock } } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accBonePerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Safe bone transfer function, just in case if rounding error causes pool to not have enough BONEs. function safeBoneTransfer(address _to, uint256 _amount) internal { uint256 boneBal = bone.balanceOf(address(this)); if (_amount > boneBal) { bone.transfer(_to, boneBal); } else { bone.transfer(_to, _amount); } } // Update boneLocker address by the owner. function boneLockerUpdate(address _boneLocker) public onlyOwner { boneLocker = BoneLocker(_boneLocker); } // Update dev bone distributor address by the owner. function devBoneDistributorUpdate(address _devBoneDistributor) public onlyOwner { devBoneDistributor = _devBoneDistributor; } // Update rewardMintPercent value, currently set to 33%, called by the owner function setRewardMintPercent(uint256 _newPercent) public onlyOwner{ rewardMintPercent = _newPercent; emit SetPercent("RewardMint", msg.sender, _newPercent); } // Update devRewardMintPercent value, currently set to 50%, called by the owner function setDevRewardMintPercent(uint256 _newPercent) public onlyOwner{ devRewardMintPercent = _newPercent; emit SetPercent("DevRewardMint", msg.sender, _newPercent); } // Update locking period for users and dev function setLockingPeriod(uint256 _newLockingPeriod, uint256 _newDevLockingPeriod) public onlyOwner{ boneLocker.setLockingPeriod(_newLockingPeriod, _newDevLockingPeriod); } // Call emergency withdraw to transfer bone tokens to any other address, onlyOwner function function callEmergencyWithdraw(address _to) public onlyOwner{ boneLocker.emergencyWithdrawOwner(_to); } // Update tBoneBoneDistributor address by the owner. function tBoneBoneDistributorUpdate(address _tBoneBoneDistributor) public onlyOwner { tBoneBoneDistributor = _tBoneBoneDistributor; emit SetAddress("tBone-BoneDistributor", msg.sender, _tBoneBoneDistributor); } // Update xShibBoneDistributor address by the owner. function xShibBoneDistributorUpdate(address _xShibBoneDistributor) public onlyOwner { xShibBoneDistributor = _xShibBoneDistributor; emit SetAddress("xShib-BoneDistributor", msg.sender, _xShibBoneDistributor); } // Update xLeashBoneDistributor address by the owner. function xLeashBoneDistributorUpdate(address _xLeashBoneDistributor) public onlyOwner { xLeashBoneDistributor = _xLeashBoneDistributor; emit SetAddress("xLeash-BoneDistributor", msg.sender, _xLeashBoneDistributor); } // Update devPercent by the owner. function devPercentUpdate(uint _devPercent) public onlyOwner { require(_devPercent <= 10, "topDog: Percent too high"); devPercent = _devPercent; emit SetPercent("Dev share", msg.sender, _devPercent); } // Update tBonePercent by the owner. function tBonePercentUpdate(uint _tBonePercent) public onlyOwner { tBonePercent = _tBonePercent; emit SetPercent("tBone share", msg.sender, _tBonePercent); } // Update xShibPercent by the owner. function xShibPercentUpdate(uint _xShibPercent) public onlyOwner { xShibPercent = _xShibPercent; emit SetPercent("xShib share", msg.sender, _xShibPercent); } // Update xLeashPercent by the owner. function xLeashPercentUpdate(uint _xLeashPercent) public onlyOwner { xLeashPercent = _xLeashPercent; emit SetPercent("xLeash share", msg.sender, _xLeashPercent); } } // 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 Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; // BoneToken with Governance. contract BoneToken is ERC20("BONE SHIBASWAP", "BONE"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (TopDog). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } function _transfer(address sender, address recipient, uint256 amount) internal override { super._transfer(sender, recipient, amount); _moveDelegates(_delegates[sender], _delegates[recipient], amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @dev A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => 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 Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "BONE::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "BONE::delegateBySig: invalid nonce"); require(now <= expiry, "BONE::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "BONE::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying BONEs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "BONE::_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); require(nCheckpoints + 1 > nCheckpoints, "BONE::_writeCheckpoint: new checkpoint exceeds 32 bits"); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; // BoneToken locker contract. contract BoneLocker is Ownable { using SafeMath for uint256; IERC20 boneToken; address emergencyAddress; bool emergencyFlag = false; struct LockInfo{ uint256 _amount; uint256 _timestamp; bool _isDev; } uint256 public lockingPeriod; uint256 public devLockingPeriod; mapping (address => LockInfo[]) public lockInfoByUser; mapping (address => uint256) public latestCounterByUser; mapping (address => uint256) public unclaimedTokensByUser; event LockingPeriod(address indexed user, uint newLockingPeriod, uint newDevLockingPeriod); constructor(address _boneToken, address _emergencyAddress, uint256 _lockingPeriodInDays, uint256 _devLockingPeriodInDays) public { require(address(_boneToken) != address(0), "_bone token is a zero address"); require(address(_emergencyAddress) != address(0), "_emergencyAddress is a zero address"); boneToken = IERC20(_boneToken); emergencyAddress = _emergencyAddress; lockingPeriod = _lockingPeriodInDays * 1 days; devLockingPeriod = _devLockingPeriodInDays * 1 days; } // function to lock user reward bone tokens in token contract, called by onlyOwner that would be TopDog.sol function lock(address _holder, uint256 _amount, bool _isDev) external onlyOwner { require(_holder != address(0), "Invalid user address"); require(_amount > 0, "Invalid amount entered"); lockInfoByUser[_holder].push(LockInfo(_amount, now, _isDev)); unclaimedTokensByUser[_holder] = unclaimedTokensByUser[_holder].add(_amount); } // function to claim all the tokens locked for a user, after the locking period function claimAllForUser(uint256 r, address user) public { require(!emergencyFlag, "Emergency mode, cannot access this function"); require(r>latestCounterByUser[user], "Increase right header, already claimed till this"); require(r<=lockInfoByUser[user].length, "Decrease right header, it exceeds total length"); LockInfo[] memory lockInfoArrayForUser = lockInfoByUser[user]; uint256 totalTransferableAmount = 0; uint i; for (i=latestCounterByUser[user]; i<r; i++){ uint256 lockingPeriodHere = lockingPeriod; if(lockInfoArrayForUser[i]._isDev){ lockingPeriodHere = devLockingPeriod; } if(now >= (lockInfoArrayForUser[i]._timestamp.add(lockingPeriodHere))){ totalTransferableAmount = totalTransferableAmount.add(lockInfoArrayForUser[i]._amount); unclaimedTokensByUser[user] = unclaimedTokensByUser[user].sub(lockInfoArrayForUser[i]._amount); latestCounterByUser[user] = i.add(1); } else { break; } } boneToken.transfer(user, totalTransferableAmount); } // function to claim all the tokens locked by user, after the locking period function claimAll(uint256 r) external { claimAllForUser(r, msg.sender); } // function to get claimable amount for any user function getClaimableAmount(address _user) external view returns(uint256) { LockInfo[] memory lockInfoArrayForUser = lockInfoByUser[_user]; uint256 totalTransferableAmount = 0; uint i; for (i=latestCounterByUser[_user]; i<lockInfoArrayForUser.length; i++){ uint256 lockingPeriodHere = lockingPeriod; if(lockInfoArrayForUser[i]._isDev){ lockingPeriodHere = devLockingPeriod; } if(now >= (lockInfoArrayForUser[i]._timestamp.add(lockingPeriodHere))){ totalTransferableAmount = totalTransferableAmount.add(lockInfoArrayForUser[i]._amount); } else { break; } } return totalTransferableAmount; } // get the left and right headers for a user, left header is the index counter till which we have already iterated, right header is basically the length of user's lockInfo array function getLeftRightCounters(address _user) external view returns(uint256, uint256){ return(latestCounterByUser[_user], lockInfoByUser[_user].length); } // in cases of emergency, emergency address can set this to true, which will enable emergencyWithdraw function function setEmergencyFlag(bool _emergencyFlag) external { require(msg.sender == emergencyAddress, "This function can only be called by emergencyAddress"); emergencyFlag = _emergencyFlag; } // function for owner to transfer all tokens to another address function emergencyWithdrawOwner(address _to) external onlyOwner{ uint256 amount = boneToken.balanceOf(address(this)); require(boneToken.transfer(_to, amount), 'MerkleDistributor: Transfer failed.'); } // emergency address can be updated from here function setEmergencyAddr(address _newAddr) external { require(msg.sender == emergencyAddress, "This function can only be called by emergencyAddress"); require(_newAddr != address(0), "_newAddr is a zero address"); emergencyAddress = _newAddr; } // function to update/change the normal & dev locking period function setLockingPeriod(uint256 _newLockingPeriod, uint256 _newDevLockingPeriod) external onlyOwner { lockingPeriod = _newLockingPeriod; devLockingPeriod = _newDevLockingPeriod; emit LockingPeriod(msg.sender, _newLockingPeriod, _newDevLockingPeriod); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 boneReward = multiplier.mul(bonePerBlock).mul(pool.allocPoint).div(totalAllocPoint); if(devRewardMintPercent != 100) { boneLocker.lock(devBoneDistributor, devBoneReward.sub(devBoneReward.mul(devRewardMintPercent).div(100)), true); } bone.mint(address(this), boneReward); pool.accBonePerShare = pool.accBonePerShare.add(boneReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; }
13,873,747
// SPDX-License-Identifier: No License // File: 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 no longer needed starting with Solidity 0.8. 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. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * 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: 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]; } // 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: utils/structs/EnumerableMap.sol pragma solidity ^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 { using EnumerableSet for EnumerableSet.Bytes32Set; // 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 Map { // Storage of keys EnumerableSet.Bytes32Set _keys; mapping (bytes32 => bytes32) _values; } /** * @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) { map._values[key] = value; return map._keys.add(key); } /** * @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) { delete map._values[key]; return map._keys.remove(key); } /** * @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._keys.contains(key); } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._keys.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) { bytes32 key = map._keys.at(index); return (key, map._values[key]); } /** * @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) { bytes32 value = map._values[key]; if (value == bytes32(0)) { return (_contains(map, key), bytes32(0)); } else { return (true, value); } } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key"); return value; } /** * @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) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), errorMessage); return value; } // 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: utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "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] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: utils/Context.sol pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: 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; // 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: 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: 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: 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: 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: token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: 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: token/ERC20/IERC20.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: token/ERC721/MerkleListNFT.sol pragma solidity ^0.8.0; /** * @dev Once a coby, always a coby */ contract MerkleAllowableRegisterV2 is Context, ERC165, IERC721, IERC721Metadata, Ownable, IERC721Enumerable { using Address for address; using SafeMath for uint256; using Strings for uint256; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; string private _name; string private _desc; bytes public _imageprefix; bytes public _imagemid; bytes public _imagesuffix; string private _symbol; address private _owner; uint256 public price; bool public sale; // 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; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _balances; // Mapping from holder address to their (enumerable) set of owned tokens EnumerableMap.UintToAddressMap private _tokenHolders; // Merkle Token Data mapping (uint256 => address) private contractAddresses; mapping (uint256 => bytes32) private merkleRoots; mapping (uint256 => bytes) private claimedBitMaps; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor () { _name = "Merkle Lists"; _symbol = "MRK"; _owner = _msgSender(); price = 0; sale = false; // Mint Genesis List to Owner _mint(msg.sender, 0); // Set token _imageprefix = ''; _imagemid = ''; _imagesuffix = ''; _desc = ''; } /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) public 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; } function claimBalanceOf(uint256 tokenId_, uint256 index) public view returns (uint256 ) { require(_exists(tokenId_), "ERC721: approved query for nonexistent token"); return uint256(uint8(claimedBitMaps[tokenId_][index])); } function setList(uint256 tokenId_, address contractAddress_, bytes32 merkleRoot_, bytes calldata claimedBitMap_) public returns (address, bytes32, bytes memory) { require(msg.sender == MerkleAllowableRegisterV2.ownerOf(tokenId_), "Not allowed to operate on this token."); require(claimedBitMap_.length <= 8192, "Exceeds max list size."); contractAddresses[tokenId_]=contractAddress_; merkleRoots[tokenId_]=merkleRoot_; claimedBitMaps[tokenId_]=claimedBitMap_; return (contractAddresses[tokenId_], merkleRoots[tokenId_], claimedBitMaps[tokenId_]); } function totalBalances(uint256 tokenId_) public view returns (uint256) { require(_exists(tokenId_), "ERC721: approved query for nonexistent token"); return claimedBitMaps[tokenId_].length; } function _setClaimed(uint256 tokenId_, uint256 index, uint256 amount) internal { uint8 number = uint8(claimBalanceOf(tokenId_,index).sub(amount)); claimedBitMaps[tokenId_][index]=bytes1(number); } function claim(uint256 tokenId_, address claimee_, uint256 index, uint256 amount, bytes32[] calldata merkleProof) external { require(claimBalanceOf(tokenId_, index).sub(amount)>=0, 'MerkleDistributor: Greedy fuck.'); require(contractAddresses[tokenId_] == msg.sender, 'Sender is not the address defined.'); // Verify the merkle proof. bytes32 node = keccak256(abi.encodePacked(index, claimee_)); require(verify(merkleProof, merkleRoots[tokenId_], node), 'MerkleDistributor: Invalid proof.'); // Mark it claimed and send the token. _setClaimed(tokenId_, index, amount); } function withdraw(uint256 amount_) onlyOwner external { payable(_owner).transfer(amount_); } function getEthBalance() public view returns (uint256) { return address(this).balance; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override (ERC165, IERC165) returns (bool) { // ERC165 == 0x01ffc9a7 // ERC721 == 0x80ac58cd // ERC721_METADATA == 0x5b5e139f // ERC721_ENUMERABLE == 0x780e9d63 if( (interfaceId == 0x01ffc9a7 ) || (interfaceId == 0x80ac58cd) || (interfaceId == 0x5b5e139f) || (interfaceId == 0x780e9d63) ) { return true; } else { return false; } } /** * @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].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenHolders.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } function totalSupply() external view override returns (uint256) { return _tokenHolders.length(); } function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < MerkleAllowableRegisterV2.balanceOf(owner), "Owner index out of bounds"); return _balances[owner].at(index); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < _tokenHolders.length(), "Global index out of bounds"); (uint256 tokenId, ) = _tokenHolders.at(index); return tokenId; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } function mint() payable public { require(sale == true, "Sale has not begun"); require(price == msg.value, "Ether value sent is not correct"); uint256 tokenId_ = _tokenHolders.length(); _safeMint(msg.sender, tokenId_); } function getContractAddress(uint256 tokenId_) public view returns (address) { require(_exists(tokenId_), "ERC721: approved query for nonexistent token"); return contractAddresses[tokenId_]; } function getMerkleRoot(uint256 tokenId_) public view returns (bytes32) { require(_exists(tokenId_), "ERC721: approved query for nonexistent token"); return merkleRoots[tokenId_]; } function getClaimedBitMap(uint256 tokenId_) public view returns (bytes memory) { require(_exists(tokenId_), "ERC721: approved query for nonexistent token"); return claimedBitMaps[tokenId_]; } function tokenURI(uint256 tokenId_) override public view returns (string memory) { require(_exists(tokenId_), "ERC721: approved query for nonexistent token"); string[3] memory parts; parts[0] = toString(getContractAddress(tokenId_)); parts[1] = toString(getMerkleRoot(tokenId_)); parts[2] = toString(getClaimedBitMap(tokenId_)); string memory output = string(abi.encodePacked(_imageprefix, parts[0], _imagemid, parts[1], _imagesuffix)); string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name":"', _name, ' #', toString(tokenId_), '", "description":"', _desc, '" , "attributes": [{"trait_type": "Contract Address", "value":"', parts[0], '"}, {"trait_type":"Merkle Root", "value":"', parts[1], '"}, {"display_type": "number", "trait_type":"Balances", "value":"', parts[2], '"}], "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}')))); output = string(abi.encodePacked('data:application/json;base64,', json)); return output; } function toString(bytes32 value) public pure returns(string memory) { return toString(abi.encodePacked(value)); } function toString(address account) public pure returns(string memory) { return toString(abi.encodePacked(account)); } function toString(bytes memory data) public pure returns(string memory) { bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(2 + data.length * 2); str[0] = "0"; str[1] = "x"; for (uint i = 0; i < data.length; i++) { str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))]; str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))]; } return string(str); } 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); } function setTokenMetadata(string memory desc_, bytes calldata imageprefix_, bytes calldata imagemid_, bytes calldata imagesuffix_) public onlyOwner returns (string memory, bytes memory, bytes memory, bytes memory) { _desc = desc_; _imageprefix = imageprefix_; _imagemid = imagemid_; _imagesuffix = imagesuffix_; return (_desc, imageprefix_, imagemid_, imagesuffix_); } function setSale(bool toggle_) public onlyOwner returns (bool) { sale = toggle_; return sale; } function setPrice(uint256 price_) public onlyOwner returns (uint256) { price = price_; return price; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = MerkleAllowableRegisterV2.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 _tokenHolders.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 = MerkleAllowableRegisterV2.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } 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].add(tokenId); _tokenHolders.set(tokenId, to); emit Transfer(address(0), to, 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(MerkleAllowableRegisterV2.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].remove(tokenId); _balances[to].add(tokenId); _tokenHolders.set(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(MerkleAllowableRegisterV2.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(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly 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 { } } /// [MIT License] /// @title Base64 /// @notice Provides a function for encoding some bytes in base64 /// @author Brecht Devos <[email protected]> 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); } }
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].add(tokenId); _tokenHolders.set(tokenId, to); emit Transfer(address(0), to, tokenId); }
5,944,009
// SPDX-License-Identifier: Apache-2.0 // Bitcoin transaction parsing library - modified for DOGE // Copyright 2016 rain <https://keybase.io/rain> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // https://en.bitcoin.it/wiki/Protocol_documentation#tx // // Raw Bitcoin transaction structure: // // field | size | type | description // version | 4 | int32 | transaction version number // n_tx_in | 1-9 | var_int | number of transaction inputs // tx_in | 41+ | tx_in[] | list of transaction inputs // n_tx_out | 1-9 | var_int | number of transaction outputs // tx_out | 9+ | tx_out[] | list of transaction outputs // lock_time | 4 | uint32 | block number / timestamp at which tx locked // // Transaction input (tx_in) structure: // // field | size | type | description // previous | 36 | outpoint | Previous output transaction reference // script_len | 1-9 | var_int | Length of the signature script // sig_script | ? | uchar[] | Script for confirming transaction authorization // sequence | 4 | uint32 | Sender transaction version // // OutPoint structure: // // field | size | type | description // hash | 32 | char[32] | The hash of the referenced transaction // index | 4 | uint32 | The index of this output in the referenced transaction // // Transaction output (tx_out) structure: // // field | size | type | description // value | 8 | int64 | Transaction value (Satoshis) // pk_script_len | 1-9 | var_int | Length of the public key script // pk_script | ? | uchar[] | Public key as a Bitcoin script. // // Variable integers (var_int) can be encoded differently depending // on the represented value, to save space. Variable integers always // precede an array of a variable length data type (e.g. tx_in). // // Variable integer encodings as a function of represented value: // // value | bytes | format // <0xFD (253) | 1 | uint8 // <=0xFFFF (65535)| 3 | 0xFD followed by length as uint16 // <=0xFFFF FFFF | 5 | 0xFE followed by length as uint32 // - | 9 | 0xFF followed by length as uint64 // // Public key scripts `pk_script` are set on the output and can // take a number of forms. The regular transaction script is // called 'pay-to-pubkey-hash' (P2PKH): // // OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG // // OP_x are Bitcoin script opcodes. The bytes representation (including // the 0x14 20-byte stack push) is: // // 0x76 0xA9 0x14 <pubKeyHash> 0x88 0xAC // // The <pubKeyHash> is the ripemd160 hash of the sha256 hash of // the public key, preceded by a network version byte. (21 bytes total) // // Network version bytes: 0x00 (mainnet); 0x6f (testnet); 0x34 (namecoin) // // The Bitcoin address is derived from the pubKeyHash. The binary form is the // pubKeyHash, plus a checksum at the end. The checksum is the first 4 bytes // of the (32 byte) double sha256 of the pubKeyHash. (25 bytes total) // This is converted to base58 to form the publicly used Bitcoin address. // Mainnet P2PKH transaction scripts are to addresses beginning with '1'. // // P2SH ('pay to script hash') scripts only supply a script hash. The spender // must then provide the script that would allow them to redeem this output. // This allows for arbitrarily complex scripts to be funded using only a // hash of the script, and moves the onus on providing the script from // the spender to the redeemer. // // The P2SH script format is simple: // // OP_HASH160 <scriptHash> OP_EQUAL // // 0xA9 0x14 <scriptHash> 0x87 // // The <scriptHash> is the ripemd160 hash of the sha256 hash of the // redeem script. The P2SH address is derived from the scriptHash. // Addresses are the scriptHash with a version prefix of 5, encoded as // Base58check. These addresses begin with a '3'. pragma solidity ^0.7.6; // parse a raw Dogecoin transaction byte array library DogeMessageLibrary { uint constant p = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f; // secp256k1 uint constant q = (p + 1) / 4; // Error codes uint constant ERR_INVALID_HEADER = 10050; uint constant ERR_COINBASE_INDEX = 10060; // coinbase tx index within Litecoin merkle isn't 0 uint constant ERR_NOT_MERGE_MINED = 10070; // trying to check AuxPoW on a block that wasn't merge mined uint constant ERR_FOUND_TWICE = 10080; // 0xfabe6d6d found twice uint constant ERR_NO_MERGE_HEADER = 10090; // 0xfabe6d6d not found uint constant ERR_NOT_IN_FIRST_20 = 10100; // chain Merkle root isn't in the first 20 bytes of coinbase tx uint constant ERR_CHAIN_MERKLE = 10110; uint constant ERR_PARENT_MERKLE = 10120; uint constant ERR_PROOF_OF_WORK = 10130; enum Network { MAINNET, TESTNET, REGTEST } // AuxPoW block fields struct AuxPoW { uint scryptHash; uint txHash; uint coinbaseMerkleRoot; // Merkle root of auxiliary block hash tree; stored in coinbase tx field uint[] chainMerkleProof; // proves that a given Dogecoin block hash belongs to a tree with the above root uint dogeHashIndex; // index of Doge block hash within block hash tree uint coinbaseMerkleRootCode; // encodes whether or not the root was found properly uint parentMerkleRoot; // Merkle root of transaction tree from parent Litecoin block header uint[] parentMerkleProof; // proves that coinbase tx belongs to a tree with the above root uint coinbaseTxIndex; // index of coinbase tx within Litecoin tx tree uint parentNonce; } // Dogecoin block header stored as a struct, mostly for readability purposes. // BlockHeader structs can be obtained by parsing a block header's first 80 bytes // with parseHeaderBytes. struct BlockHeader { uint32 version; uint32 time; uint32 bits; uint32 nonce; uint blockHash; uint prevBlock; uint merkleRoot; } struct InputDescriptor { // Byte offset where the input is located in the tx uint offset; // Byte offset where the signature script is located in the tx uint sigScriptOffset; // Length of the signature script uint sigScriptLength; } /** * Convert a variable integer into a Solidity numeric type. * * @return the integer as a uint256 * @return the byte index after the var integer */ function parseVarInt(bytes memory txBytes, uint pos) private pure returns (uint, uint) { // the first byte tells us how big the integer is uint8 ibit = uint8(txBytes[pos]); pos += 1; // skip ibit if (ibit < 0xfd) { return (ibit, pos); } else if (ibit == 0xfd) { return (getBytesLE(txBytes, pos, 16), pos + 2); } else if (ibit == 0xfe) { return (getBytesLE(txBytes, pos, 32), pos + 4); } else /*if (ibit == 0xff)*/ { return (getBytesLE(txBytes, pos, 64), pos + 8); } } // Convert little endian bytes to uint function getBytesLE(bytes memory data, uint pos, uint bits) internal pure returns (uint) { if (bits == 8) { return uint8(data[pos]); } else if (bits == 16) { return uint16(uint8(data[pos])) + uint16(uint8(data[pos + 1])) * 2 ** 8; } else if (bits == 32) { return uint32(uint8(data[pos])) + uint32(uint8(data[pos + 1])) * 2 ** 8 + uint32(uint8(data[pos + 2])) * 2 ** 16 + uint32(uint8(data[pos + 3])) * 2 ** 24; } else if (bits == 64) { return uint64(uint8(data[pos])) + uint64(uint8(data[pos + 1])) * 2 ** 8 + uint64(uint8(data[pos + 2])) * 2 ** 16 + uint64(uint8(data[pos + 3])) * 2 ** 24 + uint64(uint8(data[pos + 4])) * 2 ** 32 + uint64(uint8(data[pos + 5])) * 2 ** 40 + uint64(uint8(data[pos + 6])) * 2 ** 48 + uint64(uint8(data[pos + 7])) * 2 ** 56; } else { revert("Invalid bits parameter in getBytesLE"); } } // @dev - Parses a doge tx // // @param txBytes - tx byte array // @param expectedOperatorPKH - public key hash that is expected to be used as output or input // Outputs // @return userOutputValue - amount sent to the unlock address in satoshis // @return operatorChangePresent - if true, indicates that the operator sent some change to his address. // @return operatorOutputValue - amount of the operator change output // @return operatorOutputIndex - number of the operator change output in the tx function parseUnlockTransaction( bytes memory txBytes, bytes20 expectedOperatorPKH ) internal pure returns (uint, uint, uint16) { uint pos; // skip version pos = 4; /* Inputs One or more inputs signed by the operator. Ouputs 0. Output for the user. This is ignored. 1. Optional. Operator change. */ pos = checkUnlockInputs(txBytes, pos, expectedOperatorPKH); return parseUnlockTxOutputs(expectedOperatorPKH, txBytes, pos); } function checkUnlockInputs( bytes memory txBytes, uint pos, bytes20 expectedOperatorPKH ) private pure returns (uint) { InputDescriptor[] memory inputScripts; (inputScripts, pos) = scanInputs(txBytes, pos, 0); for (uint i = 0; i < inputScripts.length; i++) { (bytes32 inputPubKey, bool inputPubKeyOdd) = getInputPubKey(txBytes, inputScripts[i]); require( expectedOperatorPKH == pub2PubKeyHash(inputPubKey, inputPubKeyOdd), "Invalid unlock tx. One of the inputs is not signed by the operator." ); } return pos; } // Determine the operator output, if any, and the value of the user output // // @param expectedOperatorPKH - operator public key hash // @param txBytes - tx byte array // @param pos - position to start parsing txBytes // Outputs // @return output value of operator output // @return output index of operator output // @return lockDestinationEthAddress - Lock destination address if operator output and OP_RETURN output found, 0 otherwise // // Returns output amount, index and ethereum address function parseUnlockTxOutputs( bytes20 expectedOperatorPKH, bytes memory txBytes, uint pos ) private pure returns (uint, uint, uint16) { /* Ouputs 0. Output for the user. This output is ignored. 1. Optional. Operator change. */ (uint userOutputValue, uint operatorChangeScriptStart, uint operatorChangeScriptLength, uint operatorChangeValue) = scanUnlockOutputs(txBytes, pos); // TODO: abstract this check into a function? // Check if the change output exists if (operatorChangeScriptStart < txBytes.length) { // Check tx is sending funds to an operator. bytes20 outputPublicKeyHash = parseP2PKHOutputScript(txBytes, operatorChangeScriptStart, operatorChangeScriptLength); require( outputPublicKeyHash == expectedOperatorPKH, "Invalid unlock tx. The second tx output does not have a P2PKH output script for an operator." ); return (userOutputValue, operatorChangeValue, 1); } return (userOutputValue, 0, 0); } // Scan the outputs of an unlock transaction. // The first output in an unlock transaction transfers value to a user. // The second output in an unlock transaction may be change for the operator. // Returns the value unlocked for the user output and the value, offset and length of scripts // for the operator change output, if any. function scanUnlockOutputs( bytes memory txBytes, uint pos ) private pure returns (uint, uint, uint, uint) { uint nOutputs; (nOutputs, pos) = parseVarInt(txBytes, pos); require(nOutputs == 1 || nOutputs == 2, "Unlock transactions only have one or two outputs."); // Tx output 0 is for the user // read value of the output for the user uint firstOutputValue = getBytesLE(txBytes, pos, 64); pos += 8; // read the script length uint firstOutputScriptLength; (firstOutputScriptLength, pos) = parseVarInt(txBytes, pos); // uint firstOutputScriptStart = pos; pos += firstOutputScriptLength; uint secondOutputScriptLength; uint secondOutputScriptStart = txBytes.length; uint secondOutputValue; if (nOutputs == 2) { // Tx output 1 is the change for the operator // read value of operator change secondOutputValue = getBytesLE(txBytes, pos, 64); pos += 8; (secondOutputScriptLength, secondOutputScriptStart) = parseVarInt(txBytes, pos); } return (firstOutputValue, secondOutputScriptStart, secondOutputScriptLength, secondOutputValue); } // @dev - Parses a doge tx assuming it is a lock operation // // @param txBytes - tx byte array // @param expectedOperatorPKH - public key hash that is expected to be used as output or input // Outputs // @return outputValue - amount sent to the lock address in satoshis // @return lockDestinationEthAddress - address where tokens should be minted to // @return outputIndex - number of output where expectedOperatorPKH was found function parseLockTransaction( bytes memory txBytes, bytes20 expectedOperatorPKH ) internal pure returns (uint, address, uint16) { uint pos; // skip version pos = 4; // Ignore inputs pos = skipInputs(txBytes, pos); address lockDestinationEthAddress; uint operatorTxOutputValue; (operatorTxOutputValue, lockDestinationEthAddress) = parseLockTxOutputs(expectedOperatorPKH, txBytes, pos); require(lockDestinationEthAddress != address(0x0)); return (operatorTxOutputValue, lockDestinationEthAddress, 0); } // Parse operator output and embedded ethereum address in transaction outputs in tx // // @param expectedOperatorPKH - operator public key hash to look for // @param txBytes - tx byte array // @param pos - position to start parsing txBytes // Outputs // @return output value of operator output // @return output index of operator output // @return lockDestinationEthAddress - Lock destination address if operator output and OP_RETURN output found, 0 otherwise // // Returns output amount, index and ethereum address function parseLockTxOutputs( bytes20 expectedOperatorPKH, bytes memory txBytes, uint pos ) private pure returns (uint, address) { /* Outputs 0. Operator 1. OP_RETURN with the ethereum address of the user 2. Optional. Change output for the user. This output is ignored. */ uint operatorOutputValue; uint operatorScriptStart; uint operatorScriptLength; uint ethAddressScriptStart; uint ethAddressScriptLength; (operatorOutputValue, operatorScriptStart, operatorScriptLength, ethAddressScriptStart, ethAddressScriptLength) = scanLockOutputs(txBytes, pos); // Check tx is sending funds to an operator. bytes20 outputPublicKeyHash = parseP2PKHOutputScript(txBytes, operatorScriptStart, operatorScriptLength); require(outputPublicKeyHash == expectedOperatorPKH, "The first tx output does not have a P2PKH output script for an operator."); // Read the destination Ethereum address require(isEthereumAddress(txBytes, ethAddressScriptStart, ethAddressScriptLength), "The second tx output does not describe an ethereum address."); address lockDestinationEthAddress = readEthereumAddress(txBytes, ethAddressScriptStart, ethAddressScriptLength); return (operatorOutputValue, lockDestinationEthAddress); } // Scan the outputs of a lock transaction. // The first output in a lock transaction transfers value to an operator. // The second output in a lock transaction is an unspendable output with an ethereum address. // Returns the offsets and lengths of scripts for the first and second outputs and // the value of the first output. function scanLockOutputs(bytes memory txBytes, uint pos) private pure returns (uint, uint, uint, uint, uint) { uint nOutputs; (nOutputs, pos) = parseVarInt(txBytes, pos); require(nOutputs == 2 || nOutputs == 3, "Lock transactions only have two or three outputs."); // Tx output 0 is for the operator // read value of the output for the operator uint operatorOutputValue = getBytesLE(txBytes, pos, 64); pos += 8; // read the script length uint operatorScriptLength; (operatorScriptLength, pos) = parseVarInt(txBytes, pos); uint operatorScriptStart = pos; pos += operatorScriptLength; // Tx output 1 describes the ethereum address that should receive the dogecoin tokens // skip value pos += 8; uint ethAddressScriptLength; uint ethAddressScriptStart; (ethAddressScriptLength, ethAddressScriptStart) = parseVarInt(txBytes, pos); return (operatorOutputValue, operatorScriptStart, operatorScriptLength, ethAddressScriptStart, ethAddressScriptLength); } function getInputPubKey(bytes memory txBytes, InputDescriptor memory input) private pure returns (bytes32, bool) { bytes32 pubKey; bool odd; (, pubKey, odd,) = parseScriptSig(txBytes, input.sigScriptOffset); return (pubKey, odd); } // Scan the inputs and find the script lengths. // @return an array of script descriptors. Each one describes the length and the start position // of the script. // takes a 'stop' argument which sets the maximum number of // outputs to scan through. stop=0 => scan all. function scanInputs(bytes memory txBytes, uint pos, uint stop) private pure returns (InputDescriptor[] memory, uint) { uint nInputs; uint halt; (nInputs, pos) = parseVarInt(txBytes, pos); if (stop == 0 || stop > nInputs) { halt = nInputs; } else { halt = stop; } InputDescriptor[] memory inputs = new InputDescriptor[](halt); for (uint256 i = 0; i < halt; i++) { inputs[i].offset = pos; // skip outpoint pos += 36; uint scriptLength; (scriptLength, pos) = parseVarInt(txBytes, pos); inputs[i].sigScriptOffset = pos; inputs[i].sigScriptLength = scriptLength; // skip sig_script, seq pos += scriptLength + 4; } return (inputs, pos); } /** * Consumes all inputs in a transaction without storing anything in memory * @return index to tx output quantity var integer */ function skipInputs(bytes memory txBytes, uint pos) private pure returns (uint) { uint n_inputs; (n_inputs, pos) = parseVarInt(txBytes, pos); for (uint256 i = 0; i < n_inputs; i++) { // skip outpoint pos += 36; uint script_len; (script_len, pos) = parseVarInt(txBytes, pos); // skip sig_script and seq pos += script_len + 4; } return pos; } // similar to scanInputs, but consumes less gas since it doesn't store the inputs // also returns position of coinbase tx for later use function skipInputsAndGetScriptPos(bytes memory txBytes, uint pos, uint stop) private pure returns (uint, uint) { uint script_pos; uint n_inputs; uint halt; uint script_len; (n_inputs, pos) = parseVarInt(txBytes, pos); if (stop == 0 || stop > n_inputs) { halt = n_inputs; } else { halt = stop; } for (uint256 i = 0; i < halt; i++) { pos += 36; // skip outpoint (script_len, pos) = parseVarInt(txBytes, pos); if (i == 0) script_pos = pos; // first input script begins where first script length ends // (script_len, pos) = (1, 0); pos += script_len + 4; // skip sig_script, seq } return (pos, script_pos); } // scan the outputs and find the values and script lengths. // return array of values, array of script lengths and the // end position of the outputs. // takes a 'stop' argument which sets the maximum number of // outputs to scan through. stop=0 => scan all. function scanOutputs(bytes memory txBytes, uint pos, uint stop) private pure returns (uint[] memory, uint[] memory, uint[] memory, uint) { uint n_outputs; uint halt; uint script_len; (n_outputs, pos) = parseVarInt(txBytes, pos); if (stop == 0 || stop > n_outputs) { halt = n_outputs; } else { halt = stop; } uint[] memory script_starts = new uint[](halt); uint[] memory script_lens = new uint[](halt); uint[] memory output_values = new uint[](halt); for (uint256 i = 0; i < halt; i++) { output_values[i] = getBytesLE(txBytes, pos, 64); pos += 8; (script_len, pos) = parseVarInt(txBytes, pos); script_starts[i] = pos; script_lens[i] = script_len; pos += script_len; } return (output_values, script_starts, script_lens, pos); } // similar to scanOutputs, but consumes less gas since it doesn't store the outputs function skipOutputs(bytes memory txBytes, uint pos, uint stop) private pure returns (uint) { uint n_outputs; uint halt; uint script_len; (n_outputs, pos) = parseVarInt(txBytes, pos); if (stop == 0 || stop > n_outputs) { halt = n_outputs; } else { halt = stop; } for (uint256 i = 0; i < halt; i++) { pos += 8; (script_len, pos) = parseVarInt(txBytes, pos); pos += script_len; } return pos; } // get final position of inputs, outputs and lock time // this is a helper function to slice a byte array and hash the inputs, outputs and lock time function getSlicePosAndScriptPos(bytes memory txBytes, uint pos) private pure returns (uint slicePos, uint scriptPos) { (slicePos, scriptPos) = skipInputsAndGetScriptPos(txBytes, pos + 4, 0); slicePos = skipOutputs(txBytes, slicePos, 0); slicePos += 4; // skip lock time } // scan a Merkle branch. // return array of values and the end position of the sibling hashes. // takes a 'stop' argument which sets the maximum number of // siblings to scan through. stop=0 => scan all. function scanMerkleBranch(bytes memory txBytes, uint pos, uint stop) private pure returns (uint[] memory, uint) { uint n_siblings; uint halt; (n_siblings, pos) = parseVarInt(txBytes, pos); if (stop == 0 || stop > n_siblings) { halt = n_siblings; } else { halt = stop; } uint[] memory sibling_values = new uint[](halt); for (uint256 i = 0; i < halt; i++) { sibling_values[i] = flip32Bytes(sliceBytes32Int(txBytes, pos)); pos += 32; } return (sibling_values, pos); } // Slice 20 contiguous bytes from bytes `data`, starting at `start` function sliceBytes20(bytes memory data, uint start) private pure returns (bytes20) { uint160 slice = 0; // FIXME: With solc v0.4.24 and optimizations enabled // using uint160 for index i will generate an error // "Error: VM Exception while processing transaction: Error: redPow(normalNum)" for (uint256 i = 0; i < 20; i++) { slice += uint160(uint8(data[i + start])) << uint160(8 * (19 - i)); } return bytes20(slice); } // Slice 32 contiguous bytes from bytes `data`, starting at `start` function sliceBytes32Int(bytes memory data, uint start) private pure returns (uint slice) { for (uint i = 0; i < 32; i++) { if (i + start < data.length) { slice += uint(uint8(data[i + start])) << (8 * (31 - i)); } } } // @dev returns a portion of a given byte array specified by its starting and ending points // Should be private, made internal for testing // Breaks underscore naming convention for parameters because it raises a compiler error // if `offset` is changed to `_offset`. // // @param _rawBytes - array to be sliced // @param offset - first byte of sliced array // @param _endIndex - last byte of sliced array function sliceArray(bytes memory _rawBytes, uint offset, uint _endIndex) internal view returns (bytes memory) { uint len = _endIndex - offset; bytes memory result = new bytes(len); assembly { // Call precompiled contract to copy data if iszero(staticcall(gas(), 0x04, add(add(_rawBytes, 0x20), offset), len, add(result, 0x20), len)) { revert(0, 0) } } return result; } // returns true if the bytes located in txBytes by pos and // script_len represent a P2PKH script function isP2PKH(bytes memory txBytes, uint pos, uint script_len) private pure returns (bool) { return (script_len == 25) // 20 byte pubkeyhash + 5 bytes of script && (txBytes[pos] == 0x76) // OP_DUP && (txBytes[pos + 1] == 0xa9) // OP_HASH160 && (txBytes[pos + 2] == 0x14) // bytes to push && (txBytes[pos + 23] == 0x88) // OP_EQUALVERIFY && (txBytes[pos + 24] == 0xac); // OP_CHECKSIG } // Get the pubkeyhash from an output script. Assumes // pay-to-pubkey-hash (P2PKH) outputs. // Returns the pubkeyhash, or zero if unknown output. function parseP2PKHOutputScript(bytes memory txBytes, uint pos, uint script_len) private pure returns (bytes20) { if (isP2PKH(txBytes, pos, script_len)) { return sliceBytes20(txBytes, pos + 3); } else { return bytes20(0); } } // Parse a P2PKH scriptSig // TODO: add script length as a parameter? function parseScriptSig(bytes memory txBytes, uint pos) private pure returns (bytes memory, bytes32, bool, uint) { bytes memory sig; bytes32 pubKey; bool odd; // TODO: do we want the signature? (sig, pos) = parseSignature(txBytes, pos); (pubKey, odd, pos) = parsePubKey(txBytes, pos); return (sig, pubKey, odd, pos); } // Extract a signature function parseSignature(bytes memory txBytes, uint pos) private pure returns (bytes memory, uint) { uint8 op; bytes memory sig; (op, pos) = getOpcode(txBytes, pos); require(op >= 9 && op <= 73); require(uint8(txBytes[pos]) == 0x30); //FIXME: Copy signature pos += op; return (sig, pos); } // Extract public key function parsePubKey(bytes memory txBytes, uint pos) private pure returns (bytes32, bool, uint) { uint8 op; (op, pos) = getOpcode(txBytes, pos); //FIXME: Add support for uncompressed public keys require(op == 33, "Expected a compressed public key"); bytes32 pubKey; bool odd = txBytes[pos] == 0x03; pos += 1; assembly { pubKey := mload(add(add(txBytes, 0x20), pos)) } pos += 32; return (pubKey, odd, pos); } /** * Returns true if the tx output is an embedded ethereum address * @param txBytes Buffer where the entire transaction is stored. * @param pos Index into the tx buffer where the script is stored. * @param len Size of the script in terms of bytes. */ function isEthereumAddress(bytes memory txBytes, uint pos, uint len) private pure returns (bool) { // scriptPub format for the ethereum address is // 0x6a OP_RETURN // 0x14 PUSH20 // [] 20 bytes of the ethereum address return len == 20+2 && txBytes[pos] == bytes1(0x6a) && txBytes[pos+1] == bytes1(0x14); } // Read the ethereum address embedded in the tx output function readEthereumAddress(bytes memory txBytes, uint pos, uint) private pure returns (address) { uint256 data; assembly { data := mload(add(add(txBytes, 22), pos)) } return address(uint160(data)); } // Read next opcode from script function getOpcode(bytes memory txBytes, uint pos) private pure returns (uint8, uint) { return (uint8(txBytes[pos]), pos + 1); } function expmod(uint256 base, uint256 e, uint256 m) internal view returns (uint256 o) { assembly { // pointer to free memory let pos := mload(0x40) mstore(pos, 0x20) // Length of Base mstore(add(pos, 0x20), 0x20) // Length of Exponent mstore(add(pos, 0x40), 0x20) // Length of Modulus mstore(add(pos, 0x60), base) // Base mstore(add(pos, 0x80), e) // Exponent mstore(add(pos, 0xa0), m) // Modulus // call modexp precompile! if iszero(staticcall(gas(), 0x05, pos, 0xc0, pos, 0x20)) { revert(0, 0) } // data o := mload(pos) } } function pub2address(uint x, bool odd) internal view returns (address) { // First, uncompress pub key uint yy = mulmod(x, x, p); yy = mulmod(yy, x, p); yy = addmod(yy, 7, p); uint y = expmod(yy, q, p); if (((y & 1) == 1) != odd) { y = p - y; } require(yy == mulmod(y, y, p)); // Now, with uncompressed x and y, create the address return address(uint160(uint256(keccak256(abi.encodePacked(x, y))))); } // Gets the public key hash given a public key function pub2PubKeyHash(bytes32 pub, bool odd) internal pure returns (bytes20) { bytes1 firstByte = odd ? bytes1(0x03) : bytes1(0x02); return ripemd160(abi.encodePacked(sha256(abi.encodePacked(firstByte, pub)))); } // @dev - convert an unsigned integer from little-endian to big-endian representation // // @param _input - little-endian value // @return - input value in big-endian format function flip32Bytes(uint _input) internal pure returns (uint result) { assembly { let pos := mload(0x40) for { let i := 0 } lt(i, 32) { i := add(i, 1) } { mstore8(add(pos, i), byte(sub(31, i), _input)) } result := mload(pos) } } // helpers for flip32Bytes struct UintWrapper { uint value; } // @dev - Parses AuxPow part of block header // @param rawBytes - array of bytes with the block header // @param pos - starting position of the block header // @param uint - length of the block header // @return auxpow - AuxPoW struct with parsed data function parseAuxPoW(bytes memory rawBytes, uint pos, uint) internal view returns (AuxPoW memory auxpow) { // we need to traverse the bytes with a pointer because some fields are of variable length pos += 80; // skip non-AuxPoW header // auxpow.firstBytes = sliceBytes32Int(rawBytes, pos); uint slicePos; uint inputScriptPos; (slicePos, inputScriptPos) = getSlicePosAndScriptPos(rawBytes, pos); auxpow.txHash = dblShaFlipMem(rawBytes, pos, slicePos - pos); pos = slicePos; auxpow.scryptHash = sliceBytes32Int(rawBytes, pos); pos += 32; (auxpow.parentMerkleProof, pos) = scanMerkleBranch(rawBytes, pos, 0); auxpow.coinbaseTxIndex = getBytesLE(rawBytes, pos, 32); pos += 4; (auxpow.chainMerkleProof, pos) = scanMerkleBranch(rawBytes, pos, 0); auxpow.dogeHashIndex = getBytesLE(rawBytes, pos, 32); pos += 40; // skip hash that was just read, parent version and prev block auxpow.parentMerkleRoot = sliceBytes32Int(rawBytes, pos); pos += 40; // skip root that was just read, parent block timestamp and bits auxpow.parentNonce = getBytesLE(rawBytes, pos, 32); uint coinbaseMerkleRootPosition; (auxpow.coinbaseMerkleRoot, coinbaseMerkleRootPosition, auxpow.coinbaseMerkleRootCode) = findCoinbaseMerkleRoot(rawBytes); if (coinbaseMerkleRootPosition - inputScriptPos > 20 && auxpow.coinbaseMerkleRootCode == 1) { // if it was found once and only once but not in the first 20 bytes, return this error code auxpow.coinbaseMerkleRootCode = ERR_NOT_IN_FIRST_20; } } // @dev - looks for {0xfa, 0xbe, 'm', 'm'} byte sequence // returns the following 32 bytes if it appears once and only once, // 0 otherwise // also returns the position where the bytes first appear function findCoinbaseMerkleRoot(bytes memory rawBytes) private pure returns (uint, uint, uint) { uint position; bool found = false; for (uint i = 0; i < rawBytes.length; ++i) { if (rawBytes[i] == 0xfa && rawBytes[i+1] == 0xbe && rawBytes[i+2] == 0x6d && rawBytes[i+3] == 0x6d) { if (found) { // found twice return (0, position - 4, ERR_FOUND_TWICE); } else { found = true; position = i + 4; } } } if (!found) { // no merge mining header return (0, position - 4, ERR_NO_MERGE_HEADER); } else { return (sliceBytes32Int(rawBytes, position), position - 4, 1); } } // @dev - Evaluate the merkle root // // Given an array of hashes it calculates the // root of the merkle tree. // // @return root of merkle tree function makeMerkle(bytes32[] calldata hashes2) external pure returns (bytes32) { bytes32[] memory hashes = hashes2; uint length = hashes.length; if (length == 1) return hashes[0]; require(length > 0); uint i; uint j; uint k; k = 0; while (length > 1) { k = 0; for (i = 0; i < length; i += 2) { j = i+1<length ? i+1 : length-1; hashes[k] = bytes32(concatHash(uint(hashes[i]), uint(hashes[j]))); k += 1; } length = k; } return hashes[0]; } // @dev - For a valid proof, returns the root of the Merkle tree. // // @param _txHash - transaction hash // @param _txIndex - transaction's index within the block it's assumed to be in // @param _siblings - transaction's Merkle siblings // @return - Merkle tree root of the block the transaction belongs to if the proof is valid, // garbage if it's invalid function computeMerkle(uint _txHash, uint _txIndex, uint[] memory _siblings) internal pure returns (uint) { uint resultHash = _txHash; for (uint i = 0; i < _siblings.length; i++) { uint proofStep = _siblings[i]; uint left; uint right; // 0 means _siblings is on the right; 1 means left if (_txIndex % 2 == 1) { left = proofStep; right = resultHash; } else { left = resultHash; right = proofStep; } resultHash = concatHash(left, right); _txIndex /= 2; } return resultHash; } // @dev - calculates the Merkle root of a tree containing Litecoin transactions // in order to prove that `ap`'s coinbase tx is in that Litecoin block. // // @param _ap - AuxPoW information // @return - Merkle root of Litecoin block that the Dogecoin block // with this info was mined in if AuxPoW Merkle proof is correct, // garbage otherwise function computeParentMerkle(AuxPoW memory _ap) internal pure returns (uint) { return flip32Bytes(computeMerkle(_ap.txHash, _ap.coinbaseTxIndex, _ap.parentMerkleProof)); } // @dev - calculates the Merkle root of a tree containing auxiliary block hashes // in order to prove that the Dogecoin block identified by _blockHash // was merge-mined in a Litecoin block. // // @param _blockHash - SHA-256 hash of a certain Dogecoin block // @param _ap - AuxPoW information corresponding to said block // @return - Merkle root of auxiliary chain tree // if AuxPoW Merkle proof is correct, garbage otherwise function computeChainMerkle(uint _blockHash, AuxPoW memory _ap) internal pure returns (uint) { return computeMerkle(_blockHash, _ap.dogeHashIndex, _ap.chainMerkleProof); } // @dev - Helper function for Merkle root calculation. // Given two sibling nodes in a Merkle tree, calculate their parent. // Concatenates hashes `_tx1` and `_tx2`, then hashes the result. // // @param _tx1 - Merkle node (either root or internal node) // @param _tx2 - Merkle node (either root or internal node), has to be `_tx1`'s sibling // @return - `_tx1` and `_tx2`'s parent, i.e. the result of concatenating them, // hashing that twice and flipping the bytes. function concatHash(uint _tx1, uint _tx2) internal pure returns (uint) { return flip32Bytes(uint(sha256(abi.encodePacked(sha256(abi.encodePacked(flip32Bytes(_tx1), flip32Bytes(_tx2))))))); } // @dev - checks if a merge-mined block's Merkle proofs are correct, // i.e. Doge block hash is in coinbase Merkle tree // and coinbase transaction is in parent Merkle tree. // // @param _blockHash - SHA-256 hash of the block whose Merkle proofs are being checked // @param _ap - AuxPoW struct corresponding to the block // @return 1 if block was merge-mined and coinbase index, chain Merkle root and Merkle proofs are correct, // respective error code otherwise function checkAuxPoW(uint _blockHash, AuxPoW memory _ap) internal pure returns (uint) { if (_ap.coinbaseTxIndex != 0) { return ERR_COINBASE_INDEX; } if (_ap.coinbaseMerkleRootCode != 1) { return _ap.coinbaseMerkleRootCode; } if (computeChainMerkle(_blockHash, _ap) != _ap.coinbaseMerkleRoot) { return ERR_CHAIN_MERKLE; } if (computeParentMerkle(_ap) != _ap.parentMerkleRoot) { return ERR_PARENT_MERKLE; } return 1; } function sha256mem(bytes memory _rawBytes, uint offset, uint len) internal view returns (bytes32 result) { assembly { // Call sha256 precompiled contract (located in address 0x02) to copy data. // Assign to pos the next available memory position (stored in memory position 0x40). let pos := mload(0x40) if iszero(staticcall(gas(), 0x02, add(add(_rawBytes, 0x20), offset), len, pos, 0x20)) { revert(0, 0) } result := mload(pos) } } // @dev - Bitcoin-way of hashing // @param _dataBytes - raw data to be hashed // @return - result of applying SHA-256 twice to raw data and then flipping the bytes function dblShaFlip(bytes memory _dataBytes) internal pure returns (uint) { return flip32Bytes(uint(sha256(abi.encodePacked(sha256(abi.encodePacked(_dataBytes)))))); } // @dev - Bitcoin-way of hashing // @param _dataBytes - raw data to be hashed // @return - result of applying SHA-256 twice to raw data and then flipping the bytes function dblShaFlipMem(bytes memory _rawBytes, uint offset, uint len) internal view returns (uint) { return flip32Bytes(uint(sha256(abi.encodePacked(sha256mem(_rawBytes, offset, len))))); } // @dev – Read a bytes32 from an offset in the byte array function readBytes32(bytes memory data, uint offset) internal pure returns (bytes32) { bytes32 result; assembly { result := mload(add(add(data, 0x20), offset)) } return result; } // @dev – Read an uint32 from an offset in the byte array function readUint32(bytes memory data, uint offset) internal pure returns (uint32) { uint32 result; assembly { let word := mload(add(add(data, 0x20), offset)) result := add(byte(3, word), add(mul(byte(2, word), 0x100), add(mul(byte(1, word), 0x10000), mul(byte(0, word), 0x1000000)))) } return result; } // @dev - Bitcoin-way of computing the target from the 'bits' field of a block header // based on http://www.righto.com/2014/02/bitcoin-mining-hard-way-algorithms.html//ref3 // // @param _bits - difficulty in bits format // @return - difficulty in target format function targetFromBits(uint32 _bits) internal pure returns (uint) { uint exp = _bits / 0x1000000; // 2**24 uint mant = _bits & 0xffffff; return mant * 256**(exp - 3); } uint constant DOGECOIN_DIFFICULTY_ONE = 0xFFFFF * 256**(0x1e - 3); // @dev - Calculate dogecoin difficulty from target // https://en.bitcoin.it/wiki/Difficulty // Min difficulty for bitcoin is 0x1d00ffff // Min difficulty for dogecoin is 0x1e0fffff function targetToDiff(uint target) internal pure returns (uint) { return DOGECOIN_DIFFICULTY_ONE / target; } // @dev - Parse an array of bytes32 function parseBytes32Array(bytes calldata data) external pure returns (bytes32[] memory) { require(data.length % 32 == 0); uint count = data.length / 32; bytes32[] memory hashes = new bytes32[](count); for (uint i=0; i<count; ++i) { hashes[i] = readBytes32(data, 32*i); } return hashes; } // 0x00 version // 0x04 prev block hash // 0x24 merkle root // 0x44 timestamp // 0x48 bits // 0x4c nonce // @dev - extract version field from a raw Dogecoin block header // // @param _blockHeader - Dogecoin block header bytes // @param pos - where to start reading version from // @return - block's version in big endian format function getVersion(bytes memory _blockHeader, uint pos) internal pure returns (uint32 version) { assembly { let word := mload(add(add(_blockHeader, 0x4), pos)) version := add(byte(24, word), add(mul(byte(25, word), 0x100), add(mul(byte(26, word), 0x10000), mul(byte(27, word), 0x1000000)))) } } // @dev - extract previous block field from a raw Dogecoin block header // // @param _blockHeader - Dogecoin block header bytes // @param pos - where to start reading hash from // @return - hash of block's parent in big endian format function getHashPrevBlock(bytes memory _blockHeader, uint pos) internal pure returns (uint) { uint hashPrevBlock; assembly { hashPrevBlock := mload(add(add(_blockHeader, 0x24), pos)) } return flip32Bytes(hashPrevBlock); } // @dev - extract Merkle root field from a raw Dogecoin block header // // @param _blockHeader - Dogecoin block header bytes // @param pos - where to start reading root from // @return - block's Merkle root in big endian format function getHeaderMerkleRoot(bytes memory _blockHeader, uint pos) public pure returns (uint) { uint merkle; assembly { merkle := mload(add(add(_blockHeader, 0x44), pos)) } return flip32Bytes(merkle); } // @dev - extract bits field from a raw Dogecoin block header // // @param _blockHeader - Dogecoin block header bytes // @param pos - where to start reading bits from // @return - block's difficulty in bits format, also big-endian function getBits(bytes memory _blockHeader, uint pos) internal pure returns (uint32 bits) { assembly { let word := mload(add(add(_blockHeader, 0x50), pos)) bits := add(byte(24, word), add(mul(byte(25, word), 0x100), add(mul(byte(26, word), 0x10000), mul(byte(27, word), 0x1000000)))) } } // @dev - extract timestamp field from a raw Dogecoin block header // // @param _blockHeader - Dogecoin block header bytes // @param pos - where to start reading bits from // @return - block's timestamp in big-endian format function getTimestamp(bytes memory _blockHeader, uint pos) internal pure returns (uint32 time) { assembly { let word := mload(add(add(_blockHeader, 0x4c), pos)) time := add(byte(24, word), add(mul(byte(25, word), 0x100), add(mul(byte(26, word), 0x10000), mul(byte(27, word), 0x1000000)))) } } // @dev - converts raw bytes representation of a Dogecoin block header to struct representation // // @param _rawBytes - first 80 bytes of a block header // @return - exact same header information in BlockHeader struct form function parseHeaderBytes(bytes memory _rawBytes, uint pos) internal view returns (BlockHeader memory bh) { bh.version = getVersion(_rawBytes, pos); bh.time = getTimestamp(_rawBytes, pos); bh.bits = getBits(_rawBytes, pos); bh.blockHash = dblShaFlipMem(_rawBytes, pos, 80); bh.prevBlock = getHashPrevBlock(_rawBytes, pos); bh.merkleRoot = getHeaderMerkleRoot(_rawBytes, pos); } uint32 constant VERSION_AUXPOW = (1 << 8); // @dev - Converts a bytes of size 4 to uint32, // e.g. for input [0x01, 0x02, 0x03 0x04] returns 0x01020304 function bytesToUint32Flipped(bytes memory input, uint pos) internal pure returns (uint32 result) { result = uint32(uint8(input[pos])) + uint32(uint8(input[pos + 1]))*(2**8) + uint32(uint8(input[pos + 2]))*(2**16) + uint32(uint8(input[pos + 3]))*(2**24); } // @dev - checks version to determine if a block has merge mining information function isMergeMined(bytes memory _rawBytes, uint pos) internal pure returns (bool) { return bytesToUint32Flipped(_rawBytes, pos) & VERSION_AUXPOW != 0; } // @dev - checks version to determine if a block has merge mining information function isMergeMined(BlockHeader memory _blockHeader) internal pure returns (bool) { return _blockHeader.version & VERSION_AUXPOW != 0; } // @dev - Verify block header // @param _blockHeaderBytes - array of bytes with the block header // @param _pos - starting position of the block header // @param _len - length of the block header // @param _proposedBlockScryptHash - proposed block scrypt hash // @return - [ErrorCode, BlockSha256Hash, BlockScryptHash, IsMergeMined] function verifyBlockHeader(bytes calldata _blockHeaderBytes, uint _pos, uint _len, uint _proposedBlockScryptHash) external view returns (uint, uint, uint, bool) { BlockHeader memory blockHeader = parseHeaderBytes(_blockHeaderBytes, _pos); uint blockSha256Hash = blockHeader.blockHash; if (isMergeMined(blockHeader)) { AuxPoW memory ap = parseAuxPoW(_blockHeaderBytes, _pos, _len); if (flip32Bytes(ap.scryptHash) > targetFromBits(blockHeader.bits)) { return (ERR_PROOF_OF_WORK, blockHeader.blockHash, ap.scryptHash, true); } uint auxPoWCode = checkAuxPoW(blockSha256Hash, ap); if (auxPoWCode != 1) { return (auxPoWCode, blockHeader.blockHash, ap.scryptHash, true); } return (0, blockHeader.blockHash, ap.scryptHash, true); } else { if (flip32Bytes(_proposedBlockScryptHash) > targetFromBits(blockHeader.bits)) { return (ERR_PROOF_OF_WORK, blockHeader.blockHash, _proposedBlockScryptHash, false); } return (0, blockHeader.blockHash, _proposedBlockScryptHash, false); } } // @dev - Calculate difficulty from compact representation (bits) found in block function diffFromBits(uint32 bits) external pure returns (uint) { return targetToDiff(targetFromBits(bits)); } // For verifying Dogecoin difficulty uint constant DIFFICULTY_ADJUSTMENT_INTERVAL = 1; // Bitcoin adjusts every block uint constant TARGET_TIMESPAN = 60; // 1 minute uint constant TARGET_TIMESPAN_DIV_4 = TARGET_TIMESPAN / 4; uint constant TARGET_TIMESPAN_MUL_4 = TARGET_TIMESPAN * 4; uint constant UNROUNDED_MAX_TARGET = 2**224 - 1; // different from (2**16-1)*2**208 http =//bitcoin.stackexchange.com/questions/13803/how/ exactly-was-the-original-coefficient-for-difficulty-determined uint constant POW_LIMIT = 0x00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; // @dev - Implementation of DigiShield, almost directly translated from // C++ implementation of Dogecoin. See function calculateDogecoinNextWorkRequired // on dogecoin/src/dogecoin.cpp for more details. // Calculates the next block's difficulty based on the current block's elapsed time // and the desired mining time for a block, which is 60 seconds after block 145k. // // @param _actualTimespan - time elapsed from previous block creation til current block creation; // i.e., how much time it took to mine the current block // @param _bits - previous block header difficulty (in bits) // @return - expected difficulty for the next block function calculateDigishieldDifficulty(int64 _actualTimespan, uint32 _bits) external pure returns (uint32 result) { int64 retargetTimespan = int64(TARGET_TIMESPAN); int64 nModulatedTimespan = int64(_actualTimespan); nModulatedTimespan = retargetTimespan + int64(nModulatedTimespan - retargetTimespan) / int64(8); //amplitude filter int64 nMinTimespan = retargetTimespan - (int64(retargetTimespan) / int64(4)); int64 nMaxTimespan = retargetTimespan + (int64(retargetTimespan) / int64(2)); // Limit adjustment step if (nModulatedTimespan < nMinTimespan) { nModulatedTimespan = nMinTimespan; } else if (nModulatedTimespan > nMaxTimespan) { nModulatedTimespan = nMaxTimespan; } // Retarget uint bnNew = targetFromBits(_bits); bnNew = bnNew * uint(nModulatedTimespan); bnNew = uint(bnNew) / uint(retargetTimespan); if (bnNew > POW_LIMIT) { bnNew = POW_LIMIT; } return toCompactBits(bnNew); } // @dev - shift information to the right by a specified number of bits // // @param _val - value to be shifted // @param _shift - number of bits to shift // @return - `_val` shifted `_shift` bits to the right, i.e. divided by 2**`_shift` function shiftRight(uint _val, uint _shift) private pure returns (uint) { return _val / uint(2)**_shift; } // @dev - shift information to the left by a specified number of bits // // @param _val - value to be shifted // @param _shift - number of bits to shift // @return - `_val` shifted `_shift` bits to the left, i.e. multiplied by 2**`_shift` function shiftLeft(uint _val, uint _shift) private pure returns (uint) { return _val * uint(2)**_shift; } // @dev - get the number of bits required to represent a given integer value without losing information // // @param _val - unsigned integer value // @return - given value's bit length function bitLen(uint _val) private pure returns (uint length) { uint int_type = _val; while (int_type > 0) { int_type = shiftRight(int_type, 1); length += 1; } } // @dev - Convert uint256 to compact encoding // based on https://github.com/petertodd/python-bitcoinlib/blob/2a5dda45b557515fb12a0a18e5dd48d2f5cd13c2/bitcoin/core/serialize.py // Analogous to arith_uint256::GetCompact from C++ implementation // // @param _val - difficulty in target format // @return - difficulty in bits format function toCompactBits(uint _val) private pure returns (uint32) { uint nbytes = uint (shiftRight((bitLen(_val) + 7), 3)); uint32 compact = 0; if (nbytes <= 3) { compact = uint32 (shiftLeft((_val & 0xFFFFFF), 8 * (3 - nbytes))); } else { compact = uint32 (shiftRight(_val, 8 * (nbytes - 3))); compact = uint32 (compact & 0xFFFFFF); } // If the sign bit (0x00800000) is set, divide the mantissa by 256 and // increase the exponent to get an encoding without it set. if ((compact & 0x00800000) > 0) { compact = uint32(shiftRight(compact, 8)); nbytes += 1; } return compact | uint32(shiftLeft(nbytes, 24)); } /** * Dead code. * This is currently unused code. This should be deleted once it is deemed no longer useful. */ // Check whether `btcAddress` is in the transaction outputs *and* // whether *at least* `value` has been sent to it. function checkValueSent(bytes memory txBytes, bytes20 btcAddress, uint value) private pure returns (bool) { uint pos = 4; // skip version pos = skipInputs(txBytes, pos); // find end of inputs // scan *all* the outputs and find where they are uint[] memory output_values; uint[] memory script_starts; uint[] memory output_script_lens; (output_values, script_starts, output_script_lens,) = scanOutputs(txBytes, pos, 0); // look at each output and check whether it at least value to btcAddress for (uint i = 0; i < output_values.length; i++) { bytes20 pkhash = parseOutputScript(txBytes, script_starts[i], output_script_lens[i]); if (pkhash == btcAddress && output_values[i] >= value) { return true; } } return false; } // Get the pubkeyhash / scripthash from an output script. Assumes // pay-to-pubkey-hash (P2PKH) or pay-to-script-hash (P2SH) outputs. // Returns the pubkeyhash/ scripthash, or zero if unknown output. function parseOutputScript(bytes memory txBytes, uint pos, uint script_len) private pure returns (bytes20) { if (isP2PKH(txBytes, pos, script_len)) { return sliceBytes20(txBytes, pos + 3); } else if (isP2SH(txBytes, pos, script_len)) { return sliceBytes20(txBytes, pos + 2); } else { return bytes20(0); } } // returns true if the bytes located in txBytes by pos and // script_len represent a P2SH script function isP2SH(bytes memory txBytes, uint pos, uint script_len) private pure returns (bool) { return (script_len == 23) // 20 byte scripthash + 3 bytes of script && (txBytes[pos + 0] == 0xa9) // OP_HASH160 && (txBytes[pos + 1] == 0x14) // bytes to push && (txBytes[pos + 22] == 0x87); // OP_EQUAL } // scan the full transaction bytes and return the first two output // values (in satoshis) and addresses (in binary) function getFirstTwoOutputs(bytes memory txBytes) internal pure returns (uint, bytes20, uint, bytes20) { uint pos; uint[] memory output_script_lens; uint[] memory script_starts; uint[] memory output_values; bytes20[] memory output_public_key_hashes = new bytes20[](2); pos = 4; // skip version pos = skipInputs(txBytes, pos); (output_values, script_starts, output_script_lens, pos) = scanOutputs(txBytes, pos, 2); for (uint i = 0; i < 2; i++) { bytes20 pkhash = parseP2PKHOutputScript(txBytes, script_starts[i], output_script_lens[i]); output_public_key_hashes[i] = pkhash; } return (output_values[0], output_public_key_hashes[0], output_values[1], output_public_key_hashes[1]); } function ptr(UintWrapper memory uw) private pure returns (uint addr) { assembly { addr := uw } } }
Returns true if the tx output is an embedded ethereum address txBytes Buffer where the entire transaction is stored. pos Index into the tx buffer where the script is stored. len Size of the script in terms of bytes./ scriptPub format for the ethereum address is 0x6a OP_RETURN 0x14 PUSH20 [] 20 bytes of the ethereum address
function isEthereumAddress(bytes memory txBytes, uint pos, uint len) private pure returns (bool) { return len == 20+2 && txBytes[pos] == bytes1(0x6a) && txBytes[pos+1] == bytes1(0x14); }
12,605,603
// SPDX-License-Identifier: MIT pragma solidity ^0.4.24; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false mapping(address => uint256) authorizedContracts; // Only Authorized Contracts can call this contract struct Flight { bool isRegistered; uint8 statusCode; uint256 updatedTimestamp; address airline; address[] passAddress; } mapping(bytes32 => Flight) private flights; struct AirLine { bool isRegistered; bool isFunded; address airlineAddress; string airlineName; } mapping(address => AirLine) private airlines; struct Insurance { bytes32 flightID; uint256 insuranceAmount; address passengerAddress; bool insuranceStatus; bool isTaken; } mapping (address => Insurance) private passenger; uint256 public constant insuranceFee = 1 ether; mapping(address => fundInfo) private Funds; struct fundInfo { address accountAddress; uint256 amount; } /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ event AuthorizedCaller(address caller); event DeAuthorizedCaller(address caller); event RegisterAirline(address indexed account); event RegisterFlight(bytes32 flightKey); event Bought(address buyer, bytes32 flightKey, uint256 amount); event Creditted(bytes32 flightKey); event Paid(address insuree, uint256 amount); /** * @dev Constructor * The deploying account becomes contractOwner */ constructor ( ) public { contractOwner = msg.sender; authorizedContracts[msg.sender]=1; airlines[msg.sender].isRegistered = true; airlines[msg.sender].isFunded = true; airlines[msg.sender].airlineAddress = contractOwner; airlines[msg.sender].airlineName = "Bash"; emit RegisterAirline(contractOwner); emit AuthorizedCaller(contractOwner); } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } /** * @dev Modifier that requires the caller is listed in authorizedContracts with value 1 */ modifier isCallerAuthorized() { require(authorizedContracts[msg.sender] == 1 , "Caller is not authorized"); _; } function authorizeContract(address dataContract) external requireContractOwner returns(bool){ authorizedContracts[dataContract] = 1; emit AuthorizedCaller(dataContract); return true; } function deauthorizeContract(address dataContract) external requireContractOwner returns(bool){ delete authorizedContracts[dataContract]; emit DeAuthorizedCaller(dataContract); return true; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns(bool) { return operational; } /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isAirline ( address _airline ) public view returns(bool) { //require(airlines[air].isRegistered, "AirLines is not registered"); //return airlines[air].isRegistered; return airlines[_airline].isFunded; } /** * @dev Get Airline registration status * * @return A bool that indicate Airline registration status */ function isRegisteredAirline( address _airline ) public view returns(bool) { return airlines[_airline].isRegistered; } /** * @dev Get Flight registration status * * @return A bool that indicate flight registration status */ function isRegisteredFlight( bytes32 flightID ) public view returns(bool) { return flights[flightID].isRegistered; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode ) external requireContractOwner { operational = mode; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline ( address airAddress, string airName ) requireIsOperational external returns (bool) { require(!airlines[airAddress].isRegistered, "Airline is already registered."); airlines[airAddress].airlineAddress = airAddress; airlines[airAddress].airlineName = airName; airlines[airAddress].isRegistered = true; airlines[airAddress].isFunded = false; emit RegisterAirline(airAddress); return true; } /** * @dev Add a flight to the flights queue * Can only be called from FlightSuretyApp contract * */ function registerFlight ( address airline, bytes32 flightID, uint256 timeStamp ) requireIsOperational external { require(airlines[airline].isFunded, "Not Funded yet"); require(!flights[flightID].isRegistered, "Flight is already registered."); flights[flightID].airline = airline; flights[flightID].updatedTimestamp = timeStamp; flights[flightID].statusCode = 0; flights[flightID].isRegistered = true; emit RegisterFlight(flightID); } /** * @dev Buy insurance for a flight * */ function buy ( bytes32 flightID, address passengerID, uint256 recievedinsurence ) requireIsOperational external payable returns(bool) { require(passenger[passengerID].insuranceStatus == false, "You already bought an insurence for current flight."); passenger[passengerID].flightID = flightID; passenger[passengerID].passengerAddress = passengerID; passenger[passengerID].insuranceStatus = true; passenger[passengerID].isTaken == false; // is taken yet or not // transfer insurance to airline Funds[passengerID].accountAddress = passengerID; Funds[passengerID].amount = recievedinsurence; flights[flightID].passAddress.push(passengerID); emit Bought(passengerID, flightID, recievedinsurence); return true; } /** * @dev Credits payouts to insurees */ function creditInsurees ( bytes32 flightID, uint256 amount ) external { for (uint i=0; i < flights[flightID].passAddress.length; i++) { address add = flights[flightID].passAddress[i]; uint256 insuOr = Funds[add].amount; uint256 insuAf = insuOr.mul(amount).div(100); Funds[add].amount = insuAf; uint256 insuAir = Funds[flights[flightID].airline].amount; insuAir = insuAir - ( insuAf - insuOr ); Funds[flights[flightID].airline].amount = insuAir; } emit Creditted(flightID); } /** * @dev Transfers eligible payout funds to insuree * */ function payInsurance ( bytes32 flightID, address passengerAddress ) requireIsOperational external payable { require(passenger[passengerAddress].flightID == flightID, "is not a passenger in this flight."); require(passenger[passengerAddress].insuranceStatus == true, "You didnt bought an insurence for current flight."); require(passenger[passengerAddress].isTaken == false, "You already Claimed your insurence."); uint amount = Funds[passengerAddress].amount; passenger[passengerAddress].insuranceStatus == true; // reset insurance status passenger[passengerAddress].isTaken == true; // claimed the insuance Funds[passengerAddress].amount = 0; // reset insurance amount address passengerToTransfer = Funds[passengerAddress].accountAddress; passengerToTransfer.transfer(amount); // transfer insurance to passenger emit Paid(passengerAddress, amount); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund ( address airAddress ) requireIsOperational public payable { //require(msg.value >= 10 ether, "Inadaquate funds, require more than or equal 10 ether"); require(airlines[airAddress].isRegistered, "AirLine should be registered before getting funded"); Funds[airAddress].accountAddress = airAddress; Funds[airAddress].amount = msg.value; airlines[airAddress].isFunded = true; } // A function to change flight status code function processFlightStatus ( bytes32 flightID, uint8 _statusCode ) requireIsOperational external { flights[flightID].statusCode = _statusCode; } /** * @dev Fallback function for funding smart contract. * */ function() external payable { fund(msg.sender); } /* fallback() external payable { //contractOwner.transfer(msg.value); } receive() external payable { //contractOwner.transfer(msg.value); }*/ }
Add an airline to the registration queue Can only be called from FlightSuretyApp contract/
function registerAirline ( address airAddress, string airName ) requireIsOperational external returns (bool) { require(!airlines[airAddress].isRegistered, "Airline is already registered."); airlines[airAddress].airlineAddress = airAddress; airlines[airAddress].airlineName = airName; airlines[airAddress].isRegistered = true; airlines[airAddress].isFunded = false; emit RegisterAirline(airAddress); return true; }
14,042,530
// SPDX-License-Identifier: Unknown // 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.5.7; pragma experimental ABIEncoderV2; import "./balancer/BFactory.sol"; import "../interfaces/IFactory.sol"; import "../interfaces/IERC20.sol"; import "../interfaces/IFixedRateExchange.sol"; import "../interfaces/IPool.sol"; import "../interfaces/IDispenser.sol"; contract FactoryRouter is BFactory { address public routerOwner; address public factory; address public fixedRate; uint256 public swapOceanFee = 1e15; mapping(address => bool) public oceanTokens; mapping(address => bool) public ssContracts; mapping(address => bool) public fixedPrice; mapping(address => bool) public dispenser; event NewPool(address indexed poolAddress, bool isOcean); modifier onlyRouterOwner() { require(routerOwner == msg.sender, "OceanRouter: NOT OWNER"); _; } constructor( address _routerOwner, address _oceanToken, address _bpoolTemplate, address _opfCollector, address[] memory _preCreatedPools ) public BFactory(_bpoolTemplate, _opfCollector, _preCreatedPools) { routerOwner = _routerOwner; opfCollector = _opfCollector; oceanTokens[_oceanToken] = true; } function changeRouterOwner(address _routerOwner) public onlyRouterOwner { require( _routerOwner != address(0), 'Invalid new router owner' ); routerOwner = _routerOwner; } function addOceanToken(address oceanTokenAddress) public onlyRouterOwner { oceanTokens[oceanTokenAddress] = true; } function removeOceanToken(address oceanTokenAddress) public onlyRouterOwner { oceanTokens[oceanTokenAddress] = false; } function addSSContract(address _ssContract) external onlyRouterOwner { ssContracts[_ssContract] = true; } function addFactory(address _factory) external onlyRouterOwner { require(factory == address(0), "FACTORY ALREADY SET"); factory = _factory; } function addFixedRateContract(address _fixedRate) external onlyRouterOwner { fixedPrice[_fixedRate] = true; } function addDispenserContract(address _dispenser) external onlyRouterOwner { dispenser[_dispenser] = true; } function getOPFFee(address baseToken) public view returns (uint256) { if (oceanTokens[baseToken] == true) { return 0; } else return swapOceanFee; } function updateOPFFee(uint256 _newSwapOceanFee) external onlyRouterOwner { // TODO: add a maximum? how much? add event? swapOceanFee = _newSwapOceanFee; } /** * @dev Deploys a new `OceanPool` on Ocean Friendly Fork modified for 1SS. This function cannot be called directly, but ONLY through the ERC20DT contract from a ERC20DEployer role ssContract address tokens [datatokenAddress, basetokenAddress] publisherAddress user which will be assigned the vested amount. * @param tokens precreated parameter * @param ssParams params for the ssContract. * [0] = rate (wei) * [1] = basetoken decimals * [2] = vesting amount (wei) * [3] = vested blocks * [4] = initial liquidity in basetoken for pool creation * @param swapFees swapFees (swapFee, swapMarketFee), swapOceanFee will be set automatically later * [0] = swapFee for LP Providers * [1] = swapFee for marketplace runner . * @param addresses refers to an array of addresses passed by user * [0] = side staking contract address * [1] = basetoken address for pool creation(OCEAN or other) * [2] = basetokenSender user which will provide the baseToken amount for initial liquidity * [3] = publisherAddress user which will be assigned the vested amount * [4] = marketFeeCollector marketFeeCollector address [5] = poolTemplateAddress @return pool address */ function deployPool( address[2] calldata tokens, // [datatokenAddress, basetokenAddress] uint256[] calldata ssParams, uint256[] calldata swapFees, address[] calldata addresses //[controller,basetokenAddress,basetokenSender,publisherAddress, marketFeeCollector,poolTemplateAddress] ) external returns (address) { require( IFactory(factory).erc20List(msg.sender) == true, "FACTORY ROUTER: NOT ORIGINAL ERC20 TEMPLATE" ); require( ssContracts[addresses[0]] == true, "FACTORY ROUTER: invalid ssContract" ); require(ssParams[1] > 0, "Wrong decimals"); // TODO: do we need this? used only for the event? bool flag; if (oceanTokens[tokens[1]] == true) { flag = true; } // we pull basetoken for creating initial pool and send it to the controller (ssContract) IERC20 bt = IERC20(tokens[1]); require(bt.transferFrom(addresses[2], addresses[0], ssParams[4]) ,'DeployPool: Failed to transfer initial liquidity'); address pool = newBPool( tokens, ssParams, swapFees, addresses ); require(pool != address(0), "FAILED TO DEPLOY POOL"); emit NewPool(pool, flag); return pool; } function getLength(IERC20[] memory array) internal pure returns (uint256) { return array.length; } /** * @dev deployFixedRate * Creates a new FixedRateExchange setup. * As for deployPool, this function cannot be called directly, * but ONLY through the ERC20DT contract from a ERC20DEployer role * @param fixedPriceAddress fixedPriceAddress * @param addresses array of addresses [baseToken,owner,marketFeeCollector] * @param uints array of uints [baseTokenDecimals,dataTokenDecimals, fixedRate, marketFee, withMint] @return exchangeId */ function deployFixedRate( address fixedPriceAddress, address[] calldata addresses, uint[] calldata uints ) external returns (bytes32 exchangeId) { require( IFactory(factory).erc20List(msg.sender) == true, "FACTORY ROUTER: NOT ORIGINAL ERC20 TEMPLATE" ); require( fixedPrice[fixedPriceAddress] == true, "FACTORY ROUTER: Invalid FixedPriceContract" ); exchangeId = IFixedRateExchange(fixedPriceAddress).createWithDecimals( msg.sender, addresses, uints ); } /** * @dev deployDispenser * Activates a new Dispenser * As for deployPool, this function cannot be called directly, * but ONLY through the ERC20DT contract from a ERC20DEployer role * @param _dispenser dispenser contract address * @param datatoken refers to datatoken address. * @param maxTokens - max tokens to dispense * @param maxBalance - max balance of requester. * @param owner - owner * @param allowedSwapper - if !=0, only this address can request DTs */ function deployDispenser( address _dispenser, address datatoken, uint256 maxTokens, uint256 maxBalance, address owner, address allowedSwapper ) external { require( IFactory(factory).erc20List(msg.sender) == true, "FACTORY ROUTER: NOT ORIGINAL ERC20 TEMPLATE" ); require( dispenser[_dispenser] == true, "FACTORY ROUTER: Invalid DispenserContract" ); IDispenser(_dispenser).create(datatoken, maxTokens, maxBalance, owner, allowedSwapper); } function addPoolTemplate(address poolTemplate) external onlyRouterOwner { _addPoolTemplate(poolTemplate); } function removePoolTemplate(address poolTemplate) external onlyRouterOwner { _removePoolTemplate(poolTemplate); } // If you need to buy multiple DT (let's say for a compute job which has multiple datasets), // you have to send one transaction for each DT that you want to buy. // Perks: // one single call to buy multiple DT for multiple assets (better UX, better gas optimization) enum operationType { SwapExactIn, SwapExactOut, FixedRate, Dispenser} struct Operations{ bytes32 exchangeIds; // used for fixedRate or dispenser address source;// pool, dispenser or fixed rate address operationType operation; // type of operation: enum operationType address tokenIn; // token in address, only for pools uint256 amountsIn; // ExactAmount In for swapExactIn operation, maxAmount In for swapExactOut address tokenOut; // token out address, only for pools uint256 amountsOut; // minAmountOut for swapExactIn or exactAmountOut for swapExactOut uint256 maxPrice; // maxPrice, only for pools } // require tokenIn approvals for router from user. (except for dispenser operations) function buyDTBatch( Operations[] calldata _operations ) external { for (uint i= 0; i< _operations.length; i++) { if(_operations[i].operation == operationType.SwapExactIn) { // Get amountIn from user to router IERC20(_operations[i].tokenIn).transferFrom(msg.sender,address(this),_operations[i].amountsIn); // we approve pool to pull token from router IERC20(_operations[i].tokenIn).approve(_operations[i].source,_operations[i].amountsIn); // Perform swap (uint amountReceived,) = IPool(_operations[i].source) .swapExactAmountIn(_operations[i].tokenIn, _operations[i].amountsIn, _operations[i].tokenOut, _operations[i].amountsOut, _operations[i].maxPrice); // transfer token swapped to user require(IERC20(_operations[i].tokenOut).transfer(msg.sender,amountReceived),'Failed MultiSwap'); } else if (_operations[i].operation == operationType.SwapExactOut){ // calculate how much amount In we need for exact Out uint amountIn = IPool(_operations[i].source) .getAmountInExactOut(_operations[i].tokenIn,_operations[i].tokenOut,_operations[i].amountsOut); // pull amount In from user IERC20(_operations[i].tokenIn).transferFrom(msg.sender,address(this),amountIn); // we approve pool to pull token from router IERC20(_operations[i].tokenIn).approve(_operations[i].source,amountIn); // perform swap IPool(_operations[i].source) .swapExactAmountOut(_operations[i].tokenIn, _operations[i].amountsIn, _operations[i].tokenOut, _operations[i].amountsOut, _operations[i].maxPrice); // send amount out back to user require(IERC20(_operations[i].tokenOut) .transfer(msg.sender,_operations[i].amountsOut),'Failed MultiSwap'); } else if (_operations[i].operation == operationType.FixedRate) { // get datatoken address (,address datatoken,,,,,,,,,,) = IFixedRateExchange(_operations[i].source).getExchange(_operations[i].exchangeIds); // get tokenIn amount required for dt out (uint baseTokenAmount,,,) = IFixedRateExchange(_operations[i].source). calcBaseInGivenOutDT(_operations[i].exchangeIds,_operations[i].amountsOut); // pull tokenIn amount IERC20(_operations[i].tokenIn).transferFrom(msg.sender,address(this),baseTokenAmount); // we approve pool to pull token from router IERC20(_operations[i].tokenIn).approve(_operations[i].source,baseTokenAmount); // perform swap IFixedRateExchange(_operations[i].source) .buyDT(_operations[i].exchangeIds,_operations[i].amountsOut,_operations[i].amountsIn); // send dt out to user IERC20(datatoken).transfer(msg.sender,_operations[i].amountsOut); } else { IDispenser(_operations[i].source) .dispense(_operations[i].tokenOut,_operations[i].amountsOut,msg.sender); } } } }
TODO: add a maximum? how much? add event?
function updateOPFFee(uint256 _newSwapOceanFee) external onlyRouterOwner { swapOceanFee = _newSwapOceanFee; }
7,264,591
// SPDX-License-Identifier: MIT pragma solidity ^0.6.7; pragma experimental ABIEncoderV2; import "../strategy-base.sol"; import "../../../interfaces/dodo.sol"; contract StrategyDodoDodoUsdcLp is StrategyBase { // Token addresses address public constant dodo = 0x69Eb4FA4a2fbd498C257C57Ea8b7655a2559A581; address public constant usdc = 0xFF970A61A04b1cA14834A43f5dE4533eBDDB5CC8; address public constant rewards = 0x38Dbb42C4972116c88E27edFacD2451cf1b14255; address public constant dodo_dodo_usdc_lp = 0x6a58c68FF5C4e4D90EB6561449CC74A64F818dA5; address public constant dodoSwap = 0x88CBf433471A0CD8240D2a12354362988b4593E5; address public constant dodo_approve = 0xA867241cDC8d3b0C07C85cC06F25a0cD3b5474d8; address public constant dodoUsdcPair = 0x6a58c68FF5C4e4D90EB6561449CC74A64F818dA5; address[] public dodoUsdcRoute = [dodo_dodo_usdc_lp]; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyBase( dodo_dodo_usdc_lp, _governance, _strategist, _controller, _timelock ) { IERC20(dodo).approve(dodo_approve, uint256(-1)); IERC20(usdc).approve(dodo_approve, uint256(-1)); } function balanceOfPool() public view override returns (uint256) { uint256 amount = IDodoMine(rewards).balanceOf(address(this)); return amount; } function getHarvestable() external view returns (uint256) { uint256 _pendingDodo = IDodoMine(rewards).getPendingRewardByToken( address(this), dodo ); return _pendingDodo; } // **** Setters **** function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(rewards, 0); IERC20(want).safeApprove(rewards, _want); IDodoMine(rewards).deposit(_want); } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { IDodoMine(rewards).withdraw(_amount); return _amount; } // **** State Mutations **** function harvest() public override onlyBenevolent { // Anyone can harvest it at any given time. // I understand the possibility of being frontrun // But ETH is a dark forest, and I wanna see how this plays out // i.e. will be be heavily frontrunned? // if so, a new strategy will be deployed. // Collects DODO token IDodoMine(rewards).claimAllRewards(); // Swap half USDC for DODO uint256 _dodo = IERC20(dodo).balanceOf(address(this)); if (_dodo > 0) { address[] memory path = new address[](1); path[0] = dodoUsdcPair; IDodoSwap(dodoSwap).dodoSwapV2TokenToToken( dodo, usdc, _dodo.div(2), 1, path, 0, false, now + 60 ); } // Adds in liquidity for DODO/USDC _dodo = IERC20(dodo).balanceOf(address(this)); uint256 _usdc = IERC20(usdc).balanceOf(address(this)); if (_dodo > 0 && _usdc > 0) { IDodoSwap(dodoSwap).addDVMLiquidity( dodo_dodo_usdc_lp, _dodo, _usdc, 1, 1, 0, now + 60 ); // Donates DUST IERC20(dodo).transfer( IController(controller).treasury(), IERC20(dodo).balanceOf(address(this)) ); IERC20(usdc).safeTransfer( IController(controller).treasury(), IERC20(usdc).balanceOf(address(this)) ); } _distributePerformanceFeesAndDeposit(); } // **** Views **** function getName() external pure override returns (string memory) { return "StrategyDodoDodoUsdcLp"; } }
Anyone can harvest it at any given time. I understand the possibility of being frontrun But ETH is a dark forest, and I wanna see how this plays out i.e. will be be heavily frontrunned? if so, a new strategy will be deployed. Collects DODO token Swap half USDC for DODO Donates DUST
function harvest() public override onlyBenevolent { IDodoMine(rewards).claimAllRewards(); uint256 _dodo = IERC20(dodo).balanceOf(address(this)); if (_dodo > 0) { address[] memory path = new address[](1); path[0] = dodoUsdcPair; IDodoSwap(dodoSwap).dodoSwapV2TokenToToken( dodo, usdc, _dodo.div(2), 1, path, 0, false, now + 60 ); } uint256 _usdc = IERC20(usdc).balanceOf(address(this)); if (_dodo > 0 && _usdc > 0) { IDodoSwap(dodoSwap).addDVMLiquidity( dodo_dodo_usdc_lp, _dodo, _usdc, 1, 1, 0, now + 60 ); IERC20(dodo).transfer( IController(controller).treasury(), IERC20(dodo).balanceOf(address(this)) ); IERC20(usdc).safeTransfer( IController(controller).treasury(), IERC20(usdc).balanceOf(address(this)) ); } _distributePerformanceFeesAndDeposit(); }
14,095,042
./partial_match/4/0x80E682bb8E3bF3952Ca763C3D4dFb44E9B345Cc5/sources/eternal_page_v1_2b.sol
-------- distribute staking rewards-------- distribute xDai rewards
function DistributeRewards() public for (uint256 s = 0; s < stakeholders.length; s += 1){ address sh = stakeholders[s]; if(balances[sh].last_epoch_voted < epoch && (last_epoch_date.sub(balances[sh].stake_timestamp)) >= EPOCH_DURATION){ uint256 userStake = balances[sh].staked_token_balance; uint256 user_xdai_rewards_ = last_epoch_rewards.mul(userStake).div(last_epoch_total_stake_); uint256 user_staking_rewards_ = staking_rewards_amount.mul(userStake).div(last_epoch_total_stake_); balances[sh].last_collected_epoch = epoch; balances[sh].available_xdai_balance += user_xdai_rewards_; last_epoch_remaining_rewards_ = last_epoch_remaining_rewards_.sub(user_xdai_rewards_); total_xdai_rewards += user_xdai_rewards_; total_token_rewards += user_staking_rewards_; } } last_collect_timestamp = block.timestamp; last_collect_epoch = epoch; emit _RewardsDistributed(total_xdai_rewards, total_token_rewards);
8,745,129
// https://hermesdefi.io/ // SPDX-License-Identifier: GPL-3.0 pragma solidity =0.6.12; import "./libraries/HermesLibrary.sol"; import "./libraries/SafeMath.sol"; import "./libraries/TransferHelper.sol"; import "./interfaces/IHermesRouter02.sol"; import "./interfaces/IHermesFactory.sol"; import "./interfaces/IERC20.sol"; import "./interfaces/IWONE.sol"; contract HermesRouter02 is IHermesRouter02 { using SafeMathHermes for uint256; address public immutable override factory; address public immutable override WONE; modifier ensure(uint256 deadline) { require(deadline >= block.timestamp, "HermesRouter: EXPIRED"); _; } constructor(address _factory, address _WONE) public { factory = _factory; WONE = _WONE; } receive() external payable { assert(msg.sender == WONE); // only accept ONE via fallback from the WONE contract } // **** ADD LIQUIDITY **** function _addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin ) internal virtual returns (uint256 amountA, uint256 amountB) { // create the pair if it doesn't exist yet if (IHermesFactory(factory).getPair(tokenA, tokenB) == address(0)) { IHermesFactory(factory).createPair(tokenA, tokenB); } (uint256 reserveA, uint256 reserveB) = HermesLibrary.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint256 amountBOptimal = HermesLibrary.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, "HermesRouter: INSUFFICIENT_B_AMOUNT"); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint256 amountAOptimal = HermesLibrary.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, "HermesRouter: INSUFFICIENT_A_AMOUNT"); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external virtual override ensure(deadline) returns ( uint256 amountA, uint256 amountB, uint256 liquidity ) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); address pair = HermesLibrary.pairFor(factory, tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = IHermesPair(pair).mint(to); } function addLiquidityONE( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountONEMin, address to, uint256 deadline ) external payable virtual override ensure(deadline) returns ( uint256 amountToken, uint256 amountONE, uint256 liquidity ) { (amountToken, amountONE) = _addLiquidity( token, WONE, amountTokenDesired, msg.value, amountTokenMin, amountONEMin ); address pair = HermesLibrary.pairFor(factory, token, WONE); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); IWONE(WONE).deposit{value: amountONE}(); assert(IWONE(WONE).transfer(pair, amountONE)); liquidity = IHermesPair(pair).mint(to); // refund dust eth, if any if (msg.value > amountONE) TransferHelper.safeTransferONE(msg.sender, msg.value - amountONE); } // **** REMOVE LIQUIDITY **** function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) public virtual override ensure(deadline) returns (uint256 amountA, uint256 amountB) { address pair = HermesLibrary.pairFor(factory, tokenA, tokenB); IHermesPair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair (uint256 amount0, uint256 amount1) = IHermesPair(pair).burn(to); (address token0, ) = HermesLibrary.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, "HermesRouter: INSUFFICIENT_A_AMOUNT"); require(amountB >= amountBMin, "HermesRouter: INSUFFICIENT_B_AMOUNT"); } function removeLiquidityONE( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountONEMin, address to, uint256 deadline ) public virtual override ensure(deadline) returns (uint256 amountToken, uint256 amountONE) { (amountToken, amountONE) = removeLiquidity( token, WONE, liquidity, amountTokenMin, amountONEMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, amountToken); IWONE(WONE).withdraw(amountONE); TransferHelper.safeTransferONE(to, amountONE); } function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint256 amountA, uint256 amountB) { address pair = HermesLibrary.pairFor(factory, tokenA, tokenB); uint256 value = approveMax ? uint256(-1) : liquidity; IHermesPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); } function removeLiquidityONEWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountONEMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint256 amountToken, uint256 amountONE) { address pair = HermesLibrary.pairFor(factory, token, WONE); uint256 value = approveMax ? uint256(-1) : liquidity; IHermesPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountToken, amountONE) = removeLiquidityONE(token, liquidity, amountTokenMin, amountONEMin, to, deadline); } // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) **** function removeLiquidityONESupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountONEMin, address to, uint256 deadline ) public virtual override ensure(deadline) returns (uint256 amountONE) { (, amountONE) = removeLiquidity( token, WONE, liquidity, amountTokenMin, amountONEMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, IERC20Hermes(token).balanceOf(address(this))); IWONE(WONE).withdraw(amountONE); TransferHelper.safeTransferONE(to, amountONE); } function removeLiquidityONEWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountONEMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint256 amountONE) { address pair = HermesLibrary.pairFor(factory, token, WONE); uint256 value = approveMax ? uint256(-1) : liquidity; IHermesPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); amountONE = removeLiquidityONESupportingFeeOnTransferTokens( token, liquidity, amountTokenMin, amountONEMin, to, deadline ); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap( uint256[] memory amounts, address[] memory path, address _to ) internal virtual { for (uint256 i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0, ) = HermesLibrary.sortTokens(input, output); uint256 amountOut = amounts[i + 1]; (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0)); address to = i < path.length - 2 ? HermesLibrary.pairFor(factory, output, path[i + 2]) : _to; IHermesPair(HermesLibrary.pairFor(factory, input, output)).swap(amount0Out, amount1Out, to, new bytes(0)); } } function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external virtual override ensure(deadline) returns (uint256[] memory amounts) { amounts = HermesLibrary.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, "HermesRouter: INSUFFICIENT_OUTPUT_AMOUNT"); TransferHelper.safeTransferFrom(path[0], msg.sender, HermesLibrary.pairFor(factory, path[0], path[1]), amounts[0]); _swap(amounts, path, to); } function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external virtual override ensure(deadline) returns (uint256[] memory amounts) { amounts = HermesLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, "HermesRouter: EXCESSIVE_INPUT_AMOUNT"); TransferHelper.safeTransferFrom(path[0], msg.sender, HermesLibrary.pairFor(factory, path[0], path[1]), amounts[0]); _swap(amounts, path, to); } function swapExactONEForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable virtual override ensure(deadline) returns (uint256[] memory amounts) { require(path[0] == WONE, "HermesRouter: INVALID_PATH"); amounts = HermesLibrary.getAmountsOut(factory, msg.value, path); require(amounts[amounts.length - 1] >= amountOutMin, "HermesRouter: INSUFFICIENT_OUTPUT_AMOUNT"); IWONE(WONE).deposit{value: amounts[0]}(); assert(IWONE(WONE).transfer(HermesLibrary.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); } function swapTokensForExactONE( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external virtual override ensure(deadline) returns (uint256[] memory amounts) { require(path[path.length - 1] == WONE, "HermesRouter: INVALID_PATH"); amounts = HermesLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, "HermesRouter: EXCESSIVE_INPUT_AMOUNT"); TransferHelper.safeTransferFrom(path[0], msg.sender, HermesLibrary.pairFor(factory, path[0], path[1]), amounts[0]); _swap(amounts, path, address(this)); IWONE(WONE).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferONE(to, amounts[amounts.length - 1]); } function swapExactTokensForONE( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external virtual override ensure(deadline) returns (uint256[] memory amounts) { require(path[path.length - 1] == WONE, "HermesRouter: INVALID_PATH"); amounts = HermesLibrary.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, "HermesRouter: INSUFFICIENT_OUTPUT_AMOUNT"); TransferHelper.safeTransferFrom(path[0], msg.sender, HermesLibrary.pairFor(factory, path[0], path[1]), amounts[0]); _swap(amounts, path, address(this)); IWONE(WONE).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferONE(to, amounts[amounts.length - 1]); } function swapONEForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable virtual override ensure(deadline) returns (uint256[] memory amounts) { require(path[0] == WONE, "HermesRouter: INVALID_PATH"); amounts = HermesLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= msg.value, "HermesRouter: EXCESSIVE_INPUT_AMOUNT"); IWONE(WONE).deposit{value: amounts[0]}(); assert(IWONE(WONE).transfer(HermesLibrary.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); // refund dust eth, if any if (msg.value > amounts[0]) TransferHelper.safeTransferONE(msg.sender, msg.value - amounts[0]); } // **** SWAP (supporting fee-on-transfer tokens) **** // requires the initial amount to have already been sent to the first pair function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual { for (uint256 i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0, ) = HermesLibrary.sortTokens(input, output); IHermesPair pair = IHermesPair(HermesLibrary.pairFor(factory, input, output)); uint256 amountInput; uint256 amountOutput; { // scope to avoid stack too deep errors (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); (uint256 reserveInput, uint256 reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountInput = IERC20Hermes(input).balanceOf(address(pair)).sub(reserveInput); amountOutput = HermesLibrary.getAmountOut(amountInput, reserveInput, reserveOutput); } (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOutput) : (amountOutput, uint256(0)); address to = i < path.length - 2 ? HermesLibrary.pairFor(factory, output, path[i + 2]) : _to; pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external virtual override ensure(deadline) { TransferHelper.safeTransferFrom(path[0], msg.sender, HermesLibrary.pairFor(factory, path[0], path[1]), amountIn); uint256 balanceBefore = IERC20Hermes(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20Hermes(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, "HermesRouter: INSUFFICIENT_OUTPUT_AMOUNT" ); } function swapExactONEForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable virtual override ensure(deadline) { require(path[0] == WONE, "HermesRouter: INVALID_PATH"); uint256 amountIn = msg.value; IWONE(WONE).deposit{value: amountIn}(); assert(IWONE(WONE).transfer(HermesLibrary.pairFor(factory, path[0], path[1]), amountIn)); uint256 balanceBefore = IERC20Hermes(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20Hermes(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, "HermesRouter: INSUFFICIENT_OUTPUT_AMOUNT" ); } function swapExactTokensForONESupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external virtual override ensure(deadline) { require(path[path.length - 1] == WONE, "HermesRouter: INVALID_PATH"); TransferHelper.safeTransferFrom(path[0], msg.sender, HermesLibrary.pairFor(factory, path[0], path[1]), amountIn); _swapSupportingFeeOnTransferTokens(path, address(this)); uint256 amountOut = IERC20Hermes(WONE).balanceOf(address(this)); require(amountOut >= amountOutMin, "HermesRouter: INSUFFICIENT_OUTPUT_AMOUNT"); IWONE(WONE).withdraw(amountOut); TransferHelper.safeTransferONE(to, amountOut); } // **** LIBRARY FUNCTIONS **** function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) public pure virtual override returns (uint256 amountB) { return HermesLibrary.quote(amountA, reserveA, reserveB); } function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) public pure virtual override returns (uint256 amountOut) { return HermesLibrary.getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) public pure virtual override returns (uint256 amountIn) { return HermesLibrary.getAmountIn(amountOut, reserveIn, reserveOut); } function getAmountsOut(uint256 amountIn, address[] memory path) public view virtual override returns (uint256[] memory amounts) { return HermesLibrary.getAmountsOut(factory, amountIn, path); } function getAmountsIn(uint256 amountOut, address[] memory path) public view virtual override returns (uint256[] memory amounts) { return HermesLibrary.getAmountsIn(factory, amountOut, path); } }
SWAP requires the initial amount to have already been sent to the first pair
function _swap( uint256[] memory amounts, address[] memory path, address _to ) internal virtual { for (uint256 i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0, ) = HermesLibrary.sortTokens(input, output); uint256 amountOut = amounts[i + 1]; (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0)); address to = i < path.length - 2 ? HermesLibrary.pairFor(factory, output, path[i + 2]) : _to; IHermesPair(HermesLibrary.pairFor(factory, input, output)).swap(amount0Out, amount1Out, to, new bytes(0)); } }
12,978,457
./partial_match/56/0xD50aAb6B210fe049B6c5262f5A7676204699AB8E/sources/Vault.sol
bytes4(keccak256(bytes('transfer(address,uint256)')));
function safeTransfer(address token, address to, uint256 value) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "!safeTransfer"); }
11,079,596
/** *Submitted for verification at Etherscan.io on 2022-03-06 */ // 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 Polytopia 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("Polytopia", "POLYTOPIA") { 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 = 1; uint256 buyLiquidityFee = 1; uint256 buyDevFee = 10; uint256 sellMarketingFee = 1; uint256 sellLiquidityFee = 1; uint256 sellDevFee = 10; 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("Polytopia", "POLYTOPIA") { 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 = 1; uint256 buyLiquidityFee = 1; uint256 buyDevFee = 10; uint256 sellMarketingFee = 1; uint256 sellLiquidityFee = 1; uint256 sellDevFee = 10; 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);
15,014,959
pragma solidity ^0.4.23; // Copyright 2018 OpenST Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ---------------------------------------------------------------------------- // MessageBus Library // // http://www.simpletoken.org/ // // ---------------------------------------------------------------------------- import "../lib/MerklePatriciaProof.sol"; import "../lib/SafeMath.sol"; import "../lib/BytesLib.sol"; library MessageBus { using SafeMath for uint256; /* Enum */ /** Status of the message state machine */ enum MessageStatus { Undeclared, Declared, Progressed, DeclaredRevocation, Revoked } /** Status of the message state machine */ enum MessageBoxType { Outbox, Inbox } /* Struct */ /** MessageBox stores the inbox and outbox mapping */ struct MessageBox { /** Maps messageHash to the MessageStatus. */ mapping(bytes32 /* messageHash */ => MessageStatus) outbox; /** Maps messageHash to the MessageStatus. */ mapping(bytes32 /* messageHash */ => MessageStatus) inbox; } /** Message */ struct Message { /** * intent hash, this can be staking intent hash, redemption intent * hash, gateway linking hash */ bytes32 intentHash; /** nonce of the sender */ uint256 nonce; /** gas price that sender will pay for reward */ uint256 gasPrice; /** gas limit that sender will pay */ uint256 gasLimit; /** sender address */ address sender; /** hash lock provided by the facilitator */ bytes32 hashLock; /** * the amount of the gas consumed, this is used for reward * calculation */ uint256 gasConsumed; } /* constants */ /** Position of outbox in struct MessageBox */ uint8 constant OUTBOX_OFFSET = 0; /** Position of inbox in struct MessageBox */ uint8 constant INBOX_OFFSET = 1; /** * @notice Declare a new message. This will update the outbox status to * `Declared` for the given message hash * * @param _messageBox Message Box * @param _messageTypeHash Message type hash * @param _message Message object * @param _signature Signed data. * * @return messageHash_ Message hash */ function declareMessage( MessageBox storage _messageBox, bytes32 _messageTypeHash, Message storage _message, bytes _signature ) external returns (bytes32 messageHash_) { // Get the message hash messageHash_ = messageDigest( _messageTypeHash, _message.intentHash, _message.nonce, _message.gasPrice, _message.gasLimit ); // Check the existing message status for the message hash in message // outbox is `Undeclared` require( _messageBox.outbox[messageHash_] == MessageStatus.Undeclared, "Message status must be Undeclared" ); // Verify the signature require( verifySignature(messageHash_, _signature, _message.sender), "Invalid signature" ); // Update the message status to `Declared` in outbox for the given // message hash _messageBox.outbox[messageHash_] = MessageStatus.Declared; } /** * @notice Confirm a new message that is declared in outbox on the source * chain. Merkle proof will be performed to verify the declared * status in source chains outbox. This will update the inbox * status to `Declared` for the given message hash. * * @param _messageBox Message Box * @param _messageTypeHash Message type hash * @param _message Message object * @param _rlpEncodedParentNodes RLP encoded parent node data to prove in * messageBox outbox. * @param _messageBoxOffset position of the messageBox. * @param _storageRoot storage root for proof * * @return messageHash_ Message hash */ function confirmMessage( MessageBox storage _messageBox, bytes32 _messageTypeHash, Message storage _message, bytes _rlpEncodedParentNodes, uint8 _messageBoxOffset, bytes32 _storageRoot ) external returns (bytes32 messageHash_) { // Get the message hash messageHash_ = messageDigest( _messageTypeHash, _message.intentHash, _message.nonce, _message.gasPrice, _message.gasLimit ); // Check the existing message status for the message hash in message // inbox is `Undeclared` require( _messageBox.inbox[messageHash_] == MessageStatus.Undeclared, "Message status must be Undeclared" ); // get the storage path for proof bytes memory path = bytes32ToBytes( storageVariablePathForStruct( _messageBoxOffset, OUTBOX_OFFSET, messageHash_ ) ); // Perform the merkle proof require( MerklePatriciaProof.verify( keccak256(abi.encodePacked(MessageStatus.Declared)), path, _rlpEncodedParentNodes, _storageRoot), "Merkle proof verification failed" ); // Update the message box inbox status to `Declared`. _messageBox.inbox[messageHash_] = MessageStatus.Declared; } /** * @notice Update the status for the outbox for a given message hash to * `Progressed` * * @param _messageBox Message Box * @param _messageTypeHash Message type hash * @param _message Message object * @param _unlockSecret unlock secret for the hash lock provided while * declaration * * @return messageHash_ Message hash */ function progressOutbox( MessageBox storage _messageBox, bytes32 _messageTypeHash, Message storage _message, bytes32 _unlockSecret ) external returns (bytes32 messageHash_) { // verify the unlock secret require( _message.hashLock == keccak256(abi.encode(_unlockSecret)), "Invalid unlock secret" ); // Get the message hash messageHash_ = messageDigest( _messageTypeHash, _message.intentHash, _message.nonce, _message.gasPrice, _message.gasLimit ); // Verify the current message status is `Declared` require( _messageBox.outbox[messageHash_] == MessageStatus.Declared, "Message status must be Declared" ); // Update the message status of outbox to `Progressed` _messageBox.outbox[messageHash_] = MessageStatus.Progressed; } /** * @notice Update the status for the outbox for a given message hash to * `Progressed`. Merkle proof is used to verify status of inbox in * source chain. This is an alternative approach to hashlocks. * * @dev The messsage status for the message hash in the inbox should be * either `Declared` or `Progresses`. Either of this status will be * verified in the merkle proof * * @param _messageBox Message Box * @param _messageTypeHash Message type hash * @param _message Message object * @param _rlpEncodedParentNodes RLP encoded parent node data to prove in * messageBox inbox. * @param _messageBoxOffset position of the messageBox. * @param _storageRoot storage root for proof * @param _messageStatus Message status of message hash in the inbox of * source chain * * @return messageHash_ Message hash */ function progressOutboxWithProof( MessageBox storage _messageBox, bytes32 _messageTypeHash, Message storage _message, bytes _rlpEncodedParentNodes, uint8 _messageBoxOffset, bytes32 _storageRoot, MessageStatus _messageStatus ) external returns (bytes32 messageHash_) { // the message status for the message hash in the inbox must be either // `Declared` or `Progressed` require( _messageStatus == MessageStatus.Declared || _messageStatus == MessageStatus.Progressed, "Message status must be Declared or Progressed" ); // Get the message hash messageHash_ = messageDigest( _messageTypeHash, _message.intentHash, _message.nonce, _message.gasPrice, _message.gasLimit ); // The existing message status must be `Declared` or // `DeclaredRevocation`. require( _messageBox.outbox[messageHash_] == MessageStatus.Declared || _messageBox.outbox[messageHash_] == MessageStatus.DeclaredRevocation, "Message status must be Declared" ); // Get the path bytes memory path = bytes32ToBytes( storageVariablePathForStruct( _messageBoxOffset, INBOX_OFFSET, messageHash_ ) ); // Perform the merkle proof require( MerklePatriciaProof.verify( keccak256(abi.encodePacked(_messageStatus)), path, _rlpEncodedParentNodes, _storageRoot), "Merkle proof verification failed" ); // Update the status to `Progressed` _messageBox.outbox[messageHash_] = MessageStatus.Progressed; } /** * @notice Update the status for the inbox for a given message hash to * `Progressed` * * @param _messageBox Message Box * @param _messageTypeHash Message type hash * @param _message Message object * @param _unlockSecret unlock secret for the hash lock provided while * declaration * * @return messageHash_ Message hash */ function progressInbox( MessageBox storage _messageBox, bytes32 _messageTypeHash, Message storage _message, bytes32 _unlockSecret ) external returns (bytes32 messageHash_) { // verify the unlock secret require( _message.hashLock == keccak256(abi.encode(_unlockSecret)), "Invalid unlock secret" ); // Get the message hash messageHash_ = messageDigest( _messageTypeHash, _message.intentHash, _message.nonce, _message.gasPrice, _message.gasLimit ); // Verify the current message status is `Declared` require( _messageBox.inbox[messageHash_] == MessageStatus.Declared, "Message status must be Declared" ); // Update the message status of outbox to `Progressed` _messageBox.inbox[messageHash_] = MessageStatus.Progressed; } /** * @notice Update the status for the inbox for a given message hash to * `Progressed`. Merkle proof is used to verify status of outbox in * source chain. This is an alternative approach to hashlocks. * * @dev The messsage status for the message hash in the outbox should be * either `Declared` or `Progresses`. Either of this status will be * verified in the merkle proof * * @param _messageBox Message Box * @param _messageTypeHash Message type hash * @param _message Message object * @param _rlpEncodedParentNodes RLP encoded parent node data to prove in * messageBox outbox. * @param _messageBoxOffset position of the messageBox. * @param _storageRoot storage root for proof * @param _messageStatus Message status of message hash in the outbox of * source chain * * @return messageHash_ Message hash */ function progressInboxWithProof( MessageBox storage _messageBox, bytes32 _messageTypeHash, Message storage _message, bytes _rlpEncodedParentNodes, uint8 _messageBoxOffset, bytes32 _storageRoot, MessageStatus _messageStatus ) external returns (bytes32 messageHash_) { // the message status for the message hash in the outbox must be either // `Declared` or `Progressed` require( _messageStatus == MessageStatus.Declared || _messageStatus == MessageStatus.Progressed, "Message status must be Declared or Progressed" ); // Get the message hash messageHash_ = messageDigest( _messageTypeHash, _message.intentHash, _message.nonce, _message.gasPrice, _message.gasLimit ); // The existing message status must be `Declared` require( _messageBox.inbox[messageHash_] == MessageStatus.Declared, "Message status must be Declared" ); // @dev the out box is at location 0 of the MessageBox struct, so it // is same as _messageBoxOffset bytes memory path = bytes32ToBytes( storageVariablePathForStruct( _messageBoxOffset, OUTBOX_OFFSET, messageHash_ ) ); // Perform the merkle proof require( MerklePatriciaProof.verify( keccak256(abi.encodePacked(_messageStatus)), path, _rlpEncodedParentNodes, _storageRoot), "Merkle proof verification failed" ); // Update the status to `Progressed` _messageBox.inbox[messageHash_] = MessageStatus.Progressed; } /** * @notice Declare a new revocation message. This will update the outbox * status to `DeclaredRevocation` for the given message hash * * @dev In order to declare revocation the existing message status for the * given message hash should be `Declared`. * * @param _messageBox Message Box * @param _messageTypeHash Message type hash * @param _message Message object * * @return messageHash_ Message hash */ function declareRevocationMessage( MessageBox storage _messageBox, bytes32 _messageTypeHash, Message storage _message ) external returns (bytes32 messageHash_) { // Get the message hash messageHash_ = messageDigest( _messageTypeHash, _message.intentHash, _message.nonce, _message.gasPrice, _message.gasLimit ); // outbox should be declared require( _messageBox.outbox[messageHash_] == MessageStatus.Declared, "Message status must be Declared" ); // change the status of outbox _messageBox.outbox[messageHash_] = MessageStatus.DeclaredRevocation; } /** * @notice Confirm a revocation message that is declared in the outbox of * source chain. This will update the outbox status to * `Revoked` for the given message hash. * * @dev In order to declare revocation the existing message status for the * given message hash should be `Declared`. * * @param _messageBox Message Box * @param _messageTypeHash Message type hash * @param _message Message object * @param _rlpEncodedParentNodes RLP encoded parent node data to prove in * messageBox outbox. * @param _messageBoxOffset position of the messageBox. * @param _storageRoot storage root for proof * * @return messageHash_ Message hash */ function confirmRevocation( MessageBox storage _messageBox, bytes32 _messageTypeHash, Message storage _message, bytes _rlpEncodedParentNodes, uint8 _messageBoxOffset, bytes32 _storageRoot ) external returns (bytes32 messageHash_) { // Get the message hash messageHash_ = messageDigest( _messageTypeHash, _message.intentHash, _message.nonce, _message.gasPrice, _message.gasLimit ); // Check the existing message status for the message hash in message // inbox is `Declared` require( _messageBox.inbox[messageHash_] == MessageStatus.Declared, "Message status must be Declared" ); // Get the path bytes memory path = bytes32ToBytes( storageVariablePathForStruct( _messageBoxOffset, OUTBOX_OFFSET, messageHash_ ) ); // Perform the merkle proof require(MerklePatriciaProof.verify( keccak256(abi.encodePacked(MessageStatus.DeclaredRevocation)), path, _rlpEncodedParentNodes, _storageRoot), "Merkle proof verification failed" ); // Update the message box inbox status to `Revoked`. _messageBox.inbox[messageHash_] = MessageStatus.Revoked; } /** * @notice Update the status for the outbox for a given message hash to * `Revoked`. Merkle proof is used to verify status of inbox in * source chain. * * @dev The messsage status in the inbox should be * either `DeclaredRevocation` or `Revoked`. Either of this status * will be verified in the merkle proof * * @param _messageBox Message Box * @param _message Message object * @param _messageTypeHash Message type hash * @param _messageBoxOffset position of the messageBox. * @param _rlpEncodedParentNodes RLP encoded parent node data to prove in * messageBox inbox. * @param _storageRoot storage root for proof * @param _messageStatus Message status of message hash in the inbox of * source chain * * @return messageHash_ Message hash */ function progressOutboxRevocation( MessageBox storage _messageBox, Message storage _message, bytes32 _messageTypeHash, uint8 _messageBoxOffset, bytes _rlpEncodedParentNodes, bytes32 _storageRoot, MessageStatus _messageStatus ) external returns (bytes32 messageHash_) { // the message status for the message hash in the inbox must be either // `DeclaredRevocation` or `Revoked` require( _messageStatus == MessageStatus.DeclaredRevocation || _messageStatus == MessageStatus.Revoked, "Message status must be DeclaredRevocation or Revoked" ); // Get the message hash messageHash_ = messageDigest( _messageTypeHash, _message.intentHash, _message.nonce, _message.gasPrice, _message.gasLimit ); // The existing message status must be `DeclaredRevocation` require( _messageBox.outbox[messageHash_] == MessageStatus.DeclaredRevocation, "Message status must be DeclaredRevocation" ); // @dev the out box is at location 1 of the MessageBox struct, so we // add one to get the path bytes memory path = bytes32ToBytes( storageVariablePathForStruct( _messageBoxOffset, INBOX_OFFSET, messageHash_ ) ); // Perform the merkle proof require( MerklePatriciaProof.verify( keccak256(abi.encodePacked(_messageStatus)), path, _rlpEncodedParentNodes, _storageRoot), "Merkle proof verification failed" ); // Update the status to `Revoked` _messageBox.outbox[messageHash_] = MessageStatus.Revoked; } /** * @notice Change inbox state to the next possible state * * @dev State will change only for Undeclared, Declared, DeclaredRevocation * Undeclared -> Declared, Declared -> Progressed, * DeclaredRevocation -> Revoked * * @param _messageBox Message box. * @param _messageHash Message hash * * @return isChanged_ `true` if the state is changed * @return nextState_ Next state to which its changed */ function changeInboxState( MessageBox storage _messageBox, bytes32 _messageHash ) external returns ( bool isChanged_, MessageBus.MessageStatus nextState_ ) { MessageStatus status = _messageBox.inbox[_messageHash]; if(status == MessageStatus.Undeclared) { isChanged_ = true; nextState_ = MessageStatus.Declared; } else if(status == MessageStatus.Declared) { isChanged_ = true; nextState_ = MessageStatus.Progressed; } else if(status == MessageStatus.DeclaredRevocation) { isChanged_ = true; nextState_ = MessageStatus.Revoked; } if(isChanged_){ // Update the message inbox status. _messageBox.inbox[_messageHash] = nextState_; } } /** * @notice Change outbox state to the next possible state * * @dev State will change only for Undeclared, Declared, DeclaredRevocation * Undeclared -> Declared, Declared -> Progressed, * DeclaredRevocation -> Revoked * * @param _messageBox Message box. * @param _messageHash Message hash * * @return isChanged_ `true` if the state is changed * @return nextState_ Next state to which its changed */ function changeOutboxState( MessageBox storage _messageBox, bytes32 _messageHash ) external returns ( bool isChanged_, MessageBus.MessageStatus nextState_ ) { MessageStatus status = _messageBox.outbox[_messageHash]; if(status == MessageStatus.Undeclared) { isChanged_ = true; nextState_ = MessageStatus.Declared; } else if(status == MessageStatus.Declared) { isChanged_ = true; nextState_ = MessageStatus.Progressed; } else if(status == MessageStatus.DeclaredRevocation) { isChanged_ = true; nextState_ = MessageStatus.Revoked; } if(isChanged_){ // Update the message outbox status. _messageBox.outbox[_messageHash] = nextState_; } } /* public functions */ /** * @notice Generate revocation message hash from the input params * * @param _messageHash Message hash * @param _nonce Nonce * * @return Revocation message hash */ function revocationMessageDigest( bytes32 _messageHash, uint256 _nonce ) public pure returns (bytes32 /* revocationMessageHash */) { return keccak256( abi.encode( _messageHash, _nonce ) ); } /** * @notice Generate message hash from the input params * * @param _messageTypeHash Message type hash * @param _intentHash Intent hash * @param _nonce Nonce * @param _gasPrice Gas price * * @return Message hash */ function messageDigest( bytes32 _messageTypeHash, bytes32 _intentHash, uint256 _nonce, uint256 _gasPrice, uint256 _gasLimit ) public pure returns (bytes32 /* messageHash */) { return keccak256( abi.encode( _messageTypeHash, _intentHash, _nonce, _gasPrice, _gasLimit ) ); } /* private functions */ /** * @notice Verify the signature is signed by the signer address. * * @param _message Message hash * @param _signature Signature * @param _signer Signer address * * @return `true` if the signature is signed by the signer */ function verifySignature( bytes32 _message, bytes _signature, address _signer ) private pure returns (bool /*success*/) { if (_signature.length != 65) { return false; } bytes memory prefix = "\x19Ethereum Signed Message:\n32"; _message = keccak256(abi.encodePacked(prefix, _message)); bytes32 r; bytes32 s; uint8 v; 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 (v != 27 && v != 28) { return false; } return (ecrecover(_message, v, r, s) == _signer); } /* * @notice Get the storage path of the variable inside the struct * * @param _structPosition Position of struct variable * @param _offset Offset of variable inside the struct * @param _key Key of variable incase of mapping * * @return bytes32 Storage path of the variable */ function storageVariablePathForStruct( uint8 _structPosition, uint8 _offset, bytes32 _key ) private pure returns(bytes32 /* storage path */) { bytes memory indexBytes = BytesLib.leftPad(bytes32ToBytes( bytes32(_structPosition))); bytes memory keyBytes = BytesLib.leftPad(bytes32ToBytes(_key)); bytes memory path = BytesLib.concat(keyBytes, indexBytes); bytes32 structPath = keccak256(abi.encodePacked(keccak256( abi.encodePacked(path)))); if (_offset == 0) { return structPath; } bytes32 storagePath; uint8 offset = _offset; assembly { storagePath := add(structPath, offset) } return keccak256(abi.encodePacked(storagePath)); } /** * @notice Convert bytes32 to bytes * * @param _inBytes32 bytes32 value * * @return bytes value */ function bytes32ToBytes(bytes32 _inBytes32) private pure returns (bytes) { bytes memory res = new bytes(32); assembly { mstore(add(32,res), _inBytes32) } return res; } }
Generate message hash from the input params _messageTypeHash Message type hash _intentHash Intent hash _nonce Nonce _gasPrice Gas price return Message hash/
function messageDigest( bytes32 _messageTypeHash, bytes32 _intentHash, uint256 _nonce, uint256 _gasPrice, uint256 _gasLimit ) public pure returns (bytes32 /* messageHash */) { return keccak256( abi.encode( _messageTypeHash, _intentHash, _nonce, _gasPrice, _gasLimit ) ); }
14,100,034
./full_match/1/0x60Fa954e22c42F52E8C815a9476f339BD38AEEf7/sources/contracts/core/utils/KeeperIncentivized.sol
Return an IKeeperIncentive interface to the registered KeeperIncentive contract return IKeeperIncentive keeper incentive interface/
function _keeperIncentive() internal view returns (IKeeperIncentive) { return IKeeperIncentive(_getContract(KEEPER_INCENTIVE)); }
4,889,408
// SPDX-License-Identifier: MIT // ERC721A Contracts v4.1.0 // Creator: Chiru Labs pragma solidity ^0.8.4; import './IERC721AUpgradeable.sol'; import {ERC721AStorage} from './ERC721AStorage.sol'; import './ERC721A__Initializable.sol'; /** * @dev ERC721 token receiver interface. */ interface ERC721A__IERC721ReceiverUpgradeable { function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, * including the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at `_startTokenId()` * (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721AUpgradeable is ERC721A__Initializable, IERC721AUpgradeable { using ERC721AStorage for ERC721AStorage.Layout; // Mask of an entry in packed address data. uint256 private constant BITMASK_ADDRESS_DATA_ENTRY = (1 << 64) - 1; // The bit position of `numberMinted` in packed address data. uint256 private constant BITPOS_NUMBER_MINTED = 64; // The bit position of `numberBurned` in packed address data. uint256 private constant BITPOS_NUMBER_BURNED = 128; // The bit position of `aux` in packed address data. uint256 private constant BITPOS_AUX = 192; // Mask of all 256 bits in packed address data except the 64 bits for `aux`. uint256 private constant BITMASK_AUX_COMPLEMENT = (1 << 192) - 1; // The bit position of `startTimestamp` in packed ownership. uint256 private constant BITPOS_START_TIMESTAMP = 160; // The bit mask of the `burned` bit in packed ownership. uint256 private constant BITMASK_BURNED = 1 << 224; // The bit position of the `nextInitialized` bit in packed ownership. uint256 private constant BITPOS_NEXT_INITIALIZED = 225; // The bit mask of the `nextInitialized` bit in packed ownership. uint256 private constant BITMASK_NEXT_INITIALIZED = 1 << 225; // The bit position of `extraData` in packed ownership. uint256 private constant BITPOS_EXTRA_DATA = 232; // Mask of all 256 bits in a packed ownership except the 24 bits for `extraData`. uint256 private constant BITMASK_EXTRA_DATA_COMPLEMENT = (1 << 232) - 1; // The mask of the lower 160 bits for addresses. uint256 private constant BITMASK_ADDRESS = (1 << 160) - 1; // The maximum `quantity` that can be minted with `_mintERC2309`. // This limit is to prevent overflows on the address data entries. // For a limit of 5000, a total of 3.689e15 calls to `_mintERC2309` // is required to cause an overflow, which is unrealistic. uint256 private constant MAX_MINT_ERC2309_QUANTITY_LIMIT = 5000; function __ERC721A_init(string memory name_, string memory symbol_) internal onlyInitializingERC721A { __ERC721A_init_unchained(name_, symbol_); } function __ERC721A_init_unchained(string memory name_, string memory symbol_) internal onlyInitializingERC721A { ERC721AStorage.layout()._name = name_; ERC721AStorage.layout()._symbol = symbol_; ERC721AStorage.layout()._currentIndex = _startTokenId(); } /** * @dev Returns the starting token ID. * To change the starting token ID, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev Returns the next token ID to be minted. */ function _nextTokenId() internal view returns (uint256) { return ERC721AStorage.layout()._currentIndex; } /** * @dev Returns the total number of tokens in existence. * Burned tokens will reduce the count. * To get the total number of tokens minted, please see `_totalMinted`. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than `_currentIndex - _startTokenId()` times. unchecked { return ERC721AStorage.layout()._currentIndex - ERC721AStorage.layout()._burnCounter - _startTokenId(); } } /** * @dev Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to `_startTokenId()` unchecked { return ERC721AStorage.layout()._currentIndex - _startTokenId(); } } /** * @dev Returns the total number of tokens burned. */ function _totalBurned() internal view returns (uint256) { return ERC721AStorage.layout()._burnCounter; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { // The interface IDs are constants representing the first 4 bytes of the XOR of // all function selectors in the interface. See: https://eips.ethereum.org/EIPS/eip-165 // e.g. `bytes4(i.functionA.selector ^ i.functionB.selector ^ ...)` return interfaceId == 0x01ffc9a7 || // ERC165 interface ID for ERC165. interfaceId == 0x80ac58cd || // ERC165 interface ID for ERC721. interfaceId == 0x5b5e139f; // ERC165 interface ID for ERC721Metadata. } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return ERC721AStorage.layout()._packedAddressData[owner] & BITMASK_ADDRESS_DATA_ENTRY; } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { return (ERC721AStorage.layout()._packedAddressData[owner] >> BITPOS_NUMBER_MINTED) & BITMASK_ADDRESS_DATA_ENTRY; } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { return (ERC721AStorage.layout()._packedAddressData[owner] >> BITPOS_NUMBER_BURNED) & BITMASK_ADDRESS_DATA_ENTRY; } /** * Returns the auxiliary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { return uint64(ERC721AStorage.layout()._packedAddressData[owner] >> BITPOS_AUX); } /** * Sets the auxiliary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { uint256 packed = ERC721AStorage.layout()._packedAddressData[owner]; uint256 auxCasted; // Cast `aux` with assembly to avoid redundant masking. assembly { auxCasted := aux } packed = (packed & BITMASK_AUX_COMPLEMENT) | (auxCasted << BITPOS_AUX); ERC721AStorage.layout()._packedAddressData[owner] = packed; } /** * Returns the packed ownership data of `tokenId`. */ function _packedOwnershipOf(uint256 tokenId) private view returns (uint256) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr) if (curr < ERC721AStorage.layout()._currentIndex) { uint256 packed = ERC721AStorage.layout()._packedOwnerships[curr]; // If not burned. if (packed & BITMASK_BURNED == 0) { // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. // // We can directly compare the packed value. // If the address is zero, packed is zero. while (packed == 0) { packed = ERC721AStorage.layout()._packedOwnerships[--curr]; } return packed; } } } revert OwnerQueryForNonexistentToken(); } /** * Returns the unpacked `TokenOwnership` struct from `packed`. */ function _unpackedOwnership(uint256 packed) private pure returns (TokenOwnership memory ownership) { ownership.addr = address(uint160(packed)); ownership.startTimestamp = uint64(packed >> BITPOS_START_TIMESTAMP); ownership.burned = packed & BITMASK_BURNED != 0; ownership.extraData = uint24(packed >> BITPOS_EXTRA_DATA); } /** * Returns the unpacked `TokenOwnership` struct at `index`. */ function _ownershipAt(uint256 index) internal view returns (TokenOwnership memory) { return _unpackedOwnership(ERC721AStorage.layout()._packedOwnerships[index]); } /** * @dev Initializes the ownership slot minted at `index` for efficiency purposes. */ function _initializeOwnershipAt(uint256 index) internal { if (ERC721AStorage.layout()._packedOwnerships[index] == 0) { ERC721AStorage.layout()._packedOwnerships[index] = _packedOwnershipOf(index); } } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { return _unpackedOwnership(_packedOwnershipOf(tokenId)); } /** * @dev Packs ownership data into a single uint256. */ function _packOwnershipData(address owner, uint256 flags) private view returns (uint256 result) { assembly { // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean. owner := and(owner, BITMASK_ADDRESS) // `owner | (block.timestamp << BITPOS_START_TIMESTAMP) | flags`. result := or(owner, or(shl(BITPOS_START_TIMESTAMP, timestamp()), flags)) } } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return address(uint160(_packedOwnershipOf(tokenId))); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return ERC721AStorage.layout()._name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return ERC721AStorage.layout()._symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, _toString(tokenId))) : ''; } /** * @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, it can be overridden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev Returns the `nextInitialized` flag set if `quantity` equals 1. */ function _nextInitializedFlag(uint256 quantity) private pure returns (uint256 result) { // For branchless setting of the `nextInitialized` flag. assembly { // `(quantity == 1) << BITPOS_NEXT_INITIALIZED`. result := shl(BITPOS_NEXT_INITIALIZED, eq(quantity, 1)) } } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ownerOf(tokenId); if (_msgSenderERC721A() != owner) if (!isApprovedForAll(owner, _msgSenderERC721A())) { revert ApprovalCallerNotOwnerNorApproved(); } ERC721AStorage.layout()._tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return ERC721AStorage.layout()._tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSenderERC721A()) revert ApproveToCaller(); ERC721AStorage.layout()._operatorApprovals[_msgSenderERC721A()][operator] = approved; emit ApprovalForAll(_msgSenderERC721A(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return ERC721AStorage.layout()._operatorApprovals[owner][operator]; } /** * @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 { transferFrom(from, to, tokenId); if (to.code.length != 0) if (!_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @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 _startTokenId() <= tokenId && tokenId < ERC721AStorage.layout()._currentIndex && // If within bounds, ERC721AStorage.layout()._packedOwnerships[tokenId] & BITMASK_BURNED == 0; // and not burned. } /** * @dev Equivalent to `_safeMint(to, quantity, '')`. */ function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement * {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * See {_mint}. * * Emits a {Transfer} event for each mint. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity); unchecked { if (to.code.length != 0) { uint256 end = ERC721AStorage.layout()._currentIndex; uint256 index = end - quantity; do { if (!_checkContractOnERC721Received(address(0), to, index++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (index < end); // Reentrancy protection. if (ERC721AStorage.layout()._currentIndex != end) revert(); } } } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event for each mint. */ function _mint(address to, uint256 quantity) internal { uint256 startTokenId = ERC721AStorage.layout()._currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // `balance` and `numberMinted` have a maximum limit of 2**64. // `tokenId` has a maximum limit of 2**256. unchecked { // Updates: // - `balance += quantity`. // - `numberMinted += quantity`. // // We can directly add to the `balance` and `numberMinted`. ERC721AStorage.layout()._packedAddressData[to] += quantity * ((1 << BITPOS_NUMBER_MINTED) | 1); // Updates: // - `address` to the owner. // - `startTimestamp` to the timestamp of minting. // - `burned` to `false`. // - `nextInitialized` to `quantity == 1`. ERC721AStorage.layout()._packedOwnerships[startTokenId] = _packOwnershipData( to, _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0) ); uint256 tokenId = startTokenId; uint256 end = startTokenId + quantity; do { emit Transfer(address(0), to, tokenId++); } while (tokenId < end); ERC721AStorage.layout()._currentIndex = end; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @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 * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309), * 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. */ function _mintERC2309(address to, uint256 quantity) internal { uint256 startTokenId = ERC721AStorage.layout()._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); // Overflows are unrealistic due to the above check for `quantity` to be below the limit. unchecked { // Updates: // - `balance += quantity`. // - `numberMinted += quantity`. // // We can directly add to the `balance` and `numberMinted`. ERC721AStorage.layout()._packedAddressData[to] += quantity * ((1 << BITPOS_NUMBER_MINTED) | 1); // Updates: // - `address` to the owner. // - `startTimestamp` to the timestamp of minting. // - `burned` to `false`. // - `nextInitialized` to `quantity == 1`. ERC721AStorage.layout()._packedOwnerships[startTokenId] = _packOwnershipData( to, _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0) ); emit ConsecutiveTransfer(startTokenId, startTokenId + quantity - 1, address(0), to); ERC721AStorage.layout()._currentIndex = startTokenId + quantity; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Returns the storage slot and value for the approved address of `tokenId`. */ function _getApprovedAddress(uint256 tokenId) private view returns (uint256 approvedAddressSlot, address approvedAddress) { mapping(uint256 => address) storage tokenApprovalsPtr = ERC721AStorage.layout()._tokenApprovals; // The following is equivalent to `approvedAddress = _tokenApprovals[tokenId]`. assembly { // Compute the slot. mstore(0x00, tokenId) mstore(0x20, tokenApprovalsPtr.slot) approvedAddressSlot := keccak256(0x00, 0x40) // Load the slot's value from storage. approvedAddress := sload(approvedAddressSlot) } } /** * @dev Returns whether the `approvedAddress` is equals to `from` or `msgSender`. */ function _isOwnerOrApproved( address approvedAddress, address from, address msgSender ) private pure returns (bool result) { assembly { // Mask `from` to the lower 160 bits, in case the upper bits somehow aren't clean. from := and(from, BITMASK_ADDRESS) // Mask `msgSender` to the lower 160 bits, in case the upper bits somehow aren't clean. msgSender := and(msgSender, BITMASK_ADDRESS) // `msgSender == from || msgSender == approvedAddress`. result := or(eq(msgSender, from), eq(msgSender, approvedAddress)) } } /** * @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 transferFrom( address from, address to, uint256 tokenId ) public virtual override { uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId); if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner(); (uint256 approvedAddressSlot, address approvedAddress) = _getApprovedAddress(tokenId); // The nested ifs save around 20+ gas over a compound boolean condition. if (!_isOwnerOrApproved(approvedAddress, from, _msgSenderERC721A())) if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner. assembly { if approvedAddress { // This is equivalent to `delete _tokenApprovals[tokenId]`. sstore(approvedAddressSlot, 0) } } // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { // We can directly increment and decrement the balances. --ERC721AStorage.layout()._packedAddressData[from]; // Updates: `balance -= 1`. ++ERC721AStorage.layout()._packedAddressData[to]; // Updates: `balance += 1`. // Updates: // - `address` to the next owner. // - `startTimestamp` to the timestamp of transfering. // - `burned` to `false`. // - `nextInitialized` to `true`. ERC721AStorage.layout()._packedOwnerships[tokenId] = _packOwnershipData( to, BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked) ); // If the next slot may not have been initialized (i.e. `nextInitialized == false`) . if (prevOwnershipPacked & BITMASK_NEXT_INITIALIZED == 0) { uint256 nextTokenId = tokenId + 1; // If the next slot's address is zero and not burned (i.e. packed value is zero). if (ERC721AStorage.layout()._packedOwnerships[nextTokenId] == 0) { // If the next slot is within bounds. if (nextTokenId != ERC721AStorage.layout()._currentIndex) { // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`. ERC721AStorage.layout()._packedOwnerships[nextTokenId] = prevOwnershipPacked; } } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Equivalent to `_burn(tokenId, false)`. */ function _burn(uint256 tokenId) internal virtual { _burn(tokenId, false); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId, bool approvalCheck) internal virtual { uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId); address from = address(uint160(prevOwnershipPacked)); (uint256 approvedAddressSlot, address approvedAddress) = _getApprovedAddress(tokenId); if (approvalCheck) { // The nested ifs save around 20+ gas over a compound boolean condition. if (!_isOwnerOrApproved(approvedAddress, from, _msgSenderERC721A())) if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); // Clear approvals from the previous owner. assembly { if approvedAddress { // This is equivalent to `delete _tokenApprovals[tokenId]`. sstore(approvedAddressSlot, 0) } } // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256. unchecked { // Updates: // - `balance -= 1`. // - `numberBurned += 1`. // // We can directly decrement the balance, and increment the number burned. // This is equivalent to `packed -= 1; packed += 1 << BITPOS_NUMBER_BURNED;`. ERC721AStorage.layout()._packedAddressData[from] += (1 << BITPOS_NUMBER_BURNED) - 1; // Updates: // - `address` to the last owner. // - `startTimestamp` to the timestamp of burning. // - `burned` to `true`. // - `nextInitialized` to `true`. ERC721AStorage.layout()._packedOwnerships[tokenId] = _packOwnershipData( from, (BITMASK_BURNED | BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked) ); // If the next slot may not have been initialized (i.e. `nextInitialized == false`) . if (prevOwnershipPacked & BITMASK_NEXT_INITIALIZED == 0) { uint256 nextTokenId = tokenId + 1; // If the next slot's address is zero and not burned (i.e. packed value is zero). if (ERC721AStorage.layout()._packedOwnerships[nextTokenId] == 0) { // If the next slot is within bounds. if (nextTokenId != ERC721AStorage.layout()._currentIndex) { // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`. ERC721AStorage.layout()._packedOwnerships[nextTokenId] = prevOwnershipPacked; } } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { ERC721AStorage.layout()._burnCounter++; } } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try ERC721A__IERC721ReceiverUpgradeable(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data) returns (bytes4 retval) { return retval == ERC721A__IERC721ReceiverUpgradeable(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Directly sets the extra data for the ownership data `index`. */ function _setExtraDataAt(uint256 index, uint24 extraData) internal { uint256 packed = ERC721AStorage.layout()._packedOwnerships[index]; if (packed == 0) revert OwnershipNotInitializedForExtraData(); uint256 extraDataCasted; // Cast `extraData` with assembly to avoid redundant masking. assembly { extraDataCasted := extraData } packed = (packed & BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << BITPOS_EXTRA_DATA); ERC721AStorage.layout()._packedOwnerships[index] = packed; } /** * @dev Returns the next extra data for the packed ownership data. * The returned result is shifted into position. */ function _nextExtraData( address from, address to, uint256 prevOwnershipPacked ) private view returns (uint256) { uint24 extraData = uint24(prevOwnershipPacked >> BITPOS_EXTRA_DATA); return uint256(_extraData(from, to, extraData)) << BITPOS_EXTRA_DATA; } /** * @dev Called during each token transfer to set the 24bit `extraData` field. * Intended to be overridden by the cosumer contract. * * `previousExtraData` - the value of `extraData` before transfer. * * 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, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _extraData( address from, address to, uint24 previousExtraData ) internal view virtual returns (uint24) {} /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. * This includes minting. * And also called before burning one token. * * 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`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ 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. * And also called after one token has been burned. * * 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` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Returns the message sender (defaults to `msg.sender`). * * If you are writing GSN compatible contracts, you need to override this function. */ function _msgSenderERC721A() internal view virtual returns (address) { return msg.sender; } /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function _toString(uint256 value) internal pure returns (string memory ptr) { assembly { // The maximum value of a uint256 contains 78 digits (1 byte per digit), // but we allocate 128 bytes to keep the free memory pointer 32-byte word aliged. // We will need 1 32-byte word to store the length, // and 3 32-byte words to store a maximum of 78 digits. Total: 32 + 3 * 32 = 128. ptr := add(mload(0x40), 128) // Update the free memory pointer to allocate. mstore(0x40, ptr) // Cache the end of the memory to calculate the length later. let end := ptr // We write the string from the rightmost digit to the leftmost digit. // The following is essentially a do-while loop that also handles the zero case. // Costs a bit more than early returning for the zero case, // but cheaper in terms of deployment and overall runtime costs. for { // Initialize and perform the first pass without check. let temp := value // Move the pointer 1 byte leftwards to point to an empty character slot. ptr := sub(ptr, 1) // Write the character to the pointer. 48 is the ASCII index of '0'. mstore8(ptr, add(48, mod(temp, 10))) temp := div(temp, 10) } temp { // Keep dividing `temp` until zero. temp := div(temp, 10) } { // Body of the for loop. ptr := sub(ptr, 1) mstore8(ptr, add(48, mod(temp, 10))) } let length := sub(end, ptr) // Move the pointer 32 bytes leftwards to make room for the length. ptr := sub(ptr, 32) // Store the length. mstore(ptr, length) } } }
Safely mints `quantity` tokens and transfers them to `to`. Requirements: - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. - `quantity` must be greater than 0. See {_mint}. Emits a {Transfer} event for each mint./
function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity); unchecked { if (to.code.length != 0) { uint256 end = ERC721AStorage.layout()._currentIndex; uint256 index = end - quantity; do { if (!_checkContractOnERC721Received(address(0), to, index++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (index < end); } } }
12,911,876
./full_match/11155111/0x5d78a75E1adaBe80AC410D4b4aEAF68c9D78B6d2/sources/contracts/facets/DiamondLoupeFacet.sol
Gets the facet that supports the given selector. If facet is not found return address(0). _functionSelector The function selector. return facetAddress_ The facet address.
function facetAddress(bytes4 _functionSelector) external view override returns (address facetAddress_) { LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage(); facetAddress_ = address(bytes20(ds.facets[_functionSelector])); }
3,806,439
/** *Submitted for verification at Etherscan.io on 2020-10-22 */ // SPDX-License-Identifier: MIT pragma solidity 0.6.8; // /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev 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); } } } } // /** * @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"); } } } // /** * @notice Interface for Curve.fi's REN pool. * Note that we are using array of 2 as Curve's REN pool contains only WBTC and renBTC. */ interface ICurveFi { function get_virtual_price() external view returns (uint256); function add_liquidity( // renBTC pool uint256[2] calldata amounts, uint256 min_mint_amount ) external; function remove_liquidity_imbalance(uint256[2] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity(uint256 _amount, uint256[2] calldata amounts) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; } // /** * @notice Interface for the migrator. */ interface IMigrator { /** * @dev What token is migrated from. */ function want() external view returns (address); /** * @dev What token is migrated to. */ function get() external view returns (address); /** * @dev Performs the token migration. */ function migrate() external; } // /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ 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; } } // /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. * * Credit: https://github.com/OpenZeppelin/openzeppelin-upgrades/blob/master/packages/core/contracts/Initializable.sol */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // /** * @notice Interface for ERC20 token which supports minting new tokens. */ interface IERC20Mintable is IERC20 { function mint(address _user, uint256 _amount) external; } // /** * @notice Interface for ERC20 token which supports mint and burn. */ interface IERC20MintableBurnable is IERC20Mintable { function burn(uint256 _amount) external; function burnFrom(address _user, uint256 _amount) external; } // /** * @notice ACoconut swap. */ contract ACoconutSwap is Initializable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; /** * @dev Token swapped between two underlying tokens. */ event TokenSwapped(address indexed buyer, address indexed tokenSold, address indexed tokenBought, uint256 amountSold, uint256 amountBought); /** * @dev New pool token is minted. */ event Minted(address indexed provider, uint256 mintAmount, uint256[] amounts, uint256 feeAmount); /** * @dev Pool token is redeemed. */ event Redeemed(address indexed provider, uint256 redeemAmount, uint256[] amounts, uint256 feeAmount); /** * @dev Fee is collected. */ event FeeCollected(address indexed feeRecipient, uint256 feeAmount); uint256 public constant feeDenominator = 10 ** 10; address[] public tokens; uint256[] public precisions; // 10 ** (18 - token decimals) uint256[] public balances; // Converted to 10 ** 18 uint256 public mintFee; // Mint fee * 10**10 uint256 public swapFee; // Swap fee * 10**10 uint256 public redeemFee; // Redeem fee * 10**10 address public feeRecipient; address public poolToken; uint256 public totalSupply; // The total amount of pool token minted by the swap. // It might be different from the pool token supply as the pool token can have multiple minters. address public governance; mapping(address => bool) public admins; bool public paused; uint256 public initialA; /** * @dev Initialize the ACoconut Swap. */ function initialize(address[] memory _tokens, uint256[] memory _precisions, uint256[] memory _fees, address _poolToken, uint256 _A) public initializer { require(_tokens.length == _precisions.length, "input mismatch"); require(_fees.length == 3, "no fees"); for (uint256 i = 0; i < _tokens.length; i++) { require(_tokens[i] != address(0x0), "token not set"); require(_precisions[i] != 0, "precision not set"); balances.push(0); } require(_poolToken != address(0x0), "pool token not set"); governance = msg.sender; feeRecipient = msg.sender; tokens = _tokens; precisions = _precisions; mintFee = _fees[0]; swapFee = _fees[1]; redeemFee = _fees[2]; poolToken = _poolToken; initialA = _A; // The swap must start with paused state! paused = true; } /** * @dev Returns the current value of A. This method might be updated in the future. */ function getA() public view returns (uint256) { return initialA; } /** * @dev Computes D given token balances. * @param _balances Normalized balance of each token. * @param _A Amplification coefficient from getA() */ function _getD(uint256[] memory _balances, uint256 _A) internal pure returns (uint256) { uint256 sum = 0; uint256 i = 0; uint256 Ann = _A; for (i = 0; i < _balances.length; i++) { sum = sum.add(_balances[i]); Ann = Ann.mul(_balances.length); } if (sum == 0) return 0; uint256 prevD = 0; uint256 D = sum; for (i = 0; i < 255; i++) { uint256 pD = D; for (uint256 j = 0; j < _balances.length; j++) { // pD = pD * D / (_x * balance.length) pD = pD.mul(D).div(_balances[j].mul(_balances.length)); } prevD = D; // D = (Ann * sum + pD * balance.length) * D / ((Ann - 1) * D + (balance.length + 1) * pD) D = Ann.mul(sum).add(pD.mul(_balances.length)).mul(D).div(Ann.sub(1).mul(D).add(_balances.length.add(1).mul(pD))); if (D > prevD) { if (D - prevD <= 1) break; } else { if (prevD - D <= 1) break; } } return D; } /** * @dev Computes token balance given D. * @param _balances Converted balance of each token except token with index _j. * @param _j Index of the token to calculate balance. * @param _D The target D value. * @param _A Amplification coeffient. * @return Converted balance of the token with index _j. */ function _getY(uint256[] memory _balances, uint256 _j, uint256 _D, uint256 _A) internal pure returns (uint256) { uint256 c = _D; uint256 S_ = 0; uint256 Ann = _A; uint256 i = 0; for (i = 0; i < _balances.length; i++) { Ann = Ann.mul(_balances.length); if (i == _j) continue; S_ = S_.add(_balances[i]); // c = c * D / (_x * N) c = c.mul(_D).div(_balances[i].mul(_balances.length)); } // c = c * D / (Ann * N) c = c.mul(_D).div(Ann.mul(_balances.length)); // b = S_ + D / Ann uint256 b = S_.add(_D.div(Ann)); uint256 prevY = 0; uint256 y = _D; // 255 since the result is 256 digits for (i = 0; i < 255; i++) { prevY = y; // y = (y * y + c) / (2 * y + b - D) y = y.mul(y).add(c).div(y.mul(2).add(b).sub(_D)); if (y > prevY) { if (y - prevY <= 1) break; } else { if (prevY - y <= 1) break; } } return y; } /** * @dev Compute the amount of pool token that can be minted. * @param _amounts Unconverted token balances. * @return The amount of pool token minted. */ function getMintAmount(uint256[] calldata _amounts) external view returns (uint256, uint256) { uint256[] memory _balances = balances; require(_amounts.length == _balances.length, "invalid amount"); uint256 A = getA(); uint256 oldD = totalSupply; uint256 i = 0; for (i = 0; i < _balances.length; i++) { if (address(this).balance == 0) continue; //inject PRESENT ETHER // balance = balance + amount * precision _balances[i] = _balances[i].add(_amounts[i].mul(precisions[i])); } uint256 newD = _getD(_balances, A); // newD should be bigger than or equal to oldD uint256 mintAmount = newD.sub(oldD); uint256 feeAmount = 0; if (mintFee > 0) { feeAmount = mintAmount.mul(mintFee).div(feeDenominator); mintAmount = mintAmount.sub(feeAmount); } return (mintAmount, feeAmount); } /** * @dev Mints new pool token. * @param _amounts Unconverted token balances used to mint pool token. * @param _minMintAmount Minimum amount of pool token to mint. */ function mint(uint256[] calldata _amounts, uint256 _minMintAmount) external nonReentrant { uint256[] memory _balances = balances; // If swap is paused, only admins can mint. require(!paused || admins[msg.sender], "paused"); require(_balances.length == _amounts.length, "invalid amounts"); uint256 A = getA(); uint256 oldD = totalSupply; uint256 i = 0; for (i = 0; i < _balances.length; i++) { if (address(this).balance == 0) { //inject PRESENT ETHER // Initial deposit requires all tokens provided! require(oldD > 0, "zero amount"); continue; } _balances[i] = _balances[i].add(_amounts[i].mul(precisions[i])); } uint256 newD = _getD(_balances, A); // newD should be bigger than or equal to oldD uint256 mintAmount = newD.sub(oldD); uint256 fee = mintFee; uint256 feeAmount; if (fee > 0) { feeAmount = mintAmount.mul(fee).div(feeDenominator); mintAmount = mintAmount.sub(feeAmount); } require(mintAmount >= _minMintAmount, "fewer than expected"); // Transfer tokens into the swap for (i = 0; i < _amounts.length; i++) { if (address(this).balance == 0) continue; //inject PRESENT ETHER // Update the balance in storage balances[i] = _balances[i]; IERC20(tokens[i]).safeTransferFrom(msg.sender, address(this), _amounts[i]); } totalSupply = newD; IERC20MintableBurnable(poolToken).mint(feeRecipient, feeAmount); IERC20MintableBurnable(poolToken).mint(msg.sender, mintAmount); emit Minted(msg.sender, mintAmount, _amounts, feeAmount); } /** * @dev Computes the output amount after the swap. * @param _i Token index to swap in. * @param _j Token index to swap out. * @param _dx Unconverted amount of token _i to swap in. * @return Unconverted amount of token _j to swap out. */ function getSwapAmount(uint256 _i, uint256 _j, uint256 _dx) external view returns (uint256) { uint256[] memory _balances = balances; require(_i != _j, "same token"); require(_i < _balances.length, "invalid in"); require(_j < _balances.length, "invalid out"); require(_dx > 0, "invalid amount"); uint256 A = getA(); uint256 D = totalSupply; // balance[i] = balance[i] + dx * precisions[i] _balances[_i] = _balances[_i].add(_dx.mul(precisions[_i])); uint256 y = _getY(_balances, _j, D, A); // dy = (balance[j] - y - 1) / precisions[j] in case there was rounding errors uint256 dy = _balances[_j].sub(y).sub(1).div(precisions[_j]); if (swapFee > 0) { dy = dy.sub(dy.mul(swapFee).div(feeDenominator)); } return dy; } /** * @dev Exchange between two underlying tokens. * @param _i Token index to swap in. * @param _j Token index to swap out. * @param _dx Unconverted amount of token _i to swap in. * @param _minDy Minimum token _j to swap out in converted balance. */ function swap(uint256 _i, uint256 _j, uint256 _dx, uint256 _minDy) external nonReentrant { uint256[] memory _balances = balances; // If swap is paused, only admins can swap. require(!paused || admins[msg.sender], "paused"); require(_i != _j, "same token"); require(_i < _balances.length, "invalid in"); require(_j < _balances.length, "invalid out"); require(_dx > 0, "invalid amount"); uint256 A = getA(); uint256 D = totalSupply; // balance[i] = balance[i] + dx * precisions[i] _balances[_i] = _balances[_i].add(_dx.mul(precisions[_i])); uint256 y = _getY(_balances, _j, D, A); // dy = (balance[j] - y - 1) / precisions[j] in case there was rounding errors uint256 dy = _balances[_j].sub(y).sub(1).div(precisions[_j]); // Update token balance in storage balances[_j] = y; balances[_i] = _balances[_i]; uint256 fee = swapFee; if (fee > 0) { dy = dy.sub(dy.mul(fee).div(feeDenominator)); } require(dy >= _minDy, "fewer than expected"); IERC20(tokens[_i]).safeTransferFrom(msg.sender, address(this), _dx); // Important: When swap fee > 0, the swap fee is charged on the output token. // Therefore, balances[j] < tokens[j].balanceOf(this) // Since balances[j] is used to compute D, D is unchanged. // collectFees() is used to convert the difference between balances[j] and tokens[j].balanceOf(this) // into pool token as fees! IERC20(tokens[_j]).safeTransfer(msg.sender, dy); emit TokenSwapped(msg.sender, tokens[_i], tokens[_j], _dx, dy); } /** * @dev Computes the amounts of underlying tokens when redeeming pool token. * @param _amount Amount of pool tokens to redeem. * @return Amounts of underlying tokens redeemed. */ function getRedeemProportionAmount(uint256 _amount) external view returns (uint256[] memory, uint256) { uint256[] memory _balances = balances; require(_amount > 0, "zero amount"); uint256 D = totalSupply; uint256[] memory amounts = new uint256[](_balances.length); uint256 feeAmount = 0; if (redeemFee > 0) { feeAmount = _amount.mul(redeemFee).div(feeDenominator); // Redemption fee is charged with pool token before redemption. _amount = _amount.sub(feeAmount); } for (uint256 i = 0; i < _balances.length; i++) { // We might choose to use poolToken.totalSupply to compute the amount, but decide to use // D in case we have multiple minters on the pool token. amounts[i] = _balances[i].mul(_amount).div(D).div(precisions[i]); } return (amounts, feeAmount); } /** * @dev Redeems pool token to underlying tokens proportionally. * @param _amount Amount of pool token to redeem. * @param _minRedeemAmounts Minimum amount of underlying tokens to get. */ function redeemProportion(uint256 _amount, uint256[] calldata _minRedeemAmounts) external nonReentrant { uint256[] memory _balances = balances; // If swap is paused, only admins can redeem. require(!paused || admins[msg.sender], "paused"); require(_amount > 0, "zero amount"); require(_balances.length == _minRedeemAmounts.length, "invalid mins"); uint256 D = totalSupply; uint256[] memory amounts = new uint256[](_balances.length); uint256 fee = redeemFee; uint256 feeAmount; if (fee > 0) { feeAmount = _amount.mul(fee).div(feeDenominator); // Redemption fee is paid with pool token // No conversion is needed as the pool token has 18 decimals IERC20(poolToken).safeTransferFrom(msg.sender, feeRecipient, feeAmount); _amount = _amount.sub(feeAmount); } for (uint256 i = 0; i < _balances.length; i++) { // We might choose to use poolToken.totalSupply to compute the amount, but decide to use // D in case we have multiple minters on the pool token. uint256 tokenAmount = _balances[i].mul(_amount).div(D); // Important: Underlying tokens must convert back to original decimals! amounts[i] = tokenAmount.div(precisions[i]); require(amounts[i] >= _minRedeemAmounts[i], "fewer than expected"); // Updates the balance in storage balances[i] = _balances[i].sub(tokenAmount); IERC20(tokens[i]).safeTransfer(msg.sender, amounts[i]); } totalSupply = D.sub(_amount); // After reducing the redeem fee, the remaining pool tokens are burned! IERC20MintableBurnable(poolToken).burnFrom(msg.sender, _amount); emit Redeemed(msg.sender, _amount.add(feeAmount), amounts, feeAmount); } /** * @dev Computes the amount when redeeming pool token to one specific underlying token. * @param _amount Amount of pool token to redeem. * @param _i Index of the underlying token to redeem to. * @return Amount of underlying token that can be redeem to. */ function getRedeemSingleAmount(uint256 _amount, uint256 _i) external view returns (uint256, uint256) { uint256[] memory _balances = balances; require(_amount > 0, "zero amount"); require(_i < _balances.length, "invalid token"); uint256 A = getA(); uint256 D = totalSupply; uint256 feeAmount = 0; if (redeemFee > 0) { feeAmount = _amount.mul(redeemFee).div(feeDenominator); // Redemption fee is charged with pool token before redemption. _amount = _amount.sub(feeAmount); } // The pool token amount becomes D - _amount uint256 y = _getY(_balances, _i, D.sub(_amount), A); // dy = (balance[i] - y - 1) / precisions[i] in case there was rounding errors uint256 dy = _balances[_i].sub(y).sub(1).div(precisions[_i]); return (dy, feeAmount); } /** * @dev Redeem pool token to one specific underlying token. * @param _amount Amount of pool token to redeem. * @param _i Index of the token to redeem to. * @param _minRedeemAmount Minimum amount of the underlying token to redeem to. */ function redeemSingle(uint256 _amount, uint256 _i, uint256 _minRedeemAmount) external nonReentrant { uint256[] memory _balances = balances; // If swap is paused, only admins can redeem. require(!paused || admins[msg.sender], "paused"); require(_amount > 0, "zero amount"); require(_i < _balances.length, "invalid token"); uint256 A = getA(); uint256 D = totalSupply; uint256 fee = redeemFee; uint256 feeAmount = 0; if (fee > 0) { // Redemption fee is charged with pool token before redemption. feeAmount = _amount.mul(fee).div(feeDenominator); // No conversion is needed as the pool token has 18 decimals IERC20(poolToken).safeTransferFrom(msg.sender, feeRecipient, feeAmount); _amount = _amount.sub(feeAmount); } // y is converted(18 decimals) uint256 y = _getY(_balances, _i, D.sub(_amount), A); // dy is not converted // dy = (balance[i] - y - 1) / precisions[i] in case there was rounding errors uint256 dy = _balances[_i].sub(y).sub(1).div(precisions[_i]); require(dy >= _minRedeemAmount, "fewer than expected"); // Updates token balance in storage balances[_i] = y; uint256[] memory amounts = new uint256[](_balances.length); amounts[_i] = dy; IERC20(tokens[_i]).safeTransfer(msg.sender, dy); totalSupply = D.sub(_amount); IERC20MintableBurnable(poolToken).burnFrom(msg.sender, _amount); emit Redeemed(msg.sender, _amount.add(feeAmount), amounts, feeAmount); } /** * @dev Compute the amount of pool token that needs to be redeemed. * @param _amounts Unconverted token balances. * @return The amount of pool token that needs to be redeemed. */ function getRedeemMultiAmount(uint256[] calldata _amounts) external view returns (uint256, uint256) { uint256[] memory _balances = balances; require(_amounts.length == balances.length, "length not match"); uint256 A = getA(); uint256 oldD = totalSupply; for (uint256 i = 0; i < _balances.length; i++) { if (address(this).balance == 0) continue; //inject PRESENT ETHER // balance = balance + amount * precision _balances[i] = _balances[i].sub(_amounts[i].mul(precisions[i])); } uint256 newD = _getD(_balances, A); // newD should be smaller than or equal to oldD uint256 redeemAmount = oldD.sub(newD); uint256 feeAmount = 0; if (redeemFee > 0) { redeemAmount = redeemAmount.mul(feeDenominator).div(feeDenominator.sub(redeemFee)); feeAmount = redeemAmount.sub(oldD.sub(newD)); } return (redeemAmount, feeAmount); } /** * @dev Redeems underlying tokens. * @param _amounts Amounts of underlying tokens to redeem to. * @param _maxRedeemAmount Maximum of pool token to redeem. */ function redeemMulti(uint256[] calldata _amounts, uint256 _maxRedeemAmount) external nonReentrant { uint256[] memory _balances = balances; require(_amounts.length == balances.length, "length not match"); // If swap is paused, only admins can redeem. require(!paused || admins[msg.sender], "paused"); uint256 A = getA(); uint256 oldD = totalSupply; uint256 i = 0; for (i = 0; i < _balances.length; i++) { if (address(this).balance == 0) continue; //inject PRESENT ETHER // balance = balance + amount * precision _balances[i] = _balances[i].sub(_amounts[i].mul(precisions[i])); } uint256 newD = _getD(_balances, A); // newD should be smaller than or equal to oldD uint256 redeemAmount = oldD.sub(newD); uint256 fee = redeemFee; uint256 feeAmount = 0; if (fee > 0) { redeemAmount = redeemAmount.mul(feeDenominator).div(feeDenominator.sub(fee)); feeAmount = redeemAmount.sub(oldD.sub(newD)); // No conversion is needed as the pool token has 18 decimals IERC20(poolToken).safeTransferFrom(msg.sender, feeRecipient, feeAmount); } require(redeemAmount <= _maxRedeemAmount, "more than expected"); // Updates token balances in storage. balances = _balances; uint256 burnAmount = redeemAmount.sub(feeAmount); totalSupply = oldD.sub(burnAmount); IERC20MintableBurnable(poolToken).burnFrom(msg.sender, burnAmount); for (i = 0; i < _balances.length; i++) { if (address(this).balance == 0) continue; //inject PRESENT ETHER IERC20(tokens[i]).safeTransfer(msg.sender, _amounts[i]); } emit Redeemed(msg.sender, redeemAmount, _amounts, feeAmount); } /** * @dev Return the amount of fee that's not collected. */ function getPendingFeeAmount() external view returns (uint256) { uint256[] memory _balances = balances; uint256 A = getA(); uint256 oldD = totalSupply; for (uint256 i = 0; i < _balances.length; i++) { _balances[i] = IERC20(tokens[i]).balanceOf(address(this)).mul(precisions[i]); } uint256 newD = _getD(_balances, A); return newD.sub(oldD); } /** * @dev Collect fee based on the token balance difference. */ function collectFee() external returns (uint256) { require(admins[msg.sender], "not admin"); uint256[] memory _balances = balances; uint256 A = getA(); uint256 oldD = totalSupply; for (uint256 i = 0; i < _balances.length; i++) { _balances[i] = IERC20(tokens[i]).balanceOf(address(this)).mul(precisions[i]); } uint256 newD = _getD(_balances, A); uint256 feeAmount = newD.sub(oldD); if (address(this).balance == 0) return 0; //inject PRESENT ETHER balances = _balances; totalSupply = newD; address _feeRecipient = feeRecipient; IERC20MintableBurnable(poolToken).mint(_feeRecipient, feeAmount); emit FeeCollected(_feeRecipient, feeAmount); return feeAmount; } /** * @dev Updates the govenance address. */ function setGovernance(address _governance) external { require(msg.sender == governance, "not governance"); governance = _governance; } /** * @dev Updates the mint fee. */ function setMintFee(uint256 _mintFee) external { require(msg.sender == governance, "not governance"); mintFee = _mintFee; } /** * @dev Updates the swap fee. */ function setSwapFee(uint256 _swapFee) external { require(msg.sender == governance, "not governance"); swapFee = _swapFee; } /** * @dev Updates the redeem fee. */ function setRedeemFee(uint256 _redeemFee) external { require(msg.sender == governance, "not governance"); redeemFee = _redeemFee; } /** * @dev Updates the recipient of mint/swap/redeem fees. */ function setFeeRecipient(address _feeRecipient) external { require(msg.sender == governance, "not governance"); require(_feeRecipient != address(0x0), "fee recipient not set"); feeRecipient = _feeRecipient; } /** * @dev Updates the pool token. */ function setPoolToken(address _poolToken) external { require(msg.sender == governance, "not governance"); require(_poolToken != address(0x0), "pool token not set"); poolToken = _poolToken; } /** * @dev Pause mint/swap/redeem actions. Can unpause later. */ function pause() external { require(msg.sender == governance, "not governance"); require(!paused, "paused"); paused = true; } /** * @dev Unpause mint/swap/redeem actions. */ function unpause() external { require(msg.sender == governance, "not governance"); require(paused, "not paused"); paused = false; } /** * @dev Updates the admin role for the address. * @param _account Address to update admin role. * @param _allowed Whether the address is granted the admin role. */ function setAdmin(address _account, bool _allowed) external { require(msg.sender == governance, "not governance"); require(_account != address(0x0), "account not set"); admins[_account] = _allowed; } } // contract CurveRenCrvMigrator is IMigrator { using SafeERC20 for IERC20; address public constant override want = address(0x49849C98ae39Fff122806C06791Fa73784FB3675); // renCrv token address public constant override get = address(0xeF6e45af9a422c5469928F927ca04ed332322e2e); // acBTC address public constant wbtc = address(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); // WBTC token address public constant renbtc = address(0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D); // renBTC token address public constant acSwap = address(0x73FddFb941c11d16C827169Bb94aCC227841C396); // ACoconutSwap (proxy) address public constant acVault = address(0x1eB47C01cfAb26D2346B449975b7BF20a34e0d45); // acBTC vault address public constant curve = address(0x93054188d876f558f4a66B2EF1d97d16eDf0895B); // REN swap /** * @dev Performs the token migration. Only acBTC vault can trigger the migration. */ function migrate() public override { require(msg.sender == acVault, "not vault"); uint256 _want = IERC20(want).balanceOf(address(this)); // renCrv balance IERC20(want).safeApprove(curve, _want); if (_want > 0) { ICurveFi(curve).remove_liquidity(_want, [uint256(0), 0]); } uint256 _wbtc = IERC20(wbtc).balanceOf(address(this)); uint256 _renbtc = IERC20(renbtc).balanceOf(address(this)); // The initial deposit requires both WBTC and RenBTC. if (_wbtc > 0 && _renbtc > 0) { IERC20(wbtc).safeApprove(acSwap, _wbtc); IERC20(renbtc).safeApprove(acSwap, _renbtc); // WBTC is the first token and renBTC is the second! uint256[] memory amounts = new uint256[](2); amounts[0] = _wbtc; amounts[1] = _renbtc; ACoconutSwap(acSwap).mint(amounts, 0); } uint256 _get = IERC20(get).balanceOf(address(this)); // acBTC balance if (_get > 0) { IERC20(get).safeTransfer(acVault, _get); } } }
Updates the swap fee./
function setSwapFee(uint256 _swapFee) external { require(msg.sender == governance, "not governance"); swapFee = _swapFee; }
12,730,987
./partial_match/3/0xb7E92c14F753425DdF7Cd334DEbd78a0714c5c2A/sources/UTOCOIN.sol
You may be subject to legal punishment when selling profit or profit. KMONG OMD([email protected])
function owner() public view returns (address) { return _owner; }
5,122,210
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC1155Upgradeable.sol"; import "./IERC1155ReceiverUpgradeable.sol"; import "./extensions/IERC1155MetadataURIUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC1155Upgradeable, IERC1155MetadataURIUpgradeable { using AddressUpgradeable for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ function __ERC1155_init(string memory uri_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC1155_init_unchained(uri_); } function __ERC1155_init_unchained(string memory uri_) internal initializer { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC1155Upgradeable).interfaceId || interfaceId == type(IERC1155MetadataURIUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155ReceiverUpgradeable(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } uint256[47] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC1155Upgradeable.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURIUpgradeable is IERC1155Upgradeable { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; struct RoleData { mapping(address => bool) members; bytes32 adminRole; } library AccessControlEvents { event OwnerSet(address indexed owner); event OwnerTransferred(address indexed owner, address indexed prevOwner); /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged( bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole ); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted( bytes32 indexed role, address indexed account, address indexed sender ); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked( bytes32 indexed role, address indexed account, address indexed sender ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../storage/roles.sol"; abstract contract int_hasRole_AccessControl_v1 is sto_AccessControl_Roles { function _hasRole(bytes32 role, address account) internal view returns (bool hasRole_) { hasRole_ = accessControlRolesStore().roles[role].members[account]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./has-role.sol"; abstract contract int_requireAuthorization_AccessControl_v1 is int_hasRole_AccessControl_v1 { function _requireAuthorization(bytes32 role, address account) internal view { require(_hasRole(role, account), "AccessControl: unauthorized"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { int_requireAuthorization_AccessControl_v1 } from "../internal/require-authorization.sol"; abstract contract mod_authorized_AccessControl_v1 is int_requireAuthorization_AccessControl_v1 { modifier authorized(bytes32 role, address account) { _requireAuthorization(role, account); _; } } abstract contract mod_authorized_AccessControl is mod_authorized_AccessControl_v1 {} // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { RoleData } from "../data.sol"; contract sto_AccessControl_Roles { bytes32 internal constant POS = keccak256("teller_protocol.storage.access_control.roles"); struct AccessControlRolesStorage { mapping(bytes32 => RoleData) roles; } function accessControlRolesStore() internal pure returns (AccessControlRolesStorage storage s) { bytes32 position = POS; assembly { s.slot := position } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IStakeableNFT { function tokenBaseLoanSize(uint256 tokenId) external view returns (uint256); function tokenURIHash(uint256 tokenId) external view returns (string memory); function tokenContributionAsset(uint256 tokenId) external view returns (address); function tokenContributionSize(uint256 tokenId) external view returns (uint256); function tokenContributionMultiplier(uint256 tokenId) external view returns (uint8); } /** * @notice TellerNFTDictionary Version 1.02 * * @notice This contract is used to gather data for TellerV1 NFTs more efficiently. * @notice This contract has data which must be continuously synchronized with the TellerV1 NFT data * * @author [email protected] */ pragma solidity ^0.8.0; // Contracts import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; // Interfaces import "./IStakeableNFT.sol"; /** * @notice This contract is used by borrowers to call Dapp functions (using delegate calls). * @notice This contract should only be constructed using it's upgradeable Proxy contract. * @notice In order to call a Dapp function, the Dapp must be added in the DappRegistry instance. * * @author [email protected] */ contract TellerNFTDictionary is IStakeableNFT, AccessControlUpgradeable { struct Tier { uint256 baseLoanSize; string[] hashes; address contributionAsset; uint256 contributionSize; uint8 contributionMultiplier; } mapping(uint256 => uint256) public baseLoanSizes; mapping(uint256 => string[]) public hashes; mapping(uint256 => address) public contributionAssets; mapping(uint256 => uint256) public contributionSizes; mapping(uint256 => uint8) public contributionMultipliers; /* Constants */ bytes32 public constant ADMIN = keccak256("ADMIN"); /* State Variables */ mapping(uint256 => uint256) public _tokenTierMappingCompressed; bool public _tokenTierMappingCompressedSet; /* Modifiers */ modifier onlyAdmin() { require(hasRole(ADMIN, _msgSender()), "TellerNFTDictionary: not admin"); _; } function initialize(address initialAdmin) public { _setupRole(ADMIN, initialAdmin); _setRoleAdmin(ADMIN, ADMIN); __AccessControl_init(); } /* External Functions */ /** * @notice It returns information about a Tier for a token ID. * @param tokenId ID of the token to get Tier info. */ function getTokenTierIndex(uint256 tokenId) public view returns (uint8 index_) { //32 * 8 = 256 - each uint256 holds the data of 32 tokens . 8 bits each. uint256 mappingIndex = tokenId / 32; uint256 compressedRegister = _tokenTierMappingCompressed[mappingIndex]; //use 31 instead of 32 to account for the '0x' in the start. //the '31 -' reverses our bytes order which is necessary uint256 offset = ((31 - (tokenId % 32)) * 8); uint8 tierIndex = uint8((compressedRegister >> offset)); return tierIndex; } function getTierHashes(uint256 tierIndex) external view returns (string[] memory) { return hashes[tierIndex]; } /** * @notice Adds a new Tier to be minted with the given information. * @dev It auto increments the index of the next tier to add. * @param newTier Information about the new tier to add. * * Requirements: * - Caller must have the {Admin} role */ function setTier(uint256 index, Tier memory newTier) external onlyAdmin returns (bool) { baseLoanSizes[index] = newTier.baseLoanSize; hashes[index] = newTier.hashes; contributionAssets[index] = newTier.contributionAsset; contributionSizes[index] = newTier.contributionSize; contributionMultipliers[index] = newTier.contributionMultiplier; return true; } /** * @notice Sets the tiers for each tokenId using compressed data. * @param tiersMapping Information about the new tiers to add. * * Requirements: * - Caller must have the {Admin} role */ function setAllTokenTierMappings(uint256[] memory tiersMapping) public onlyAdmin returns (bool) { require( !_tokenTierMappingCompressedSet, "TellerNFTDictionary: token tier mapping already set" ); for (uint256 i = 0; i < tiersMapping.length; i++) { _tokenTierMappingCompressed[i] = tiersMapping[i]; } _tokenTierMappingCompressedSet = true; return true; } /** * @notice Sets the tiers for each tokenId using compressed data. * @param index the mapping row, each holds data for 32 tokens * @param tierMapping Information about the new tier to add. * * Requirements: * - Caller must have the {Admin} role */ function setTokenTierMapping(uint256 index, uint256 tierMapping) public onlyAdmin returns (bool) { _tokenTierMappingCompressed[index] = tierMapping; return true; } /** * @notice Sets a specific tier for a specific tokenId using compressed data. * @param tokenIds the NFT token Ids for which to add data * @param tokenTier the index of the tier that these tokenIds should have * * Requirements: * - Caller must have the {Admin} role */ function setTokenTierForTokenIds( uint256[] calldata tokenIds, uint256 tokenTier ) public onlyAdmin returns (bool) { for (uint256 i; i < tokenIds.length; i++) { setTokenTierForTokenId(tokenIds[i], tokenTier); } return true; } /** * @notice Sets a specific tier for a specific tokenId using compressed data. * @param tokenId the NFT token Id for which to add data * @param tokenTier the index of the tier that these tokenIds should have * * Requirements: * - Caller must have the {Admin} role */ function setTokenTierForTokenId(uint256 tokenId, uint256 tokenTier) public onlyAdmin returns (bool) { uint256 mappingIndex = tokenId / 32; uint256 existingRegister = _tokenTierMappingCompressed[mappingIndex]; uint256 offset = ((31 - (tokenId % 32)) * 8); uint256 updateMaskShifted = 0x00000000000000000000000000000000000000000000000000000000000000FF << offset; uint256 updateMaskShiftedNegated = ~updateMaskShifted; uint256 tokenTierShifted = ((0x0000000000000000000000000000000000000000000000000000000000000000 | tokenTier) << offset); uint256 existingRegisterClearedWithMask = existingRegister & updateMaskShiftedNegated; uint256 updatedRegister = existingRegisterClearedWithMask | tokenTierShifted; _tokenTierMappingCompressed[mappingIndex] = updatedRegister; return true; } function supportsInterface(bytes4 interfaceId) public view override(AccessControlUpgradeable) returns (bool) { return interfaceId == type(IStakeableNFT).interfaceId || AccessControlUpgradeable.supportsInterface(interfaceId); } /** New methods for the dictionary */ /** * @notice It returns Base Loan Size for a token ID. * @param tokenId ID of the token to get info. */ function tokenBaseLoanSize(uint256 tokenId) public view override returns (uint256) { uint8 tokenTier = getTokenTierIndex(tokenId); return baseLoanSizes[tokenTier]; } /** * @notice It returns Token URI Hash for a token ID. * @param tokenId ID of the token to get info. */ function tokenURIHash(uint256 tokenId) public view override returns (string memory) { uint8 tokenTier = getTokenTierIndex(tokenId); string[] memory tierImageHashes = hashes[tokenTier]; return tierImageHashes[tokenId % (tierImageHashes.length)]; } /** * @notice It returns Contribution Asset for a token ID. * @param tokenId ID of the token to get info. */ function tokenContributionAsset(uint256 tokenId) public view override returns (address) { uint8 tokenTier = getTokenTierIndex(tokenId); return contributionAssets[tokenTier]; } /** * @notice It returns Contribution Size for a token ID. * @param tokenId ID of the token to get info. */ function tokenContributionSize(uint256 tokenId) public view override returns (uint256) { uint8 tokenTier = getTokenTierIndex(tokenId); return contributionSizes[tokenTier]; } /** * @notice It returns Contribution Multiplier for a token ID. * @param tokenId ID of the token to get info. */ function tokenContributionMultiplier(uint256 tokenId) public view override returns (uint8) { uint8 tokenTier = getTokenTierIndex(tokenId); return contributionMultipliers[tokenTier]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // Contracts import { ERC1155Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155Upgradeable.sol"; import { AccessControlUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; // Libraries import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol"; import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; /*****************************************************************************************************/ /** WARNING **/ /** THIS CONTRACT IS UPGRADEABLE! **/ /** --------------------------------------------------------------------------------------------- **/ /** Do NOT change the order of or PREPEND any storage variables to this or new versions of this **/ /** contract as this will cause the the storage slots to be overwritten on the proxy contract!! **/ /** **/ /** Visit https://docs.openzeppelin.com/upgrades/2.6/proxies#upgrading-via-the-proxy-pattern for **/ /** more information. **/ /*****************************************************************************************************/ /** * @notice This contract is used by borrowers to call Dapp functions (using delegate calls). * @notice This contract should only be constructed using it's upgradeable Proxy contract. * @notice In order to call a Dapp function, the Dapp must be added in the DappRegistry instance. * * @author [email protected] */ abstract contract TellerNFT_V2 is ERC1155Upgradeable, AccessControlUpgradeable { using EnumerableSet for EnumerableSet.UintSet; /* Constants */ string public constant name = "Teller NFT"; string public constant symbol = "TNFT"; uint256 private constant ID_PADDING = 10000; bytes32 public constant ADMIN = keccak256("ADMIN"); /* State Variables */ struct Tier { uint256 baseLoanSize; address contributionAsset; uint256 contributionSize; uint16 contributionMultiplier; } // It holds the total number of tokens in existence. uint256 public totalSupply; // It holds the information about a tier. mapping(uint256 => Tier) public tiers; // It holds the total number of tiers. uint128 public tierCount; // It holds how many tokens types exists in a tier. mapping(uint128 => uint256) public tierTokenCount; // It holds a set of tokenIds for an owner address mapping(address => EnumerableSet.UintSet) internal _ownedTokenIds; // It holds the URI hash containing the token metadata mapping(uint256 => string) internal _idToUriHash; // It is a reverse lookup of the token ID given the metadata hash mapping(string => uint256) internal _uriHashToId; // Hash to the contract metadata string private _contractURIHash; /* Public Functions */ /** * @notice checks if an interface is supported by ITellerNFT or AccessControlUpgradeable * @param interfaceId the identifier of the interface * @return bool stating whether or not our interface is supported */ function supportsInterface(bytes4 interfaceId) public view override(ERC1155Upgradeable, AccessControlUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256 tokenId) public view virtual override returns (string memory) { return string(abi.encodePacked(super.uri(tokenId), _idToUriHash[tokenId])); } /* External Functions */ /** * @notice The contract metadata URI. * @return the contract URI hash */ function contractURI() external view returns (string memory) { // URI returned from parent just returns base URI return string(abi.encodePacked(super.uri(0), _contractURIHash)); } /** * @notice It returns information about a Tier for a token ID. * @param tokenId ID of the token to get Tier info. * @return tierId_ the index of the tier the tokenId belongs to * @return tierTokenId_ the tokenId in tier */ function getTokenTierId(uint256 tokenId) external view returns (uint128 tierId_, uint128 tierTokenId_) { (tierId_, tierTokenId_) = _splitTokenId(tokenId); } /** * @notice It returns Base Loan Size for a token ID. * @param tokenId ID of the token to get info. */ function tokenBaseLoanSize(uint256 tokenId) public view returns (uint256) { (uint128 tierId, ) = _splitTokenId(tokenId); return tiers[tierId].baseLoanSize; } /** * @notice It returns Contribution Asset for a token ID. * @param tokenId ID of the token to get info. */ function tokenContributionAsset(uint256 tokenId) public view returns (address) { (uint128 tierId, ) = _splitTokenId(tokenId); return tiers[tierId].contributionAsset; } /** * @notice It returns Contribution Size for a token ID. * @param tokenId ID of the token to get info. */ function tokenContributionSize(uint256 tokenId) public view returns (uint256) { (uint128 tierId, ) = _splitTokenId(tokenId); return tiers[tierId].contributionSize; } /** * @notice It returns Contribution Multiplier for a token ID. * @param tokenId ID of the token to get info. */ function tokenContributionMultiplier(uint256 tokenId) public view returns (uint16) { (uint128 tierId, ) = _splitTokenId(tokenId); return tiers[tierId].contributionMultiplier; } /** * @notice It returns an array of token IDs owned by an address. * @dev It uses a EnumerableSet to store values and loops over each element to add to the array. * @dev Can be costly if calling within a contract for address with many tokens. * @return owned_ the array of tokenIDs owned by the address */ function getOwnedTokens(address owner) external view returns (uint256[] memory owned_) { EnumerableSet.UintSet storage set = _ownedTokenIds[owner]; owned_ = new uint256[](set.length()); for (uint256 i; i < owned_.length; i++) { owned_[i] = set.at(i); } } /** * @notice Creates new Tiers to be minted with the given information. * @dev It auto increments the index of the next tier to add. * @param newTiers Information about the new tiers to add. * @param tierHashes Metadata hashes belonging to the tiers. * * Requirements: * - Caller must have the {ADMIN} role */ function createTiers( Tier[] calldata newTiers, string[][] calldata tierHashes ) external onlyRole(ADMIN) { require( newTiers.length == tierHashes.length, "Teller: array length mismatch" ); for (uint256 i; i < newTiers.length; i++) { _createTier(newTiers[i], tierHashes[i]); } } /** * @notice creates the tier along with the tier hashes, then saves the tokenId * information in id -> hash and hash -> id mappings * @param newTier the Tier struct containing all the tier information * @param tierHashes the tier hashes to add to the tier */ function _createTier(Tier calldata newTier, string[] calldata tierHashes) internal { // Increment tier counter to use tierCount++; Tier storage tier = tiers[tierCount]; tier.baseLoanSize = newTier.baseLoanSize; tier.contributionAsset = newTier.contributionAsset; tier.contributionSize = newTier.contributionSize; tier.contributionMultiplier = newTier.contributionMultiplier; // Store how many tokens are on the tier tierTokenCount[tierCount] = tierHashes.length; // Set the token URI hash for (uint128 i; i < tierHashes.length; i++) { uint256 tokenId = _mergeTokenId(tierCount, i); _idToUriHash[tokenId] = tierHashes[i]; _uriHashToId[tierHashes[i]] = tokenId; } } /** * @dev See {_setURI}. * * Requirements: * * - `newURI` must be prepended with a forward slash (/) */ function setURI(string memory newURI) external onlyRole(ADMIN) { _setURI(newURI); } /** * @notice Sets the contract level metadata URI hash. * @param contractURIHash The hash to the initial contract level metadata. */ function setContractURIHash(string memory contractURIHash) public onlyRole(ADMIN) { _contractURIHash = contractURIHash; } /** * @notice Initializes the TellerNFT. * @param data Bytes to init the token with. */ function initialize(bytes calldata data) public virtual initializer { // Set the initial URI __ERC1155_init("https://gateway.pinata.cloud/ipfs/"); __AccessControl_init(); // Set admin role for admins _setRoleAdmin(ADMIN, ADMIN); // Set the initial admin _setupRole(ADMIN, _msgSender()); // Set initial contract URI hash setContractURIHash("QmWAfQFFwptzRUCdF2cBFJhcB2gfHJMd7TQt64dZUysk3R"); __TellerNFT_V2_init_unchained(data); } function __TellerNFT_V2_init_unchained(bytes calldata data) internal virtual initializer {} /* Internal Functions */ /** * @notice it removes a token ID from the ownedTokenIds mapping if the balance of * the user's tokenId is 0 * @param account the address to add the token id to * @param id the token ID */ function _removeOwnedTokenCheck(address account, uint256 id) private { if (balanceOf(account, id) == 0) { _ownedTokenIds[account].remove(id); } } /** * @notice it adds a token id to the ownedTokenIds mapping * @param account the address to the add the token ID to * @param id the token ID */ function _addOwnedToken(address account, uint256 id) private { _ownedTokenIds[account].add(id); } /** * @dev Runs super function and then increases total supply. * * See {ERC1155Upgradeable._mint}. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal override { super._mint(account, id, amount, data); // add the id to the owned token ids of the user _addOwnedToken(account, id); totalSupply += amount; } /** * @dev Runs super function and then increases total supply. * * See {ERC1155Upgradeable._mintBatch}. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override { super._mintBatch(to, ids, amounts, data); for (uint256 i; i < amounts.length; i++) { totalSupply += amounts[i]; _addOwnedToken(to, ids[i]); } } /** * @dev Runs super function and then decreases total supply. * * See {ERC1155Upgradeable._burn}. */ function _burn( address account, uint256 id, uint256 amount ) internal override { super._burn(account, id, amount); _removeOwnedTokenCheck(account, id); totalSupply -= amount; } /** * @dev Runs super function and then decreases total supply. * * See {ERC1155Upgradeable._burnBatch}. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal override { super._burnBatch(account, ids, amounts); for (uint256 i; i < amounts.length; i++) { totalSupply -= amounts[i]; _removeOwnedTokenCheck(account, ids[i]); } } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * See {ERC1155Upgradeable._safeTransferFrom}. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal override { super._safeTransferFrom(from, to, id, amount, data); _removeOwnedTokenCheck(from, id); _addOwnedToken(to, id); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * See {ERC1155Upgradeable._safeBatchTransferFrom} */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override { super._safeBatchTransferFrom(from, to, ids, amounts, data); for (uint256 i; i < ids.length; i++) { _removeOwnedTokenCheck(from, ids[i]); _addOwnedToken(to, ids[i]); } } /** * @dev Checks if a token ID exists. To exists the ID must have a URI hash associated. * @param tokenId ID of the token to check. */ function _exists(uint256 tokenId) internal view returns (bool) { return bytes(_idToUriHash[tokenId]).length > 0; } /** * @dev Creates a V2 token ID from a tier ID and tier token ID. * @param tierId Index of the tier to use. * @param tierTokenId ID of the token within the given tier. * @return tokenId_ V2 NFT token ID. */ function _mergeTokenId(uint128 tierId, uint128 tierTokenId) internal pure returns (uint256 tokenId_) { tokenId_ = tierId * ID_PADDING; tokenId_ += tierTokenId; } /** * @dev Creates a V2 token ID from a tier ID and tier token ID. * @param tokenId V2 NFT token ID. * @return tierId_ Index of the token tier. * @return tierTokenId_ ID of the token within the tier. */ function _splitTokenId(uint256 tokenId) internal pure returns (uint128 tierId_, uint128 tierTokenId_) { tierId_ = SafeCast.toUint128(tokenId / ID_PADDING); tierTokenId_ = SafeCast.toUint128(tokenId % ID_PADDING); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; bytes32 constant ADMIN = keccak256("ADMIN"); bytes32 constant MINTER = keccak256("MINTER"); struct MerkleRoot { bytes32 merkleRoot; uint256 tierIndex; } struct ClaimNFTRequest { uint256 merkleIndex; uint256 nodeIndex; uint256 amount; bytes32[] merkleProof; } library DistributorEvents { event Claimed(address indexed account); event MerkleAdded(uint256 index); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // Contracts import "../store.sol"; import "../../../contexts/access-control/modifiers/authorized.sol"; // Utils import { ADMIN } from "../data.sol"; // Interfaces import "../../mainnet/MainnetTellerNFT.sol"; contract ent_upgradeNFTV2_NFTDistributor_v1 is sto_NFTDistributor, mod_authorized_AccessControl_v1 { /** * @notice Upgrades the reference to the NFT to the V2 deployment address. * @param _nft The address of the TellerNFT. */ function upgradeNFTV2(address _nft) external authorized(ADMIN, msg.sender) { require(distributorStore().version == 0, "Teller: invalid upgrade version"); distributorStore().version = 1; distributorStore().nft = MainnetTellerNFT(_nft); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // Interfaces import "../mainnet/MainnetTellerNFT.sol"; // Utils import { MerkleRoot } from "./data.sol"; abstract contract sto_NFTDistributor { struct DistributorStorage { MainnetTellerNFT nft; MerkleRoot[] merkleRoots; mapping(uint256 => mapping(uint256 => uint256)) claimedBitMap; address _dictionary; // DEPRECATED uint256 version; } bytes32 constant POSITION = keccak256("teller_nft.distributor"); function distributorStore() internal pure returns (DistributorStorage storage s) { bytes32 P = POSITION; assembly { s.slot := P } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // Contracts import { TellerNFT_V2 } from "../TellerNFT_V2.sol"; import { TellerNFTDictionary } from "../TellerNFTDictionary.sol"; import { IERC721ReceiverUpgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; contract MainnetTellerNFT is IERC721ReceiverUpgradeable, TellerNFT_V2 { /* Constants */ address public constant V1 = 0x2ceB85a2402C94305526ab108e7597a102D6C175; TellerNFTDictionary public constant DICT = TellerNFTDictionary(0x72733102AB139FB0367cc29D492c955A7c736079); address public constant diamond = 0xc14D994fe7C5858c93936cc3bD42bb9467d6fB2C; bytes32 public constant MINTER = keccak256("MINTER"); /* Initializers */ /** * @notice Initializes the TellerNFT. * @param data The addresses that should allowed to mint tokens. */ function __TellerNFT_V2_init_unchained(bytes calldata data) internal override initializer { address[] memory minters = abi.decode(data, (address[])); // Set admin role for minters _setRoleAdmin(MINTER, ADMIN); // Set the initial minters for (uint256 i; i < minters.length; i++) { _setupRole(MINTER, minters[i]); } } /* External Functions */ /** * @notice It mints a new token for a Tier index. * @param tierIndex Tier to mint token on. * @param owner The owner of the new token. * * Requirements: * - Caller must be an authorized minter */ function mint( address owner, uint128 tierIndex, uint128 amount ) external onlyRole(MINTER) { // Get the token ID to mint for the user // On a fresh mint, the exact token ID minted is determined on tx execution // with sudo randomness using the block number uint256 tokenId = _mergeTokenId( tierIndex, uint128(block.number % tierTokenCount[tierIndex]) ); _mint(owner, tokenId, uint256(amount), ""); } /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external override returns (bytes4) { // Check which 721 token we received // We only care about V1 so we can migrate it if (_msgSender() == V1) { uint256 newTokenId; // if the from address is the diamond address, we trust that we // can decode the data into the newly converted token id if (from == diamond) { newTokenId = abi.decode(data, (uint256)); } else { newTokenId = convertV1TokenId(tokenId); } // Convert V1 token ID and mint 1 new V2 token to the diamond _mint(from, newTokenId, 1, ""); } return IERC721ReceiverUpgradeable.onERC721Received.selector; } /* Public Functions */ /** * @notice it performs a reverse look up on by finding our ID using the * tokenURI hash using the NFT dictionary. Required that the token id exists * @param _tokenId the tokenId to look up */ function convertV1TokenId(uint256 _tokenId) public view returns (uint256 tokenId_) { tokenId_ = _uriHashToId[DICT.tokenURIHash(_tokenId)]; require(_exists(tokenId_), "TellerNFT: invalid token ID"); } }
checks if an interface is supported by ITellerNFT or AccessControlUpgradeable interfaceId the identifier of the interface return bool stating whether or not our interface is supported/
function supportsInterface(bytes4 interfaceId) public view override(ERC1155Upgradeable, AccessControlUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); }
6,317,300
pragma solidity 0.4.24; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "../interface/IArbitrage.sol"; import "../interface/IBank.sol"; import "../FlashLender.sol"; contract MockReentrancyArbitrage is IArbitrage { using SafeMath for uint256; address public lender; address constant public ETH = 0x0; uint256 constant public MAX_UINT = 2 ** 256 - 1; modifier onlyLender() { require(msg.sender == lender); _; } constructor(address _lender) public { lender = _lender; } // Receive ETH from bank. function () payable public {} /** * @dev Borrow from flash lender to execute arbitrage trade. * @param token Address of the token to borrow. 0x0 for Ether. * @param amount Amount to borrow. * @param dest Address of the account to receive arbitrage profits. * @param data The data to execute the arbitrage trade. */ function submitTrade(address token, uint256 amount, address dest, bytes data) external { FlashLender(lender).borrow(token, amount, dest, data); } /** * @dev Callback from flash lender. Executes arbitrage trade. * @param token Address of the borrowed token. 0x0 for Ether. * @param amount Amount borrowed. * @param dest Address of the account to receive arbitrage profits. * @param data The data to execute the arbitrage trade. */ function executeArbitrage( address token, uint256 amount, address dest, bytes data ) external onlyLender returns (bool) { FlashLender(lender).borrow(token, amount, dest, data); return true; } }
Callback from flash lender. Executes arbitrage trade. token Address of the borrowed token. 0x0 for Ether. amount Amount borrowed. dest Address of the account to receive arbitrage profits. data The data to execute the arbitrage trade./
function executeArbitrage( address token, uint256 amount, address dest, bytes data ) external onlyLender returns (bool) { FlashLender(lender).borrow(token, amount, dest, data); return true; }
2,514,851
// SPDX-License-Identifier: MIT // 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.6.12; import './lib/ABDKMath64x64.sol'; import './Orchestrator.sol'; import './ProportionalLiquidity.sol'; import './Swaps.sol'; import './ViewLiquidity.sol'; import './Storage.sol'; import './MerkleProver.sol'; import './interfaces/IFreeFromUpTo.sol'; library Curves { using ABDKMath64x64 for int128; event Approval( address indexed _owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 value); function add( uint256 x, uint256 y, string memory errorMessage ) private pure returns (uint256 z) { require((z = x + y) >= x, errorMessage); } function sub( uint256 x, uint256 y, string memory errorMessage ) private pure returns (uint256 z) { require((z = x - y) <= x, errorMessage); } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer( Storage.Curve storage curve, address recipient, uint256 amount ) external returns (bool) { _transfer(curve, msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve( Storage.Curve storage curve, address spender, uint256 amount ) external returns (bool) { _approve(curve, 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( Storage.Curve storage curve, address sender, address recipient, uint256 amount ) external returns (bool) { _transfer(curve, sender, recipient, amount); _approve( curve, sender, msg.sender, sub( curve.allowances[sender][msg.sender], amount, 'Curve/insufficient-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( Storage.Curve storage curve, address spender, uint256 addedValue ) external returns (bool) { _approve( curve, msg.sender, spender, add( curve.allowances[msg.sender][spender], addedValue, 'Curve/approval-overflow' ) ); 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( Storage.Curve storage curve, address spender, uint256 subtractedValue ) external returns (bool) { _approve( curve, msg.sender, spender, sub( curve.allowances[msg.sender][spender], subtractedValue, 'Curve/allowance-decrease-underflow' ) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is public 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( Storage.Curve storage curve, address sender, address recipient, uint256 amount ) private { require(sender != address(0), 'ERC20: transfer from the zero address'); require(recipient != address(0), 'ERC20: transfer to the zero address'); curve.balances[sender] = sub( curve.balances[sender], amount, 'Curve/insufficient-balance' ); curve.balances[recipient] = add( curve.balances[recipient], amount, 'Curve/transfer-overflow' ); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `_owner`s tokens. * * This is public 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( Storage.Curve storage curve, 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'); curve.allowances[_owner][spender] = amount; emit Approval(_owner, spender, amount); } } contract Curve is Storage, MerkleProver { using SafeMath for uint256; event Approval( address indexed _owner, address indexed spender, uint256 value ); event ParametersSet( uint256 alpha, uint256 beta, uint256 delta, uint256 epsilon, uint256 lambda ); event AssetIncluded( address indexed numeraire, address indexed reserve, uint256 weight ); event AssimilatorIncluded( address indexed derivative, address indexed numeraire, address indexed reserve, address assimilator ); event PartitionRedeemed( address indexed token, address indexed redeemer, uint256 value ); event OwnershipTransfered( address indexed previousOwner, address indexed newOwner ); event FrozenSet(bool isFrozen); event EmergencyAlarm(bool isEmergency); event WhitelistingStopped(); event Trade( address indexed trader, address indexed origin, address indexed target, uint256 originAmount, uint256 targetAmount ); event Transfer(address indexed from, address indexed to, uint256 value); modifier onlyOwner() { require(msg.sender == owner, 'Curve/caller-is-not-owner'); _; } modifier nonReentrant() { require(notEntered, 'Curve/re-entered'); notEntered = false; _; notEntered = true; } modifier transactable() { require(!frozen, 'Curve/frozen-only-allowing-proportional-withdraw'); _; } modifier isEmergency() { require( emergency, 'Curve/emergency-only-allowing-emergency-proportional-withdraw' ); _; } modifier deadline(uint256 _deadline) { require(block.timestamp < _deadline, 'Curve/tx-deadline-passed'); _; } modifier inWhitelistingStage() { require(whitelistingStage, 'Curve/whitelist-stage-on-going'); _; } modifier notInWhitelistingStage() { require(!whitelistingStage, 'Curve/whitelist-stage-stopped'); _; } constructor( string memory _name, string memory _symbol, address[] memory _assets, uint256[] memory _assetWeights ) public { owner = msg.sender; name = _name; symbol = _symbol; emit OwnershipTransfered(address(0), msg.sender); Orchestrator.initialize( curve, numeraires, reserves, derivatives, _assets, _assetWeights ); } /// @notice sets the parameters for the pool /// @param _alpha the value for alpha (halt threshold) must be less than or equal to 1 and greater than 0 /// @param _beta the value for beta must be less than alpha and greater than 0 /// @param _feeAtHalt the maximum value for the fee at the halt point /// @param _epsilon the base fee for the pool /// @param _lambda the value for lambda must be less than or equal to 1 and greater than zero function setParams( uint256 _alpha, uint256 _beta, uint256 _feeAtHalt, uint256 _epsilon, uint256 _lambda ) external onlyOwner { Orchestrator.setParams(curve, _alpha, _beta, _feeAtHalt, _epsilon, _lambda); } /// @notice excludes an assimilator from the curve /// @param _derivative the address of the assimilator to exclude function excludeDerivative(address _derivative) external onlyOwner { for (uint256 i = 0; i < numeraires.length; i++) { if (_derivative == numeraires[i]) revert('Curve/cannot-delete-numeraire'); if (_derivative == reserves[i]) revert('Curve/cannot-delete-reserve'); } delete curve.assimilators[_derivative]; } /// @notice view the current parameters of the curve /// @return alpha_ the current alpha value /// beta_ the current beta value /// delta_ the current delta value /// epsilon_ the current epsilon value /// lambda_ the current lambda value /// omega_ the current omega value function viewCurve() external view returns ( uint256 alpha_, uint256 beta_, uint256 delta_, uint256 epsilon_, uint256 lambda_ ) { return Orchestrator.viewCurve(curve); } function turnOffWhitelisting() external onlyOwner { emit WhitelistingStopped(); whitelistingStage = false; } function setEmergency(bool _emergency) external onlyOwner { emit EmergencyAlarm(_emergency); emergency = _emergency; } function setFrozen(bool _toFreezeOrNotToFreeze) external onlyOwner { emit FrozenSet(_toFreezeOrNotToFreeze); frozen = _toFreezeOrNotToFreeze; } function transferOwnership(address _newOwner) external onlyOwner { require( _newOwner != address(0), 'Curve/new-owner-cannot-be-zeroth-address' ); emit OwnershipTransfered(owner, _newOwner); owner = _newOwner; } /// @notice swap a dynamic origin amount for a fixed target amount /// @param _origin the address of the origin /// @param _target the address of the target /// @param _originAmount the origin amount /// @param _minTargetAmount the minimum target amount /// @param _deadline deadline in block number after which the trade will not execute /// @return targetAmount_ the amount of target that has been swapped for the origin amount function originSwap( address _origin, address _target, uint256 _originAmount, uint256 _minTargetAmount, uint256 _deadline ) external deadline(_deadline) transactable nonReentrant returns (uint256 targetAmount_) { targetAmount_ = Swaps.originSwap( curve, _origin, _target, _originAmount, msg.sender ); require(targetAmount_ >= _minTargetAmount, 'Curve/below-min-target-amount'); } /// @notice view how much target amount a fixed origin amount will swap for /// @param _origin the address of the origin /// @param _target the address of the target /// @param _originAmount the origin amount /// @return targetAmount_ the target amount that would have been swapped for the origin amount function viewOriginSwap( address _origin, address _target, uint256 _originAmount ) external view transactable returns (uint256 targetAmount_) { targetAmount_ = Swaps.viewOriginSwap( curve, _origin, _target, _originAmount ); } /// @notice swap a dynamic origin amount for a fixed target amount /// @param _origin the address of the origin /// @param _target the address of the target /// @param _maxOriginAmount the maximum origin amount /// @param _targetAmount the target amount /// @param _deadline deadline in block number after which the trade will not execute /// @return originAmount_ the amount of origin that has been swapped for the target function targetSwap( address _origin, address _target, uint256 _maxOriginAmount, uint256 _targetAmount, uint256 _deadline ) external deadline(_deadline) transactable nonReentrant returns (uint256 originAmount_) { originAmount_ = Swaps.targetSwap( curve, _origin, _target, _targetAmount, msg.sender ); require(originAmount_ <= _maxOriginAmount, 'Curve/above-max-origin-amount'); } /// @notice view how much of the origin currency the target currency will take /// @param _origin the address of the origin /// @param _target the address of the target /// @param _targetAmount the target amount /// @return originAmount_ the amount of target that has been swapped for the origin function viewTargetSwap( address _origin, address _target, uint256 _targetAmount ) external view transactable returns (uint256 originAmount_) { originAmount_ = Swaps.viewTargetSwap( curve, _origin, _target, _targetAmount ); } /// @notice deposit into the pool with no slippage from the numeraire assets the pool supports /// @param index Index corresponding to the merkleProof /// @param account Address coorresponding to the merkleProof /// @param amount Amount coorresponding to the merkleProof, should always be 1 /// @param merkleProof Merkle proof /// @param _deposit the full amount you want to deposit into the pool which will be divided up evenly amongst /// the numeraire assets of the pool /// @return (the amount of curves you receive in return for your deposit, /// the amount deposited for each numeraire) function depositWithWhitelist( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof, uint256 _deposit, uint256 _deadline ) external deadline(_deadline) transactable nonReentrant inWhitelistingStage returns (uint256, uint256[] memory) { require( isWhitelisted(index, account, amount, merkleProof), 'Curve/not-whitelisted' ); require(msg.sender == account, 'Curve/not-approved-user'); (uint256 curvesMinted_, uint256[] memory deposits_) = ProportionalLiquidity .proportionalDeposit(curve, _deposit); whitelistedDeposited[msg.sender] = whitelistedDeposited[msg.sender].add( curvesMinted_ ); // 10k max deposit if (whitelistedDeposited[msg.sender] > 10000e18) { revert('Curve/exceed-whitelist-maximum-deposit'); } return (curvesMinted_, deposits_); } /// @notice deposit into the pool with no slippage from the numeraire assets the pool supports /// @param _deposit the full amount you want to deposit into the pool which will be divided up evenly amongst /// the numeraire assets of the pool /// @return (the amount of curves you receive in return for your deposit, /// the amount deposited for each numeraire) function deposit(uint256 _deposit, uint256 _deadline) external deadline(_deadline) transactable nonReentrant notInWhitelistingStage returns (uint256, uint256[] memory) { // (curvesMinted_, deposits_) return ProportionalLiquidity.proportionalDeposit(curve, _deposit); } /// @notice view deposits and curves minted a given deposit would return /// @param _deposit the full amount of stablecoins you want to deposit. Divided evenly according to the /// prevailing proportions of the numeraire assets of the pool /// @return (the amount of curves you receive in return for your deposit, /// the amount deposited for each numeraire) function viewDeposit(uint256 _deposit) external view transactable returns (uint256, uint256[] memory) { // curvesToMint_, depositsToMake_ return ProportionalLiquidity.viewProportionalDeposit(curve, _deposit); } /// @notice Emergency withdraw tokens in the event that the oracle somehow bugs out /// and no one is able to withdraw due to the invariant check /// @param _curvesToBurn the full amount you want to withdraw from the pool which will be withdrawn from evenly amongst the /// numeraire assets of the pool /// @return withdrawals_ the amonts of numeraire assets withdrawn from the pool function emergencyWithdraw(uint256 _curvesToBurn, uint256 _deadline) external isEmergency deadline(_deadline) nonReentrant returns (uint256[] memory withdrawals_) { return ProportionalLiquidity.emergencyProportionalWithdraw(curve, _curvesToBurn); } /// @notice withdrawas amount of curve tokens from the the pool equally from the numeraire assets of the pool with no slippage /// @param _curvesToBurn the full amount you want to withdraw from the pool which will be withdrawn from evenly amongst the /// numeraire assets of the pool /// @return withdrawals_ the amonts of numeraire assets withdrawn from the pool function withdraw(uint256 _curvesToBurn, uint256 _deadline) external deadline(_deadline) nonReentrant returns (uint256[] memory withdrawals_) { if (whitelistingStage) { whitelistedDeposited[msg.sender] = whitelistedDeposited[msg.sender].sub( _curvesToBurn ); } return ProportionalLiquidity.proportionalWithdraw(curve, _curvesToBurn); } /// @notice views the withdrawal information from the pool /// @param _curvesToBurn the full amount you want to withdraw from the pool which will be withdrawn from evenly amongst the /// numeraire assets of the pool /// @return the amonnts of numeraire assets withdrawn from the pool function viewWithdraw(uint256 _curvesToBurn) external view transactable returns (uint256[] memory) { return ProportionalLiquidity.viewProportionalWithdraw(curve, _curvesToBurn); } function supportsInterface(bytes4 _interface) public pure returns (bool supports_) { supports_ = this.supportsInterface.selector == _interface || // erc165 bytes4(0x7f5828d0) == _interface || // eip173 bytes4(0x36372b07) == _interface; // erc20 } /// @notice transfers curve tokens /// @param _recipient the address of where to send the curve tokens /// @param _amount the amount of curve tokens to send /// @return success_ the success bool of the call function transfer(address _recipient, uint256 _amount) public nonReentrant returns (bool success_) { success_ = Curves.transfer(curve, _recipient, _amount); } /// @notice transfers curve tokens from one address to another address /// @param _sender the account from which the curve tokens will be sent /// @param _recipient the account to which the curve tokens will be sent /// @param _amount the amount of curve tokens to transfer /// @return success_ the success bool of the call function transferFrom( address _sender, address _recipient, uint256 _amount ) public nonReentrant returns (bool success_) { success_ = Curves.transferFrom(curve, _sender, _recipient, _amount); } /// @notice approves a user to spend curve tokens on their behalf /// @param _spender the account to allow to spend from msg.sender /// @param _amount the amount to specify the spender can spend /// @return success_ the success bool of this call function approve(address _spender, uint256 _amount) public nonReentrant returns (bool success_) { success_ = Curves.approve(curve, _spender, _amount); } /// @notice view the curve token balance of a given account /// @param _account the account to view the balance of /// @return balance_ the curve token ballance of the given account function balanceOf(address _account) public view returns (uint256 balance_) { balance_ = curve.balances[_account]; } /// @notice views the total curve supply of the pool /// @return totalSupply_ the total supply of curve tokens function totalSupply() public view returns (uint256 totalSupply_) { totalSupply_ = curve.totalSupply; } /// @notice views the total allowance one address has to spend from another address /// @param _owner the address of the owner /// @param _spender the address of the spender /// @return allowance_ the amount the owner has allotted the spender function allowance(address _owner, address _spender) public view returns (uint256 allowance_) { allowance_ = curve.allowances[_owner][_spender]; } /// @notice views the total amount of liquidity in the curve in numeraire value and format - 18 decimals /// @return total_ the total value in the curve /// @return individual_ the individual values in the curve function liquidity() public view returns (uint256 total_, uint256[] memory individual_) { return ViewLiquidity.viewLiquidity(curve); } /// @notice view the assimilator address for a derivative /// @return assimilator_ the assimilator address function assimilator(address _derivative) public view returns (address assimilator_) { assimilator_ = curve.assimilators[_derivative].addr; } }
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( Storage.Curve storage curve, address sender, address recipient, uint256 amount ) external returns (bool) { _transfer(curve, sender, recipient, amount); _approve( curve, sender, msg.sender, sub( curve.allowances[sender][msg.sender], amount, 'Curve/insufficient-allowance' ) ); return true; }
12,815,480
./partial_match/4/0x451faE13631bC58B66d04B84a95a1E5d8e14152B/sources/stake.sol
servedDays must == stakedDays here
function _stakePerformance(GlobalsCache memory g, StakeCache memory st, uint256 servedDays) private view returns (uint256 stakeReturn, uint256 payout, uint256 dividends, uint256 penalty, uint256 cappedPenalty) { if (servedDays < st._stakedDays) { (payout, penalty) = _calcPayoutAndEarlyPenalty( g, st._lockedDay, st._stakedDays, servedDays, st._stakeShares ); stakeReturn = st._stakedSuns + payout; dividends = _calcPayoutDividendsReward( st._stakeShares, st._lockedDay, st._lockedDay + servedDays ); payout = _calcPayoutRewards( st._stakeShares, st._lockedDay, st._lockedDay + servedDays ); dividends = _calcPayoutDividendsReward( st._stakeShares, st._lockedDay, st._lockedDay + servedDays ); stakeReturn = st._stakedSuns + payout; penalty = _calcLatePenalty(st._lockedDay, st._stakedDays, st._unlockedDay, stakeReturn); } if (penalty != 0) { if (penalty > stakeReturn) { cappedPenalty = stakeReturn; stakeReturn = 0; cappedPenalty = penalty; stakeReturn -= cappedPenalty; } return (stakeReturn, payout, dividends, penalty, cappedPenalty); }
8,532,508
./partial_match/1/0xa18D3073441B0774a1EFA45Ba9D2E7DA3441DA2F/sources/contracts/proxy/admin.sol
_hypervisor Hypervisor Address _baseLower The lower tick of the base position _baseUpper The upper tick of the base position _limitLower The lower tick of the limit position _limitUpper The upper tick of the limit position _feeRecipient Address of recipient of 10% of earned fees since last rebalance
function rebalance( address _hypervisor, int24 _baseLower, int24 _baseUpper, int24 _limitLower, int24 _limitUpper, address _feeRecipient, uint256[4] memory inMin, uint256[4] memory outMin ) external onlyRebalancer(_hypervisor) { IHypervisor(_hypervisor).rebalance(_baseLower, _baseUpper, _limitLower, _limitUpper, _feeRecipient, inMin, outMin); }
9,150,087
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; // This set of contract is to create a ERC721 token with URI support for each game trade listing // ERC721URIStorage we use here is an OpenZeppelin contract for ERC721 that allows to set URI on token creation contract GameListing is ERC721URIStorage { // Counters for the total supply and balances of all tokens using Counters for Counters.Counter; Counters.Counter private _tokenIds; address contractAddress; // Take the markeplace contract address to deploy the contract constructor(address marketplaceAddress) ERC721("DeGame Australia", "DEGAME") { contractAddress = marketplaceAddress; } // Pass game trading metadata to the createToken function will create a new ERC721 token for the DeGame Trading contract to use // The metadata will be stored in the URI of the token function createGameListing(string memory gameListingDetails) public returns (uint) { _tokenIds.increment(); uint256 newgameID = _tokenIds.current(); _mint(msg.sender, newgameID); _setTokenURI(newgameID, gameListingDetails); setApprovalForAll(contractAddress, true); return newgameID; } // This function is to check if the game listing exist or not function checkGameListing(uint gameID) public view returns (bool) { return _exists(gameID); } // This function is to get the game listing details function getGameListingDetails(uint gameID) public view returns (string memory) { return tokenURI(gameID); } // Martketplace contract can call this function to burn/cancel the game listing function cancelGameListing(uint gameID) public { require(msg.sender == contractAddress); require(checkGameListing(gameID)); _burn(gameID); } function getLastListingID() public view returns (uint) { return _tokenIds.current(); } } // This set of contract is the administrative contract for each game listing // ReentrancyGuard is an OpenZeppelin contract that allows to prevent reentrancy attacks contract DeGameTrading is ReentrancyGuard { // Count and index the item id and total number of items sold using Counters for Counters.Counter; Counters.Counter private _gameIDs; Counters.Counter private _itemsSold; // Payable to the contract deloyer address // Listing fee is 0.1 ether address payable deloyer; uint256 listingPrice = 0.01 ether; // Default deloyer of this contract is whoever deploys it constructor() { deloyer = payable(msg.sender); } // A typical game item contain game id, nft contract address, ERC721 token id, seller address, buyer address, and price struct GameItem { uint gameID; address nftContract; uint256 tokenId; address payable seller; address payable deloyer; uint256 price; } mapping(uint256 => GameItem) private idToGameItem; // Log the game item to the blockchain whenever a new game item is created event GameItemCreated ( uint indexed gameID, address indexed nftContract, uint256 indexed tokenId, address seller, address deloyer, uint256 price ); // Function to get a sepcific game item from the blockchain by passing in the game id function getGameItem(uint256 GameItemID) public view returns (GameItem memory) { return idToGameItem[GameItemID]; } // Function to create a new game item and add log to the blockchain function createGameItem( address nftContract, uint256 tokenId, uint256 price ) public payable nonReentrant { require(price > 0, "Price must be at least 1 wei"); require(msg.value > listingPrice, "Price must be greater than the listing price"); _gameIDs.increment(); uint256 gameID = _gameIDs.current(); idToGameItem[gameID] = GameItem( gameID, nftContract, tokenId, payable(msg.sender), payable(address(0)), price ); IERC721(nftContract).transferFrom(msg.sender, address(this), tokenId); emit GameItemCreated( gameID, nftContract, tokenId, msg.sender, address(0), price ); } // Function to buy a game item from the marketplace by passing in the game id function createMarketSale( address nftContract, uint256 gameID ) public payable nonReentrant { uint price = idToGameItem[gameID].price; uint tokenId = idToGameItem[gameID].tokenId; require(msg.value == price, "Please submit the asking price in order to complete the purchase"); idToGameItem[gameID].seller.transfer(msg.value); IERC721(nftContract).transferFrom(address(this), msg.sender, tokenId); idToGameItem[gameID].deloyer = payable(msg.sender); _itemsSold.increment(); payable(deloyer).transfer(listingPrice); } // Function to get all the game items that is currently listed on the marketplace for sale function fetchGameItems() public view returns (GameItem[] memory) { uint itemCount = _gameIDs.current(); uint unsoldItemCount = _gameIDs.current() - _itemsSold.current(); uint currentIndex = 0; GameItem[] memory items = new GameItem[](unsoldItemCount); for (uint i = 0; i < itemCount; i++) { if (idToGameItem[i + 1].deloyer == address(0)) { uint currentId = i + 1; GameItem storage currentItem = idToGameItem[currentId]; items[currentIndex] = currentItem; currentIndex += 1; } } return items; } // Function to check the game item that you had purchased function fetchMyNFTs() public view returns (GameItem[] memory) { uint totalItemCount = _gameIDs.current(); uint itemCount = 0; uint currentIndex = 0; for (uint i = 0; i < totalItemCount; i++) { if (idToGameItem[i + 1].deloyer == msg.sender) { itemCount += 1; } } GameItem[] memory items = new GameItem[](itemCount); for (uint i = 0; i < totalItemCount; i++) { if (idToGameItem[i + 1].deloyer == msg.sender) { uint currentId = i + 1; GameItem storage currentItem = idToGameItem[currentId]; items[currentIndex] = currentItem; currentIndex += 1; } } return items; } // Features to be added: // 1. Royalties // 2. Chainlink off-chain oracle to fetch Nintendo Switch current game market price // https://docs.chain.link/docs/off-chain-oracle }
Function to check the game item that you had purchased
function fetchMyNFTs() public view returns (GameItem[] memory) { uint totalItemCount = _gameIDs.current(); uint itemCount = 0; uint currentIndex = 0; for (uint i = 0; i < totalItemCount; i++) { if (idToGameItem[i + 1].deloyer == msg.sender) { itemCount += 1; } } GameItem[] memory items = new GameItem[](itemCount); for (uint i = 0; i < totalItemCount; i++) { if (idToGameItem[i + 1].deloyer == msg.sender) { uint currentId = i + 1; GameItem storage currentItem = idToGameItem[currentId]; items[currentIndex] = currentItem; currentIndex += 1; } } return items; }
6,410,289